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
|
|---|---|---|---|---|---|---|---|---|---|
088a0c67588f9334eb8dbed9447055eff3fbfe30
|
example/controllers/football.js
|
example/controllers/football.js
|
'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
function leagueTable_id(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable/" + item.id
return item
})
}
})()
|
'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
function leagueTable_id(id) { // Auto parses id from route parameters
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable/" + item.id
return item
})
}
})()
|
Correct comment on parsing route parameters instead of query
|
Correct comment on parsing route parameters instead of query
|
JavaScript
|
mit
|
CCISEL/connect-controller,CCISEL/connect-controller
|
5a63f87a9bf6fa7c4ce54f7c5f650b85190fd930
|
fetch-browser.js
|
fetch-browser.js
|
(function () {
'use strict';
function fetchPonyfill(options) {
var Promise = options && options.Promise || self.Promise;
var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest;
var global = self;
return (function () {
var self = Object.create(global, {
fetch: {
value: undefined,
writable: true
}
});
// {{whatwgFetch}}
return {
fetch: self.fetch.bind(global),
Headers: self.Headers,
Request: self.Request,
Response: self.Response
};
}());
}
if (typeof define === 'function' && define.amd) {
define(function () {
return fetchPonyfill;
});
} else if (typeof exports === 'object') {
module.exports = fetchPonyfill;
} else {
self.fetchPonyfill = fetchPonyfill;
}
}());
|
(function () {
'use strict';
function fetchPonyfill(options) {
var Promise = options && options.Promise || self.Promise;
var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest;
var global = self;
return (function () {
var self = Object.create(global, {
fetch: {
value: undefined,
writable: true
}
});
// {{whatwgFetch}}
return {
fetch: self.fetch,
Headers: self.Headers,
Request: self.Request,
Response: self.Response
};
}());
}
if (typeof define === 'function' && define.amd) {
define(function () {
return fetchPonyfill;
});
} else if (typeof exports === 'object') {
module.exports = fetchPonyfill;
} else {
self.fetchPonyfill = fetchPonyfill;
}
}());
|
Remove global binding that is now not needed anymore
|
Remove global binding that is now not needed anymore
|
JavaScript
|
mit
|
qubyte/fetch-ponyfill,qubyte/fetch-ponyfill
|
2cb746c292c9c68d04d9393eeccdf398573a84af
|
build/tests/bootstrap.js
|
build/tests/bootstrap.js
|
// Remove the PUBLIC_URL, if defined
process.env.PUBLIC_URL = ''
process.env.INSPIRE_API_URL = 'inspire-api-url'
require('babel-register')()
const { jsdom } = require('jsdom')
const moduleAlias = require('module-alias')
const path = require('path')
moduleAlias.addAlias('common', path.join(__dirname, '../../src'))
const exposedProperties = ['window', 'navigator', 'document']
global.document = jsdom('<!doctype html><html><body></body></html>')
global.window = document.defaultView
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
global.navigator = window.navigator = {
userAgent: 'node.js',
platform: 'node.js',
}
const chai = require('chai')
const chaiEnzyme = require('chai-enzyme')
global.expect = chai.expect
chai.use(chaiEnzyme())
|
const { JSDOM } = require('jsdom')
const moduleAlias = require('module-alias')
const path = require('path')
require('babel-register')()
moduleAlias.addAlias('common', path.join(__dirname, '../../src'))
// Remove the PUBLIC_URL, if defined
process.env.PUBLIC_URL = ''
process.env.INSPIRE_API_URL = 'inspire-api-url'
const jsdom = new JSDOM('<!doctype html><html><body></body></html>')
const exposedProperties = ['window', 'navigator', 'document']
global.window = jsdom.window
global.document = global.window.document
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
global.navigator = window.navigator = {
userAgent: 'node.js',
platform: 'node.js',
}
const chai = require('chai')
const chaiEnzyme = require('chai-enzyme')
global.expect = chai.expect
chai.use(chaiEnzyme())
|
Update JSDOM usage due to API change
|
Update JSDOM usage due to API change
|
JavaScript
|
mit
|
sgmap/inspire,sgmap/inspire
|
c14bea03e77d0b7573ae087c879cadfc3ca9c970
|
firefox/prefs.js
|
firefox/prefs.js
|
user_pref("accessibility.typeaheadfind.flashBar", 0);
user_pref("accessibility.typeaheadfind.prefillwithselection", true);
user_pref("browser.backspace_action", 2);
user_pref("browser.bookmarks.restore_default_bookmarks", false);
user_pref("browser.newtab.url", "about:blank");
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.selfsupport.url", "");
user_pref("browser.showQuitWarning", true);
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.tabs.animate", false);
user_pref("browser.tabs.closeWindowWithLastTab", false);
user_pref("browser.tabs.warnOnClose", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("network.cookie.cookieBehavior", 3);
user_pref("network.cookie.lifetimePolicy", 2);
user_pref("network.http.referer.spoofSource", true);
user_pref("network.http.referer.trimmingPolicy", 2);
user_pref("network.http.referer.XOriginPolicy", 2);
user_pref("toolkit.telemetry.enabled", false);
|
user_pref("accessibility.typeaheadfind.flashBar", 0);
user_pref("accessibility.typeaheadfind.prefillwithselection", true);
user_pref("browser.backspace_action", 2);
user_pref("browser.bookmarks.restore_default_bookmarks", false);
user_pref("browser.newtab.url", "about:blank");
user_pref("browser.readinglist.enabled", false);
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.selfsupport.url", "");
user_pref("browser.showQuitWarning", true);
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.tabs.animate", false);
user_pref("browser.tabs.closeWindowWithLastTab", false);
user_pref("browser.tabs.warnOnClose", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("loop.enabled", false);
user_pref("network.cookie.cookieBehavior", 3);
user_pref("network.cookie.lifetimePolicy", 2);
user_pref("network.http.referer.spoofSource", true);
user_pref("network.http.referer.trimmingPolicy", 2);
user_pref("network.http.referer.XOriginPolicy", 2);
user_pref("readinglist.scheduler.enabled", false);
user_pref("toolkit.telemetry.enabled", false);
|
Disable a few unused features
|
firefox: Disable a few unused features
|
JavaScript
|
mit
|
poiru/dotfiles,poiru/dotfiles,poiru/dotfiles
|
9d43d46eac238af0ac1a038916e6ebe21383fc95
|
gatsby-config.js
|
gatsby-config.js
|
module.exports = {
siteMetadata: {
siteUrl: 'https://chocolate-free.com/',
title: 'Chocolate Free',
},
plugins: [
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: '0w6gaytm0wfv',
accessToken: 'c9414fe612e8c31f402182354c5263f9c6b1f0c611ae5597585cb78692dc2493',
},
},
{
resolve: 'gatsby-plugin-google-analytics',
options: {
trackingId: 'UA-89281107-1',
},
},
{
resolve: 'gatsby-plugin-sitemap'
},
{
resolve: 'gatsby-plugin-manifest',
options: {
'name': 'Chocolate-free',
'short_name': 'ChocoFree',
'start_url': '/',
'background_color': '#e8e8e8',
'icons': [
{
'src': '/android-chrome-192x192.png',
'sizes': '192x192',
'type': 'image/png'
},
{
'src': '/android-chrome-512x512.png',
'sizes': '512x512',
'type': 'image/png'
}
],
'theme_color': '#e8e8e8',
'display': 'standalone'
}
},
'gatsby-plugin-offline',
'gatsby-transformer-remark',
'gatsby-plugin-sass'
],
}
|
module.exports = {
siteMetadata: {
siteUrl: 'https://chocolate-free.com/',
title: 'Chocolate Free',
},
plugins: [
{
resolve: 'gatsby-source-contentful',
options: {
spaceId: process.env.CHOCOLATE_FREE_CF_SPACE,
accessToken: process.env.CHOCOLATE_FREE_CF_TOKEN
},
},
{
resolve: 'gatsby-plugin-google-analytics',
options: {
trackingId: 'UA-89281107-1',
},
},
{
resolve: 'gatsby-plugin-sitemap'
},
{
resolve: 'gatsby-plugin-manifest',
options: {
'name': 'Chocolate-free',
'short_name': 'ChocoFree',
'start_url': '/',
'background_color': '#e8e8e8',
'icons': [
{
'src': '/android-chrome-192x192.png',
'sizes': '192x192',
'type': 'image/png'
},
{
'src': '/android-chrome-512x512.png',
'sizes': '512x512',
'type': 'image/png'
}
],
'theme_color': '#e8e8e8',
'display': 'standalone'
}
},
'gatsby-plugin-offline',
'gatsby-transformer-remark',
'gatsby-plugin-sass'
],
}
|
Replace api key with env vars
|
Replace api key with env vars
|
JavaScript
|
apache-2.0
|
Khaledgarbaya/chocolate-free-website,Khaledgarbaya/chocolate-free-website
|
930bcf06b7cca0993d0c13250b1ae7bd484643ba
|
src/js/routes.js
|
src/js/routes.js
|
'use strict';
angular.module('mission-control').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
// For unmatched routes
$urlRouterProvider.otherwise('/');
// Application routes
$stateProvider
.state('index', {
url: '/',
templateUrl: 'views/overview.html',
controller: 'OverviewCtrl'
})
.state('agenda', {
url: '/agenda',
templateUrl: 'views/agenda.html',
controller: 'AgendaCtrl'
})
.state('events', {
url: '/events',
templateUrl: 'views/events.html',
controller: 'EventsCtrl'
})
.state('members', {
url: '/members',
templateUrl: 'views/members.html',
controller: 'MembersCtrl'
})
.state('sponsors', {
url: '/sponsors',
templateUrl: 'views/sponsors.html',
controller: 'SponsorsCtrl'
})
.state('tasks', {
url: '/tasks',
templateUrl: 'views/tasks.html',
controller: 'TasksCtrl'
});
}
]);
|
'use strict';
angular.module('mission-control').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
// For unmatched routes
$urlRouterProvider.otherwise('/');
// Application routes
$stateProvider
.state('index', {
url: '/',
templateUrl: 'views/overview.html',
controller: 'OverviewCtrl'
})
.state('agenda', {
url: '/agenda',
templateUrl: 'views/agenda.html',
controller: 'AgendaCtrl'
})
.state('events', {
url: '/events',
templateUrl: 'views/events.html',
controller: 'EventsCtrl'
})
.state('members', {
url: '/members',
templateUrl: 'views/members.html',
controller: 'MembersCtrl'
})
.state('mentors', {
url: '/mentors',
templateUrl: 'views/mentors.html',
controller: 'MentorsCtrl'
})
.state('sponsors', {
url: '/sponsors',
templateUrl: 'views/sponsors.html',
controller: 'SponsorsCtrl'
})
.state('tasks', {
url: '/tasks',
templateUrl: 'views/tasks.html',
controller: 'TasksCtrl'
});
}
]);
|
Add mentors route to router
|
Add mentors route to router
|
JavaScript
|
mit
|
craigcabrey/mission-control,craigcabrey/mission-control
|
b40447a79ed4d94ba05e379e4192556c271a1e4b
|
test/browser.spec.js
|
test/browser.spec.js
|
var expect = require('chai').expect;
var request = require('supertest');
var http = require('http');
var cookie = require('../lib/browser');
describe('server-side cookie', function() {
describe('.set', function() {
it('should work', function() {
cookie.set('yolo', 'swag');
expect(cookie.get('yolo')).to.equal('swag');
});
});
describe('.remove', function() {
it('should work', function() {
cookie.set('yolo', 'swag');
expect(cookie.get('yolo')).to.equal('swag');
cookie.remove('yolo');
expect(cookie.get('yolo')).to.be.undefined;
});
});
});
|
var expect = require('chai').expect;
var request = require('supertest');
var http = require('http');
var cookie = require('../lib/browser');
describe('server-side cookie', function() {
describe('.get', function() {
it('should work', function() {
expect(cookie.get('swag_swag_swag_')).to.be.undefined;
});
});
describe('.set', function() {
it('should work', function() {
cookie.set('yolo', 'swag');
expect(cookie.get('yolo')).to.equal('swag');
});
});
describe('.remove', function() {
it('should work', function() {
cookie.set('yolo', 'swag');
expect(cookie.get('yolo')).to.equal('swag');
cookie.remove('yolo');
expect(cookie.get('yolo')).to.be.undefined;
});
});
});
|
Add simple test case for browser `.get`
|
Add simple test case for browser `.get`
|
JavaScript
|
mit
|
srph/cookie-machine
|
09c0f85065d496bec9e869f3ec170648b99f77c9
|
lib/middleware/request_proxy.js
|
lib/middleware/request_proxy.js
|
// Copyright (C) 2007-2014, GoodData(R) Corporation.
var httpProxy = require('http-proxy');
module.exports = function(host) {
var currentHost, currentPort;
var proxy = new httpProxy.RoutingProxy({
target: {
https: true
}
});
var requestProxy = function(req, res, next) {
// Because backend does not answer without set content length
if (req.method === 'DELETE') {
// Only set content-length to zero if not already specified
req.headers['content-length'] = req.headers['content-length'] || '0';
}
// White labeled resources are based on host header
req.headers['host'] = currentHost + (currentPort!==443 ? ':'+currentPort : '');
// Remove Origin header so it's not evaluated as cross-domain request
req.headers['origin'] = null;
// Proxy received request to curret backend endpoint
proxy.proxyRequest(req, res, {
host: currentHost,
port: currentPort,
target: {
// don't choke on self-signed certificates used by *.getgooddata.com
rejectUnauthorized: false
}
});
};
requestProxy.proxy = proxy;
requestProxy.setHost = function(value) {
var splithost = value ? value.split(/:/) : '';
currentHost = splithost[0];
currentPort = parseInt(splithost[1] || '443', 10);
};
// set the host/port combination
requestProxy.setHost(host);
return requestProxy;
};
|
// Copyright (C) 2007-2014, GoodData(R) Corporation.
var httpProxy = require('http-proxy');
module.exports = function(host) {
var currentHost, currentPort;
var proxy = new httpProxy.RoutingProxy({
target: {
https: true
}
});
var requestProxy = function(req, res, next) {
// Because backend does not answer without set content length
if (req.method === 'DELETE') {
// Only set content-length to zero if not already specified
req.headers['content-length'] = req.headers['content-length'] || '0';
}
// White labeled resources are based on host header
req.headers['host'] = currentHost + (currentPort!==443 ? ':'+currentPort : '');
// Remove Origin header so it's not evaluated as cross-domain request
req.headers['origin'] = null;
// To prevent CSRF
req.headers['referer'] = 'https://' + host;
// Proxy received request to curret backend endpoint
proxy.proxyRequest(req, res, {
host: currentHost,
port: currentPort,
target: {
// don't choke on self-signed certificates used by *.getgooddata.com
rejectUnauthorized: false
}
});
};
requestProxy.proxy = proxy;
requestProxy.setHost = function(value) {
var splithost = value ? value.split(/:/) : '';
currentHost = splithost[0];
currentPort = parseInt(splithost[1] || '443', 10);
};
// set the host/port combination
requestProxy.setHost(host);
return requestProxy;
};
|
Set referer header to prevent CSRF
|
Set referer header to prevent CSRF
|
JavaScript
|
bsd-3-clause
|
gooddata/grunt-grizzly,crudo/grunt-grizzly
|
6e6ec8c967ddb486a979a267016e7eb2b5c7ff4d
|
eachSeries.js
|
eachSeries.js
|
import when from 'when';
let
openFiles = ['a.js', 'b.js', 'c.js'],
saveFile = (file) => {
console.log('saveFile', file);
return new Promise((resolve, reject) => {
setTimeout(
() => {
console.log('timeout', file);
resolve(file);
},
2000
);
});
};
let results = [];
openFiles.reduce(
(promise, file) => {
return promise
.then(saveFile.bind(null, file))
.then((result) => {
results.push(result);
return results;
});
},
Promise.resolve()
)
.then((...args) => {
console.log('promise done', args);
})
.catch((error) => {
console.log('promise error', error);
});
when.reduce(openFiles, (results, file) => {
return saveFile(file)
.then((result) => {
results.push(result);
return results;
});
}, [])
.then((...args) => {
console.log('when done', args);
})
.catch((error) => {
console.log('when error', error);
});
|
import when from 'when';
let
openFiles = ['a.js', 'b.js', 'c.js'],
saveFile = (file) => {
console.log('saveFile', file);
return new Promise((resolve, reject) => {
setTimeout(
() => {
console.log('timeout', file);
resolve(file);
},
2000
);
});
};
openFiles.reduce(
(promise, file) => promise.then((results) => {
return saveFile(file)
.then((result) => {
results.push(result);
return results;
});
}),
Promise.resolve([])
)
.then((...args) => {
console.log('promise done', args);
})
.catch((error) => {
console.log('promise error', error);
});
when.reduce(openFiles, (results, file) => {
return saveFile(file)
.then((result) => {
results.push(result);
return results;
});
}, [])
.then((...args) => {
console.log('when done', args);
})
.catch((error) => {
console.log('when error', error);
});
|
Update each series results to be embedded in the reduce
|
Update each series results to be embedded in the reduce
|
JavaScript
|
mit
|
jgornick/asyncp
|
f7d374595d08b3421f0da67932f5fcbb7a092e8d
|
src/lib/watch.js
|
src/lib/watch.js
|
"use strict";
var db = require("./firebase");
// Ensure the updated timestamp is always accurate-ish
module.exports = function(ref) {
ref.on("child_changed", function(snap) {
var key = snap.key(),
auth;
// Avoid looping forever
if(key === "updated_at" || key === "updated_by") {
return;
}
auth = db.getAuth();
// Clean up any old updated timestamps floating around
ref.child("updated").remove();
ref.child("updated_at").set(db.TIMESTAMP);
ref.child("updated_by").set(auth.uid);
});
};
|
"use strict";
var db = require("./firebase");
// Ensure the updated timestamp is always accurate-ish
module.exports = function(ref) {
ref.on("child_changed", function(snap) {
var key = snap.key(),
auth;
// Avoid looping forever
if(key === "updated_at" || key === "updated_by") {
return;
}
auth = db.getAuth();
// Clean up any old updated timestamps floating around
ref.child("updated").remove();
ref.update({
updated_at : db.TIMESTAMP,
updated_by : auth.uid
});
});
};
|
Convert two .set() calls into one .update()
|
Convert two .set() calls into one .update()
|
JavaScript
|
mit
|
tivac/crucible,Ryan-McMillan/crucible,kevinkace/crucible,tivac/anthracite,kevinkace/crucible,tivac/anthracite,tivac/crucible,Ryan-McMillan/crucible
|
560f6420d7681201cb404eb39e80f3000102e53c
|
lib/_memoize-watcher.js
|
lib/_memoize-watcher.js
|
'use strict';
var noop = require('es5-ext/function/noop')
, assign = require('es5-ext/object/assign')
, memoize = require('memoizee')
, ee = require('event-emitter')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
if (fn.memoized) return fn;
memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = ee.pipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) watcher.close();
};
return emitter;
};
factory.clear = memoized.clear;
factory.memoized = true;
return factory;
};
|
'use strict';
var noop = require('es5-ext/function/noop')
, assign = require('es5-ext/object/assign')
, memoize = require('memoizee')
, ee = require('event-emitter')
, eePipe = require('event-emitter/lib/pipe')
, deferred = require('deferred')
, isPromise = deferred.isPromise;
module.exports = function (fn/*, options*/) {
var factory, memoized;
if (fn.memoized) return fn;
memoized = memoize(fn, assign(Object(arguments[1]), { refCounter: true }));
factory = function () {
var watcher, emitter, pipe, args, def;
args = arguments;
watcher = memoized.apply(this, arguments);
if (isPromise(watcher)) {
def = deferred();
emitter = def.promise;
def.resolve(watcher);
} else {
emitter = ee();
}
pipe = eePipe(watcher, emitter);
emitter.close = function () {
emitter.close = noop;
pipe.close();
if (memoized.clearRef.apply(this, args)) watcher.close();
};
return emitter;
};
factory.clear = memoized.clear;
factory.memoized = true;
return factory;
};
|
Update up to changes in event-emitter package
|
Update up to changes in event-emitter package
|
JavaScript
|
isc
|
medikoo/fs2
|
79c32b103f5cbd76b5f9d287c89372704cfbc35e
|
bin/setup.js
|
bin/setup.js
|
#!/usr/bin/env node
// Must symlink the generator from xtc's modules up to the project's modules.
// Else Yeoman won't find it.
var path = require('path')
fs = require('fs')
;
// process.cwd() == __dirname
if ('install' === process.env.npm_lifecycle_event) {
try {
fs.symlinkSync(path.join(process.cwd(), '/node_modules/generator-xtc'), path.join(process.cwd(), '../generator-xtc'), 'dir');
console.log('symlink: generator-xtc into node_modules\n')
} catch (e) {
if (e.code === 'EEXIST') {
console.info('symlink: generator-xtc already already exists node_modules\n');
}
else {
throw e;
}
}
}
// And of course we remove it again before xtc is uninstalled
else if ('uninstall' === process.env.npm_lifecycle_event) {
try {
fs.unlinkSync(path.join(process.cwd(), '../generator-xtc'), 'dir');
console.log('symlink: removed generator-xtc from node_modules\n')
} catch (e) {
if (e.code !== 'ENOENT') {
console.info('symlink: Unable to remove generator-xtc from node_modules\n');
}
throw e;
}
}
|
#!/usr/bin/env node
// Must symlink the generator from xtc's modules up to the project's modules.
// Else Yeoman won't find it.
var path = require('path')
fs = require('fs')
;
// process.cwd() == __dirname
if ('install' === process.env.npm_lifecycle_event) {
try {
fs.symlinkSync(path.join(process.cwd(), '/node_modules/generator-xtc'), path.join(process.cwd(), '../generator-xtc'), 'dir');
console.log('symlink: generator-xtc into node_modules\n')
} catch (e) {
if (e.code === 'EEXIST') {
console.info('symlink: generator-xtc already exists in node_modules\n');
}
else {
throw e;
}
}
}
// And of course we remove it again before xtc is uninstalled
else if ('uninstall' === process.env.npm_lifecycle_event) {
try {
fs.unlinkSync(path.join(process.cwd(), '../generator-xtc'), 'dir');
console.log('symlink: removed generator-xtc from node_modules\n')
} catch (e) {
if (e.code !== 'ENOENT') {
console.info('symlink: Unable to remove generator-xtc from node_modules\n');
}
throw e;
}
}
|
Fix typo in error message
|
Fix typo in error message
|
JavaScript
|
mit
|
MarcDiethelm/xtc
|
24bd88bb2965515ac7f9ffecde850e7f63ce23a5
|
app/scripts/app/routes/items.js
|
app/scripts/app/routes/items.js
|
var ItemsRoute = Em.Route.extend({
model: function (params) {
return this.api.fetchAll('items', 'groups', params.group_id);
},
setupController: function (controller, model) {
// allow sub-routes to access the GroupId since it seems the dynamic segment is not available otherwise
controller.set('GroupId', model.get('firstObject.GroupId'));
this._super(controller, model);
},
renderTemplate: function () {
this.render('items', {
into: 'application',
outlet: 'items',
});
},
actions: {
refresh: function () {
this.refresh();
return true;
}
}
});
export default ItemsRoute;
|
var ItemsRoute = Em.Route.extend({
model: function (params) {
this.set('currentGroupId', parseInt(params.group_id, 10));
return this.api.fetchAll('items', 'groups', params.group_id);
},
setupController: function (controller, model) {
// allow sub-routes to access the GroupId since it seems the dynamic segment is not available otherwise
controller.set('GroupId', this.get('currentGroupId'));
this._super(controller, model);
},
renderTemplate: function () {
this.render('items', {
into: 'application',
outlet: 'items',
});
},
actions: {
refresh: function () {
this.refresh();
return true;
}
}
});
export default ItemsRoute;
|
Fix setting GroupId on ItemsController when its model is empty
|
Fix setting GroupId on ItemsController when its model is empty
|
JavaScript
|
mit
|
darvelo/wishlist,darvelo/wishlist
|
51e2104a004ca63fb1e7f5262e61441b558bd288
|
packages/react-native-version-check-expo/src/ExpoVersionInfo.js
|
packages/react-native-version-check-expo/src/ExpoVersionInfo.js
|
let RNVersionCheck;
if (process.env.RNVC_ENV === 'test') {
RNVersionCheck = {
country: 'ko',
packageName: 'com.reactnative.versioncheck',
currentBuildNumber: 1,
currentVersion: '0.0.1',
};
} else {
const { Platform } = require('react-native');
const { Constants, Util } = require('expo');
const { manifest = {} } = Constants;
const {
version = null,
android: { versionCode = null, package: androidPackageName = null } = {},
ios: { bundleIdentifier = null, buildNumber = null } = {},
} = manifest;
RNVersionCheck = {
currentVersion: version,
country: Util.getCurrentDeviceCountryAsync(),
currentBuildNumber: Platform.select({
android: versionCode,
ios: buildNumber,
}),
packageName: Platform.select({
android: androidPackageName,
ios: bundleIdentifier,
}),
};
}
const COUNTRY = RNVersionCheck.country;
const PACKAGE_NAME = RNVersionCheck.packageName;
const CURRENT_BUILD_NUMBER = RNVersionCheck.currentBuildNumber;
const CURRENT_VERSION = RNVersionCheck.currentVersion;
export default {
getCountry: () => Promise.resolve(COUNTRY),
getPackageName: () => PACKAGE_NAME,
getCurrentBuildNumber: () => CURRENT_BUILD_NUMBER,
getCurrentVersion: () => CURRENT_VERSION,
};
|
let RNVersionCheck;
if (process.env.RNVC_ENV === 'test') {
RNVersionCheck = {
country: 'ko',
packageName: 'com.reactnative.versioncheck',
currentBuildNumber: 1,
currentVersion: '0.0.1',
};
} else {
const { Platform } = require('react-native');
const { Constants, Localization, Util } = require('expo');
const { manifest = {} } = Constants;
const {
version = null,
android: { versionCode = null, package: androidPackageName = null } = {},
ios: { bundleIdentifier = null, buildNumber = null } = {},
} = manifest;
RNVersionCheck = {
currentVersion: version,
country: `${Constants.expoVersion < 26 ? Util.getCurrentDeviceCountryAsync : Localization.getCurrentDeviceCountryAsync()}`,
currentBuildNumber: Platform.select({
android: versionCode,
ios: buildNumber,
}),
packageName: Platform.select({
android: androidPackageName,
ios: bundleIdentifier,
}),
};
}
const COUNTRY = RNVersionCheck.country;
const PACKAGE_NAME = RNVersionCheck.packageName;
const CURRENT_BUILD_NUMBER = RNVersionCheck.currentBuildNumber;
const CURRENT_VERSION = RNVersionCheck.currentVersion;
export default {
getCountry: () => Promise.resolve(COUNTRY),
getPackageName: () => PACKAGE_NAME,
getCurrentBuildNumber: () => CURRENT_BUILD_NUMBER,
getCurrentVersion: () => CURRENT_VERSION,
};
|
Use `Localization.getCurrentDeviceCountryAsync` if its version of expo is over 26 since it's deprecated.
|
Use `Localization.getCurrentDeviceCountryAsync` if its version of expo is over 26 since it's deprecated.
ref:https://github.com/expo/expo-docs/tree/master/versions/v26.0.0/sdk
|
JavaScript
|
mit
|
kimxogus/react-native-version-check,kimxogus/react-native-version-check,kimxogus/react-native-version-check
|
c1b67784c26c4c2658446dddbed92ef44b8bd84a
|
web/src/js/app/views/ViewportView.js
|
web/src/js/app/views/ViewportView.js
|
cinema.views.ViewportView = Backbone.View.extend({
initialize: function () {
this.$el.html(cinema.app.templates.viewport());
this.camera = new cinema.models.CameraModel({
info: this.model
});
this.renderView = new cinema.views.VisualizationCanvasWidget({
el: this.$('.c-app-renderer-container'),
model: this.model,
camera: this.camera
}).render();
this.mouseInteractor = new cinema.utilities.RenderViewMouseInteractor({
renderView: this.renderView,
camera: this.camera
}).enableMouseWheelZoom({
maxZoomLevel: 10,
zoomIncrement: 0.05,
invertControl: false
}).enableDragPan({
keyModifiers: cinema.keyModifiers.SHIFT
}).enableDragRotation({
keyModifiers: null
});
this.listenTo(this.camera, 'change', this._refreshCamera);
},
updateQuery: function (query) {
this.renderView.updateQuery(query);
},
_refreshCamera: function () {
this.renderView.showViewpoint();
},
});
|
cinema.views.ViewportView = Backbone.View.extend({
initialize: function (opts) {
this.$el.html(cinema.app.templates.viewport());
this.camera = opts.camera || new cinema.models.CameraModel({
info: this.model
});
this.renderView = new cinema.views.VisualizationCanvasWidget({
el: this.$('.c-app-renderer-container'),
model: this.model,
camera: this.camera
}).render();
this.mouseInteractor = new cinema.utilities.RenderViewMouseInteractor({
renderView: this.renderView,
camera: this.camera
}).enableMouseWheelZoom({
maxZoomLevel: 10,
zoomIncrement: 0.05,
invertControl: false
}).enableDragPan({
keyModifiers: cinema.keyModifiers.SHIFT
}).enableDragRotation({
keyModifiers: null
});
this.listenTo(this.camera, 'change', this._refreshCamera);
},
updateQuery: function (query) {
this.renderView.updateQuery(query);
},
_refreshCamera: function () {
this.renderView.showViewpoint();
}
});
|
Allow viewport to be initialized with a pre-existing camera model
|
Allow viewport to be initialized with a pre-existing camera model
|
JavaScript
|
bsd-3-clause
|
Kitware/cinema,Kitware/cinema,Kitware/cinema,Kitware/cinema
|
1c7c553128fcc842f394c429dfc28dbce934fb86
|
pegasus/sites.v3/code.org/public/js/applab-docs.js
|
pegasus/sites.v3/code.org/public/js/applab-docs.js
|
/*global CodeMirror*/
$(function() {
$('pre').each(function() {
var preElement = $(this);
var code = dedent(preElement.text()).trim();
preElement.empty();
CodeMirror(this, {
value: code,
mode: 'javascript',
lineNumbers: !preElement.is('.inline'),
readOnly: true
});
});
$("a[href^='http']").attr("target", "_blank");
});
function getIndent(str) {
var matches = str.match(/^[\s\\t]*/gm);
var indent = matches[0].length;
for (var i = 1; i < matches.length; i++) {
indent = Math.min(matches[i].length, indent);
}
return indent;
}
function dedent(str, pattern) {
var indent = getIndent(str);
var reg;
if (indent === 0) {
return str;
}
if (typeof pattern === 'string') {
reg = new RegExp('^' + pattern, 'gm');
} else {
reg = new RegExp('^[ \\t]{' + indent + '}', 'gm');
}
return str.replace(reg, '');
}
|
/*global CodeMirror*/
$(function() {
$('pre').each(function() {
var preElement = $(this);
var code = dedent(preElement.text()).trim();
preElement.empty();
CodeMirror(this, {
value: code,
mode: 'javascript',
lineNumbers: !preElement.is('.inline'),
readOnly: true
});
});
$("a[href^='http']").attr("target", "_blank");
rewrite_urls();
});
/**
* Our x-frame-options require that any page that is embedded
* in an iframe include embedded as a query arg.
*/
function rewrite_urls() {
var is_embedded = window.location.href.endsWith("embedded");
if (!is_embedded) {
return;
}
$('a').each(function () {
var a = this;
var href = $(a).attr('href');
if (href.startsWith("/applab/docs")) {
var new_href = href;
if (href.indexOf("?") > -1) {
new_href += "&embedded";
} else {
new_href += "?embedded";
}
$(a).attr('href', new_href);
}
});
}
function getIndent(str) {
var matches = str.match(/^[\s\\t]*/gm);
var indent = matches[0].length;
for (var i = 1; i < matches.length; i++) {
indent = Math.min(matches[i].length, indent);
}
return indent;
}
function dedent(str, pattern) {
var indent = getIndent(str);
var reg;
if (indent === 0) {
return str;
}
if (typeof pattern === 'string') {
reg = new RegExp('^' + pattern, 'gm');
} else {
reg = new RegExp('^[ \\t]{' + indent + '}', 'gm');
}
return str.replace(reg, '');
}
|
Rewrite documentation urls to forward on the embedded flag
|
Rewrite documentation urls to forward on the embedded flag
|
JavaScript
|
apache-2.0
|
rvarshney/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,pickettd/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,dillia23/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,rvarshney/code-dot-org,rvarshney/code-dot-org,pickettd/code-dot-org,rvarshney/code-dot-org,pickettd/code-dot-org,dillia23/code-dot-org,dillia23/code-dot-org,dillia23/code-dot-org,dillia23/code-dot-org
|
45c28fca5c5bfad96691fb61b71967f3eb38ffe6
|
brainfuck.js
|
brainfuck.js
|
(function(global) {
'use strict';
(function(id) {
var i, j;
var tab = document.getElementById(id);
var thead = tab.querySelector('thead');
var tbody = tab.querySelector('tbody');
var tr, th, td;
// tr = document.createElement('tr');
// th = document.createElement('td');
// tr.appendChild(th);
// for (i = 0; i < 30; i++) {
// th = document.createElement('th');
// th.textContent = i + 1;
// tr.appendChild(th);
// }
// thead.appendChild(tr);
for (i = 0; i < 3; i++) {
tr = document.createElement('tr');
// th = document.createElement('th');
// th.textContent = i + 1;
// tr.appendChild(th);
for (j = 0; j < 30; j++) {
td = document.createElement('td');
td.textContent = 0;
tr.appendChild(td);
}
tbody.appendChild(tr);
}
})('rams');
})(this)
|
(function(global) {
'use strict';
(function(id) {
var i, j;
var tab = document.getElementById(id);
var thead = tab.querySelector('thead');
var tbody = tab.querySelector('tbody');
var tr, th, td;
// tr = document.createElement('tr');
// th = document.createElement('td');
// tr.appendChild(th);
// for (i = 0; i < 30; i++) {
// th = document.createElement('th');
// th.textContent = i + 1;
// tr.appendChild(th);
// }
// thead.appendChild(tr);
for (i = 0; i < 3; i++) {
tr = document.createElement('tr');
tr.id = "row-" + i;
// th = document.createElement('th');
// th.textContent = i + 1;
// tr.appendChild(th);
for (j = 0; j < 30; j++) {
td = document.createElement('td');
td.textContent = 0;
td.id = "cell-" + (i * 30 + j);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
})('rams');
})(this)
|
Add ids to the markup
|
Add ids to the markup
|
JavaScript
|
mit
|
Lexicality/esolang,Lexicality/esolang
|
2cdd929e7ee6924387e0f96a84c080d111de6604
|
config/secrets.js
|
config/secrets.js
|
module.exports = {
db: process.env.MONGODB || process.env.MONGOHQ_URL || 'mongodb://localhost:27017/gamekeller',
sessionSecret: process.env.SESSION_SECRET || 'gkdevel'
}
|
module.exports = {
db: process.env.MONGODB || 'mongodb://localhost:27017/gamekeller',
sessionSecret: process.env.SESSION_SECRET || 'gkdevel'
}
|
Remove support for MONGOHQ_URL env variable
|
Remove support for MONGOHQ_URL env variable
|
JavaScript
|
mit
|
gamekeller/next,gamekeller/next
|
790b051f536065f97da5699f9d9332391d4ec97a
|
config/targets.js
|
config/targets.js
|
/* eslint-env node */
module.exports = {
browsers: [
'ie 9',
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
]
};
|
/* eslint-env node */
// Which browsers are returned can be found at http://browserl.ist/
module.exports = {
browsers: [
'last 1 edge versions',
'last 1 chrome versions',
'firefox esr', //actually points to the last 2 ESR releases as they overlap
'last 1 safari versions',
'last 1 ios versions',
'last 1 android versions',
]
};
|
Drop support for older browsers
|
Drop support for older browsers
By only targeting modern evergreen browsers in our build we can
significantly reduce the amount of extra code we generate to be
compatible with older browsers. This will make our application smaller
to download and faster to parse.
|
JavaScript
|
mit
|
thecoolestguy/frontend,thecoolestguy/frontend,djvoa12/frontend,ilios/frontend,dartajax/frontend,jrjohnson/frontend,dartajax/frontend,ilios/frontend,jrjohnson/frontend,djvoa12/frontend
|
f5f96e1458e43f2360f16297b8e52eb71c666d8d
|
index.js
|
index.js
|
var aglio = require('aglio');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function (options) {
'use strict';
// Mixes in default options.
options = defaults(options || {}, {
compress: false,
paths: []
});
function transform(file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file); // pass along
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-aglio', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
// Clones the options object.
var opts = defaults({
theme: 'default'
}, options);
// Injects the path of the current file.
opts.filename = file.path;
// Inject includePath for relative includes
opts.includePath = opts.includePath || path.dirname(opts.filename);
aglio.render(str, opts, function (err, html) {
if (err) {
self.emit('error', new PluginError('gulp-aglio', err));
} else {
file.contents = new Buffer(html);
file.path = gutil.replaceExtension(file.path, '.html');
self.push(file);
}
next();
});
}
return through2.obj(transform);
};
|
var aglio = require('aglio');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function (options) {
'use strict';
// Mixes in default options.
options = defaults(options || {}, {
compress: false,
paths: []
});
function transform(file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file); // pass along
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-aglio', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
// Clones the options object.
var opts = defaults({
theme: 'default'
}, options);
// Injects the path of the current file.
opts.filename = file.path;
// Inject includePath for relative includes
opts.includePath = opts.includePath || path.dirname(opts.filename);
try {
aglio.render(str, opts, function (err, html) {
if (err) {
self.emit('error', new PluginError('gulp-aglio', err));
} else {
file.contents = new Buffer(html);
file.path = gutil.replaceExtension(file.path, '.html');
self.push(file);
}
next();
});
} catch(err) {
self.emit("error", new PluginError("gulp-aglio", err));
}
}
return through2.obj(transform);
};
|
Fix error when files are not found
|
:bug: Fix error when files are not found
Using include syntax with a wrong path resulted in a crash without emitting an error message.
|
JavaScript
|
mit
|
nnnnathann/gulp-aglio,nnnnathann/gulp-aglio
|
43b808affcd475e7ad94e4f494c306334323dbb3
|
index.js
|
index.js
|
const getJSON = require('get-json');
const overpass = 'http://overpass-api.de/api/interpreter?data=';
const query = '[out:json];way[%22highway%22](around:50,51.424037,-0.148666);out;';
getJSON(`${overpass}${query}`, (err, result) => {
if (err) console.log(err);
console.log(result);
});
|
const getJSON = require('get-json');
const overpass = 'http://overpass-api.de/api/interpreter?data=';
const lat = 51.424037;
const long = -0.148666;
const distance = 50;
const query = `[out:json]; way["highway"](around:${distance},${lat},${long}); out;`;
getJSON(`${overpass}${query}`, (err, result) => {
if (err) console.log(err);
console.log(result);
});
|
Use templates to cleanup query
|
Use templates to cleanup query
|
JavaScript
|
mit
|
mkhalila/nearest-roads
|
74f1842a096c184982a94d4fc5a95c1a90d18a63
|
index.js
|
index.js
|
var qs = require('querystring')
module.exports = function (network, url, opts) {
opts = opts || {}
if (!linkfor[network]) throw new Error('Unsupported network ' + network)
return linkfor[network](url, opts)
}
var linkfor = {
facebook: function (url, opts) {
var share = {
u: url
}
if (opts.t) share.t = opts.t
return 'https://www.facebook.com/sharer/sharer.php?' + qs.stringify(share)
},
googleplus: function (url, opts) {
var share = {
url: url
}
return 'https://plus.google.com/share?' + qs.stringify(share)
},
pinterest: function (url, opts) {
var share = {
url: url
}
if (opts.media) share.media = opts.media
if (opts.description) share.description = opts.description
return 'http://pinterest.com/pin/create/button/?' + qs.stringify(share)
},
twitter: function (url, opts) {
var share = {
source: url
}
if (opts.text) share.text = opts.text
if (opts.via) share.via = opts.via
return 'https://twitter.com/intent/tweet?' + qs.stringify(share)
}
}
|
var qs = require('querystring')
module.exports = function (network, url, opts) {
opts = opts || {}
if (!linkfor[network]) throw new Error('Unsupported network ' + network)
return linkfor[network](url, opts)
}
var linkfor = {
facebook: function (url, opts) {
var share = {
u: url
}
if (opts.t) share.t = opts.t
return 'https://www.facebook.com/sharer/sharer.php?' + qs.stringify(share)
},
googleplus: function (url, opts) {
var share = {
url: url
}
return 'https://plus.google.com/share?' + qs.stringify(share)
},
pinterest: function (url, opts) {
var share = {
url: url
}
if (opts.media) share.media = opts.media
if (opts.description) share.description = opts.description
return 'http://pinterest.com/pin/create/button/?' + qs.stringify(share)
},
twitter: function (url, opts) {
var share = {
source: url
}
if (opts.text) share.text = opts.text
if (opts.via) share.via = opts.via
return 'https://twitter.com/intent/tweet?' + qs.stringify(share)
}
}
linkfor['google+'] = linkfor.googleplus
|
Add google+ as alias for googleplus
|
Add google+ as alias for googleplus
|
JavaScript
|
mit
|
tableflip/share-my-url
|
64c4b12d5300c2a52b56b150f7202757c4d7c958
|
index.js
|
index.js
|
var _ = require('lodash');
var postcss = require('postcss');
var SEProperties = require('swedish-css-properties');
var SEValues = require('swedish-css-values');
module.exports = postcss.plugin('postcss-swedish-stylesheets', function (opts) {
opts = opts || {
properties: {},
values: {}
};
if (_.isObject(opts.properties)) {
SEProperties = _.merge(SEProperties, opts.properties);
}
if (_.isObject(opts.values)) {
SEValues = _.merge(SEValues, opts.values);
}
// Work with options here
return function (css) {
css.walkDecls(function transformDecl(decl) {
// Properties
_.forEach(SEProperties, function (value, key) {
if (decl.prop === value) {
decl.prop = key;
}
});
// Values
_.forEach(SEValues, function (value, key) {
decl.value = decl.value.replace(value, key);
});
// Important
if (decl.value.indexOf('!viktigt') >= 0) {
decl.value = decl.value.replace(/\s*!viktigt\s*/, '');
decl.important = true;
}
});
};
});
|
const _ = require('lodash');
const SEProperties = require('swedish-css-properties');
const SEValues = require('swedish-css-values');
const postcssSwedishStylesheets = (opts = {}) => {
if (_.isObject(opts.properties)) {
_.merge(SEProperties, opts.properties);
}
if (_.isObject(opts.values)) {
_.merge(SEValues, opts.values);
}
return {
postcssPlugin: 'postcss-swedish-stylesheets',
Once(root) {
root.walkDecls((decl) => {
// Properties
_.forEach(SEProperties, (value, key) => {
if (decl.prop === value) {
decl.prop = key;
}
});
// Values
_.forEach(SEValues, (value, key) => {
decl.value = decl.value.replace(value, key);
});
// Important
if (decl.value.indexOf('!viktigt') >= 0) {
decl.value = decl.value.replace(/\s*!viktigt\s*/, '');
decl.important = true;
}
});
},
};
};
module.exports.postcss = true;
module.exports = postcssSwedishStylesheets;
|
Update plugin to use PostCSS 8
|
feat: Update plugin to use PostCSS 8
|
JavaScript
|
mit
|
johnie/postcss-swedish-stylesheets
|
a2ac0281ef8e4a489b87553edec11f650418ef83
|
index.js
|
index.js
|
const express = require('express');
const shortUrlController = require('./lib/short-url-controller.js');
const stubController = require('./lib/stub-controller.js');
const logger = require('winston');
const port = process.env.PORT || 5000;
const app = express();
app.set('view engine', 'pug');
app.use('/', stubController);
app.use('/new', shortUrlController);
const listener = app.listen(port, () => {
logger.info(`Your app is listening on port ${listener.address().port}`);
});
|
require('dotenv').config();
const express = require('express');
const shortUrlController = require('./lib/short-url-controller.js');
const stubController = require('./lib/stub-controller.js');
const logger = require('winston');
const port = process.env.PORT || 5000;
const app = express();
app.set('view engine', 'pug');
app.use('/', stubController);
app.use('/new', shortUrlController);
const listener = app.listen(port, () => {
logger.info(`Your app is listening on port ${listener.address().port}`);
});
|
Fix dotenv to work locally instead of just on heroku
|
Fix dotenv to work locally instead of just on heroku
|
JavaScript
|
mit
|
glynnw/url-shortener,glynnw/url-shortener
|
4e9b368ea408768aa52b44660b564fa23d344781
|
index.js
|
index.js
|
/*!
* array-last <https://github.com/jonschlinkert/array-last>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
var isNumber = require('is-number');
module.exports = function last(arr, n) {
if (!Array.isArray(arr)) {
throw new Error('expected the first argument to be an array');
}
var len = arr.length;
if (len === 0) {
return null;
}
n = isNumber(n) ? +n : 1;
if (n === 1 && len === 1) {
return arr[0];
}
var res = new Array(n);
while (n--) {
res[n] = arr[--len];
}
return res;
};
|
/*!
* array-last <https://github.com/jonschlinkert/array-last>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
var isNumber = require('is-number');
module.exports = function last(arr, n) {
if (!Array.isArray(arr)) {
throw new Error('expected the first argument to be an array');
}
var len = arr.length;
if (len === 0) {
return null;
}
n = isNumber(n) ? +n : 1;
if (n === 1) {
return arr[len - 1];
}
var res = new Array(n);
while (n--) {
res[n] = arr[--len];
}
return res;
};
|
Return a single value when n=1
|
Return a single value when n=1
* Worked previously: last([1], 1) === 1
* Broken previously: last([1, 2], 1) === 2
|
JavaScript
|
mit
|
jonschlinkert/array-last
|
bb273759bbb9f9edb716fa6596477fa019057fec
|
index.js
|
index.js
|
/* jshint node: true */
'use strict';
var fs = require('fs');
module.exports = {
name: 'uncharted-describe-models',
config: function(env, config) {
if (env === 'test') {
return;
}
if (!fs.existsSync('app/schema.json')) {
throw new Error('You must include a schema.json in the root of app/');
}
var schema = JSON.parse(fs.readFileSync('app/schema.json', 'utf8'));
config['model-schema'] = schema;
return config;
},
includedCommands: function() {
return {
'update-models': require('./lib/commands/update-models')
};
}
};
|
/* jshint node: true */
'use strict';
var fs = require('fs');
module.exports = {
name: 'uncharted-describe-models',
config: function(env, config) {
if (!fs.existsSync('app/schema.json')) {
throw new Error('You must include a schema.json in the root of app/');
}
var schema = JSON.parse(fs.readFileSync('app/schema.json', 'utf8'));
config['model-schema'] = schema;
return config;
},
includedCommands: function() {
return {
'update-models': require('./lib/commands/update-models')
};
}
};
|
Make sure we always load the schema, even within a test
|
Make sure we always load the schema, even within a test
|
JavaScript
|
mit
|
unchartedcode/describe-models,unchartedcode/describe-models
|
206a09a32b2f41f19c7340ec599e5d73e86d8cfc
|
index.js
|
index.js
|
var restify = require('restify');
var messenger = require('./lib/messenger');
var session = require('./lib/session');
var server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.authorizationParser());
server.get('/', function (req, res, next) {
res.send(200, {status: 'ok'});
});
server.post('/messages', function (req, res, next) {
var phoneNumber = req.params.From;
session.get(phoneNumber, function(err, user) {
if (err) messenger.send(phoneNumber, 'There was some kind of error.')
if (user) {
messenger.send(phoneNumber, 'Hello, old friend.');
} else {
session.set(phoneNumber, 'initial', function () {
res.send(phoneNumber, 'Nice to meet you.')
})
}
});
res.send(200, {status: 'ok'});
});
server.listen(process.env.PORT || '3000', function() {
console.log('%s listening at %s', server.name, server.url);
});
|
var restify = require('restify');
var messenger = require('./lib/messenger');
var session = require('./lib/session');
var server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.authorizationParser());
server.get('/', function (req, res, next) {
res.send(200, {status: 'ok'});
});
server.post('/messages', function (req, res, next) {
var phoneNumber = req.params.From;
session.get(phoneNumber, function(err, user) {
if (err) {
messenger.send(phoneNumber, 'There was some kind of error.');
res.send(500, {error: 'Something went wrong.'});
}
if (user) {
messenger.send(phoneNumber, 'Hello, old friend.');
res.send(200);
} else {
session.set(phoneNumber, 'initial', function () {
messenger.send(phoneNumber, 'Nice to meet you.');
res.send(200);
});
}
});
res.send(200, {status: 'ok'});
});
server.listen(process.env.PORT || '3000', function() {
console.log('%s listening at %s', server.name, server.url);
});
|
Send HTTP responses for all messages
|
Send HTTP responses for all messages
|
JavaScript
|
mpl-2.0
|
rockawayhelp/emergencybadges,rockawayhelp/emergencybadges
|
b069edce8a3e82dc64e34678db4dd7fe5c508aa3
|
index.js
|
index.js
|
// var http = require("http");
// app.set('view engine', 'html');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/scripts'));
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.post('/', function (req, res) {
res.send('Got a POST request')
})
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user')
})
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user')
})
|
// var http = require("http");
// app.set('view engine', 'html');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/scripts'));
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.post('/', function (req, res) {
res.send('Got a POST request')
})
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user')
})
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user')
})
// Route path: /users/:userId/books/:bookId
// Request URL: http://localhost:3000/users/34/books/8989
// req.params: { "userId": "34", "bookId": "8989" }
// To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
|
Add info on setting parameters in route
|
Add info on setting parameters in route
|
JavaScript
|
apache-2.0
|
XanderPSON/febrezehackathon,XanderPSON/febrezehackathon
|
992c7b2c2cc3f73eaef974a5c885da6fe27ebd6c
|
index.js
|
index.js
|
module.exports = {
handlebars: require('./lib/handlebars'),
marked: require('./lib/marked'),
componentTemplate: 'node_modules/foundation-docs/templates/component.html',
handlebarsHelpers: 'node_modules/foundation-docs/helpers/'
}
|
var path = require('path');
var TEMPLATE_PATH = path.join(__dirname, 'templates/component.html');
var HELPERS_PATH = path.join(__dirname, 'helpers');
module.exports = {
handlebars: require('./lib/handlebars'),
marked: require('./lib/marked'),
componentTemplate: path.relative(process.cwd(), TEMPLATE_PATH),
handlebarsHelpers: path.relative(process.cwd(), HELPERS_PATH)
}
|
Use relative paths for componentTemplate and handlebarsHelpers paths
|
Use relative paths for componentTemplate and handlebarsHelpers paths
|
JavaScript
|
mit
|
zurb/foundation-docs,zurb/foundation-docs
|
d60976582c1c4f8035a41e59c36489f5fbe95be1
|
index.js
|
index.js
|
var Map = require('./lib/map'),
Format = require('./lib/format'),
safe64 = require('./lib/safe64');
module.exports = {
Map: Map,
Format: Format,
safe64: safe64,
pool: function(datasource) {
return {
create: function(callback) {
var resource = new Map(datasource);
resource.initialize(function(err) {
if (err) throw err;
callback(resource);
});
},
destroy: function(resource) {
resource.destroy();
}
};
},
serve: function(resource, options, callback) {
resource.render(options, callback);
}
};
|
var Map = require('./lib/map'),
Format = require('./lib/format'),
safe64 = require('./lib/safe64');
module.exports = {
Map: Map,
Format: Format,
safe64: safe64,
pool: function(datasource) {
return {
create: function(callback) {
var resource = new Map(datasource);
resource.initialize(function(err) {
callback(err, resource);
});
},
destroy: function(resource) {
resource.destroy();
}
};
},
serve: function(resource, options, callback) {
resource.render(options, callback);
}
};
|
Update tilelive pool factory create method to pass errors.
|
Update tilelive pool factory create method to pass errors.
|
JavaScript
|
bsd-3-clause
|
dshorthouse/tilelive-mapnik,CartoDB/tilelive-mapnik,mapbox/tilelive-mapnik,tomhughes/tilelive-mapnik,wsw0108/tilesource-mapnik
|
3e0998496283eb83b66f97d765e069a470f3ba5d
|
index.js
|
index.js
|
'use strict';
module.exports = {
name: 'live-reload-middleware',
serverMiddleware: function(options) {
var app = options.app;
options = options.options;
if (options.liveReload === true) {
var livereloadMiddleware = require('connect-livereload');
app.use(livereloadMiddleware({
port: options.liveReloadPort
}));
}
}
};
|
'use strict';
module.exports = {
name: 'live-reload-middleware',
serverMiddleware: function(options) {
var app = options.app;
options = options.options;
if (options.liveReload === true) {
var livereloadMiddleware = require('connect-livereload');
app.use(livereloadMiddleware({
ignore: [
/\.js(?:\?.*)?$/,
/\.css(?:\?.*)$/,
/\.svg(?:\?.*)$/,
/\.ico(?:\?.*)$/,
/\.woff(?:\?.*)$/,
/\.png(?:\?.*)$/,
/\.jpg(?:\?.*)$/,
/\.jpeg(?:\?.*)$/,
/\.ttf(?:\?.*)$/
],
port: options.liveReloadPort
}));
}
}
};
|
Fix ignore list to work with query string params.
|
Fix ignore list to work with query string params.
|
JavaScript
|
mit
|
jbescoyez/ember-cli-inject-live-reload,rwjblue/ember-cli-inject-live-reload,scottkidder/ember-cli-inject-live-reload
|
688146ec463c255b6000ce72a4462dff1a99cb3c
|
gatsby-browser.js
|
gatsby-browser.js
|
import ReactGA from 'react-ga'
import {config} from 'config'
ReactGA.initialize(config.googleAnalyticsId);
exports.onRouteUpdate = (state, page, pages) => {
ReactGA.pageview(state.pathname);
};
|
import ReactGA from 'react-ga'
import {config} from 'config'
ReactGA.initialize(config.googleAnalyticsId);
ReactGA.plugin.require('linkid');
exports.onRouteUpdate = (state, page, pages) => {
ReactGA.pageview(state.pathname);
};
|
Add linkid to google analytics
|
Add linkid to google analytics
|
JavaScript
|
bsd-3-clause
|
tadeuzagallo/blog,tadeuzagallo/blog
|
8f82186dfb27825a7b2220f9a6c3f66346f0f300
|
worker/web_client/JobStatus.js
|
worker/web_client/JobStatus.js
|
import JobStatus from 'girder_plugins/jobs/JobStatus';
JobStatus.registerStatus({
WORKER_FETCHING_INPUT: {
value: 820,
text: 'Fetching input',
icon: 'icon-download',
color: '#89d2e2'
},
WORKER_CONVERTING_INPUT: {
value: 821,
text: 'Converting input',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_CONVERTING_OUTPUT: {
value: 822,
text: 'Converting output',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_PUSHING_OUTPUT: {
value: 823,
text: 'Pushing output',
icon: 'icon-upload',
color: '#89d2e2'
}
});
|
import JobStatus from 'girder_plugins/jobs/JobStatus';
JobStatus.registerStatus({
WORKER_FETCHING_INPUT: {
value: 820,
text: 'Fetching input',
icon: 'icon-download',
color: '#89d2e2'
},
WORKER_CONVERTING_INPUT: {
value: 821,
text: 'Converting input',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_CONVERTING_OUTPUT: {
value: 822,
text: 'Converting output',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_PUSHING_OUTPUT: {
value: 823,
text: 'Pushing output',
icon: 'icon-upload',
color: '#89d2e2'
},
WORKER_CANCELING: {
value: 824,
text: 'Canceling',
icon: 'icon-cancel',
color: '#f89406'
}
});
|
Add button to cancel job
|
WIP: Add button to cancel job
|
JavaScript
|
apache-2.0
|
girder/girder_worker,girder/girder_worker,girder/girder_worker
|
2e8c529dee0385daf201ecb5fca2e1d4b69d9376
|
jest-setup.js
|
jest-setup.js
|
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
// Configure Enzyme
Enzyme.configure({ adapter: new Adapter() });
// Add RAF for React 16
global.requestAnimationFrame = function requestAnimationFrame(callback) {
setTimeout(callback, 0);
};
|
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
// Configure Enzyme
Enzyme.configure({ adapter: new Adapter() });
// Add RAF for React 16
global.requestAnimationFrame = function requestAnimationFrame(callback) {
setTimeout(callback, 0);
};
|
Use require() instead of import().
|
Use require() instead of import().
|
JavaScript
|
mit
|
milesj/build-tool-config,milesj/build-tool-config,milesj/build-tool-config
|
6cacd255d4c963af7454da36656926f213b676f8
|
client/index.js
|
client/index.js
|
require('jquery')
require('expose?$!expose?jQuery!jquery')
require("bootstrap-webpack")
require('./less/index.less')
|
require('jquery')
require('expose?$!expose?jQuery!jquery')
require("bootstrap-webpack")
require('./less/index.less')
$.get('http://10.90.100.1:8080/signalk/v1/api/vessels/self/navigation/position')
.then(res => $.get(`http://www.tuuleeko.fi:8000/nearest-station?lat=${res.latitude}&lon=${res.longitude}`))
.then(station => {
$.get(`http://www.tuuleeko.fi:8000/observations?geoid=${station.geoid}`)
.then(stationObservations => {
var obs = stationObservations.observations[stationObservations.observations.length - 1]
var forecastHtml = `
<h3>${stationObservations.name} (${(station.distanceMeters / 1000).toFixed(1)} km)</h3>
<table class='table'>
<tr><th>Wind direction</th><th>Wind speed</th><th>Wind gusts</th></tr>
<tr><td>${obs.windDir}°</td><td>${obs.windSpeedMs} m/s</td><td>${obs.windGustMs} m/s</td></tr>
</table>`
$('body').append(forecastHtml)
})
})
|
Add POC for showing the closes weather observation data
|
Add POC for showing the closes weather observation data
|
JavaScript
|
apache-2.0
|
chacal/nrf-sensor-receiver,chacal/nrf-sensor-receiver,chacal/nrf-sensor-receiver
|
b5e2e552814b00858fce4fa844d326e6b3d81bc0
|
src/index.js
|
src/index.js
|
import * as path from 'path';
import {fs} from 'node-promise-es6';
import * as fse from 'fs-extra-promise-es6';
export default class {
constructor(basePath) {
this.basePath = path.resolve(basePath);
}
async create() {
await fse.mkdirs(this.basePath);
}
path(...components) {
return path.resolve(this.basePath, ...components);
}
async remove() {
await fse.remove(this.path());
}
async write(files) {
for (const file of Object.keys(files)) {
const filePath = this.path(file);
const fileContents = files[file];
await fse.ensureFile(filePath);
if (typeof fileContents === 'object') {
await fse.writeJson(filePath, fileContents);
} else {
const reindentedFileContents = fileContents
.split('\n')
.filter((line, index, array) =>
index !== 0 && index !== array.length - 1 || line.trim() !== '')
.reduce(({indentation, contents}, line) => {
const whitespaceToRemove = Number.isInteger(indentation) ?
indentation :
line.match(/^\s*/)[0].length;
return {
indentation: whitespaceToRemove,
contents: `${contents}${line.slice(whitespaceToRemove)}\n`
};
}, {contents: ''}).contents;
await fs.writeFile(filePath, reindentedFileContents);
}
}
}
}
|
import * as path from 'path';
import {fs} from 'node-promise-es6';
import * as fse from 'fs-extra-promise-es6';
export default class {
constructor(basePath) {
this.basePath = path.resolve(basePath);
}
async create() {
await fse.mkdirs(this.basePath);
}
path(...components) {
return path.resolve(this.basePath, ...components);
}
async remove() {
await fse.remove(this.path());
}
async write(files) {
for (const [filePath, fileContents] of Object.entries(files)) {
const absoluteFilePath = this.path(filePath);
await fse.ensureFile(absoluteFilePath);
if (typeof fileContents === 'object') {
await fse.writeJson(absoluteFilePath, fileContents);
} else {
const reindentedFileContents = fileContents
.split('\n')
.filter((line, index, array) =>
index !== 0 && index !== array.length - 1 || line.trim() !== '')
.reduce(({indentation, contents}, line) => {
const whitespaceToRemove = Number.isInteger(indentation) ?
indentation :
line.match(/^\s*/)[0].length;
return {
indentation: whitespaceToRemove,
contents: `${contents}${line.slice(whitespaceToRemove)}\n`
};
}, {contents: ''}).contents;
await fs.writeFile(absoluteFilePath, reindentedFileContents);
}
}
}
}
|
Use Object.entries instead of Object.keys
|
Use Object.entries instead of Object.keys
|
JavaScript
|
mit
|
vinsonchuong/directory-helpers
|
c9e44c6d990f95bb7e92bfa97fc0a74bf636c290
|
app/templates/tasks/utils/notify-style-lint.js
|
app/templates/tasks/utils/notify-style-lint.js
|
var notify = require("./notify");
module.exports = function notifyStyleLint (stdout) {
var messages = stdout.split("\n");
messages.pop(); // Remove last empty new message.
if(0 < messages.length) {
var message = "{{length}} lint warning(s) found.".replace(/{{length}}/g, messages.length);
notify.showNotification({
subtitle: "Task style:lint",
message: message,
appIcon: notify.appIcon.sass
});
}
};
|
var notify = require("./notify");
var util = require("util");
module.exports = function notifyStyleLint (stdout) {
var messages = stdout.split("\n");
messages.pop(); // Remove last empty new message.
if(0 < messages.length) {
var message = util.format("%d lint warning(s) found.", messages.length);
notify.showNotification({
subtitle: "Task style:lint",
message: message,
appIcon: notify.appIcon.sass
});
}
};
|
Use built-in utils to format the string.
|
Use built-in utils to format the string.
|
JavaScript
|
mit
|
rishabhsrao/generator-ironhide-webapp,rishabhsrao/generator-ironhide-webapp,rishabhsrao/generator-ironhide-webapp
|
b656897309110504fbc52e2c2048ed5dc3d17e23
|
js/sinbad-app.js
|
js/sinbad-app.js
|
appRun();
function appRun() {
$(document).ready(function() {
console.log("READY");
$(".loading").hide();
$(".complete").show();
//PAGE SWIPES
$(document).on('pageinit', function(event){
$('.pages').on("swipeleft", function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.changePage(nextpage, {transition: "slide", changeHash:false });
}
});
$('.pages').on("swiperight", function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, { transition: "slide", reverse: true, changeHash: false });
}
});
});
});
}
|
appRun();
function appRun() {
$(document).ready(function() {
console.log("READY");
$(".loading").hide();
$(".complete").show();
//PAGE SWIPES
$(document).on('pageinit', function(event){
$('.pages').on("swipeleft", function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.changePage(nextpage, {transition: "slide", changeHash:false });
}
});
$('.pages').on("swiperight", function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, { transition: "slide", reverse: true, changeHash: false });
}
});
});
//DRAG AND DROP
//initialize dragging
$("#watercolor").draggable( {
revert: true,
cursor: 'move',
} );
$("#leaves").draggable( {
revert: true,
cursor: 'move',
} );
$("#bubbles").draggable( {
revert: true,
cursor: 'move',
} );
//initialize droppable callback
$("#spritesheet").droppable({
tolerance: "pointer",
drop: sinbadChange
});
console.log("before droppable");
//event handler for drop event
function sinbadChange(event, ui) {
var currentBrush = ui.draggable.attr('id');
console.log(currentBrush);
console.log("in droppable");
if (currentBrush == "watercolor") {
$("#spritesheet").removeClass();
$("#spritesheet").addClass("brushfish");
console.log("DROPPED");
} else if (currentBrush == "leaves") {
$("#spritesheet").removeClass();
$("#spritesheet").addClass("leaffish");
console.log("DROPPED LEAF");
} else if (currentBrush == "bubbles") {
$("#spritesheet").removeClass();
$("#spritesheet").addClass("bubblefish");
console.log("DROPPED BUBBLE");
} else {
$("#spritesheet").removeClass();
$("#spritesheet").addClass("plainfish");
}
}
// //add listener to drop event
// $("spritesheet").on("drop", function(event, ui) {
// })
}); //end jquery
} //end appRun
|
Add jquery UI drag/drop functionality
|
Add jquery UI drag/drop functionality
|
JavaScript
|
mit
|
andkerel/sinbad-and-the-phonegap,andkerel/sinbad-and-the-phonegap
|
a549e6988de5071dbbf397c5fd1f894f5ad0a8f7
|
assets/js/util/tracking/createDataLayerPush.js
|
assets/js/util/tracking/createDataLayerPush.js
|
/**
* Internal dependencies
*/
import { DATA_LAYER } from './index.private';
/**
* Returns a function which, when invoked will initialize the dataLayer and push data onto it.
*
* @param {Object} target Object to enhance with dataLayer data.
* @return {Function} Function that pushes data onto the dataLayer.
*/
export default function createDataLayerPush( target ) {
/**
* Pushes data onto the data layer.
*
* @param {...any} args Arguments to push onto the data layer.
*/
return function dataLayerPush( ...args ) {
target[ DATA_LAYER ] = target[ DATA_LAYER ] || [];
target[ DATA_LAYER ].push( args );
};
}
|
/**
* Internal dependencies
*/
import { DATA_LAYER } from './index.private';
/**
* Returns a function which, when invoked will initialize the dataLayer and push data onto it.
*
* @param {Object} target Object to enhance with dataLayer data.
* @return {Function} Function that pushes data onto the dataLayer.
*/
export default function createDataLayerPush( target ) {
/**
* Pushes data onto the data layer.
* Must use `arguments` internally.
*/
return function dataLayerPush() {
target[ DATA_LAYER ] = target[ DATA_LAYER ] || [];
target[ DATA_LAYER ].push( arguments );
};
}
|
Refactor dataLayerPush to use func.arguments.
|
Refactor dataLayerPush to use func.arguments.
|
JavaScript
|
apache-2.0
|
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
|
001259b0263e6b2534b0efdc9a3b6936965bf9b8
|
config/nconf.js
|
config/nconf.js
|
var nconf = require('nconf');
nconf
.env()
.file({ file: './gateway.json' });
nconf.defaults({
'RIPPLE_REST_API': 'http://localhost:5990',
'DATABASE_URL': 'postgres://username:password@localhost/ripple_gateway'
});
module.exports = nconf;
|
var nconf = require('nconf');
nconf
.env()
.file({ file: './config/config.json' });
nconf.defaults({
'RIPPLE_REST_API': 'http://localhost:5990',
'DATABASE_URL': 'postgres://username:password@localhost/ripple_gateway'
});
module.exports = nconf;
|
Move config file from gateway to config/config
|
[FEATURE] Move config file from gateway to config/config
|
JavaScript
|
isc
|
whotooktwarden/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,zealord/gatewayd,Parkjeahwan/awegeeks,xdv/gatewayd,whotooktwarden/gatewayd,crazyquark/gatewayd,zealord/gatewayd,xdv/gatewayd
|
b9ef8725552b57061865e73ca54b901bdf773465
|
app/js/app.js
|
app/js/app.js
|
//onReady
$(function() {
//temporary testing functionality
$('#refreshBtn').on('click', function() {
updateStreams();
});
});
function updateStreams() {
// Clear out the stale data
$('#mainContainer').html("");
// And fetch the fresh
var streamList = $('#streamList').val().split('\n');
for (var i = 0, len = streamList.length; i < len; i++) {
fetchStreamData(streamList[i]);
}
}
function fetchStreamData( streamName ) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamName + '?callback=?', function(data){
var streamObj = {};
streamObj.streamName = data.stream.channel.display_name;
streamObj.preview = data.stream.preview.medium;
streamObj.status = data.stream.channel.status;
streamObj.logo = data.stream.channel.logo;
streamObj.url = data.stream._links.self;
displayStream(streamObj);
});
}
function displayStream( streamObj ) {
$('#mainContainer').append(
'<div class="twitchContainer col-xs-12 col-sm-4">' +
'<img class="streamLogo" src="' + streamObj.logo + '" alt="logo">' +
'<h2>' + streamObj.streamName + '</h2>' +
'<p>' + streamObj.status + '</p>' +
'</div>'
);
}
|
//onReady
$(function() {
//temporary testing functionality
$('#refreshBtn').on('click', function() {
updateStreams();
});
});
function updateStreams() {
// Clear out the stale data
$('#mainContainer').html("");
// And fetch the fresh
var streamList = $('#streamList').val().split('\n');
for (var i = 0, len = streamList.length; i < len; i++) {
fetchStreamData(streamList[i]);
}
}
function fetchStreamData( streamName ) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamName + '?callback=?', function(data){
var streamObj = {};
streamObj.streamName = data.stream.channel.display_name;
streamObj.preview = data.stream.preview.medium;
streamObj.status = data.stream.channel.status;
streamObj.logo = data.stream.channel.logo;
streamObj.url = data.stream.channel.url;
displayStream(streamObj);
});
}
function displayStream( streamObj ) {
$('<div class="twitchContainer col-xs-12 col-sm-4">' +
'<img class="streamLogo" src="' + streamObj.logo + '" alt="logo">' +
'<h2>' + streamObj.streamName + '</h2>' +
'<p>' + streamObj.status + '</p>' +
'</div>'
)
.css('background-image', 'url(' + streamObj.preview + ')')
.on('click', function() {
window.open(streamObj.url, '_blank');
})
.appendTo($('#mainContainer'));
}
|
Refactor displayStream. Add background-image and onClick
|
Refactor displayStream. Add background-image and onClick
|
JavaScript
|
mit
|
xipxoom/fcc-twitch_status,xipxoom/fcc-twitch_status
|
00211245eafbd799b7feda2076d6a84a981e41ad
|
index.js
|
index.js
|
'use strict';
var assign = require('object-assign');
var Filter = require('broccoli-filter');
var Rework = require('rework');
/**
* Initialize `ReworkFilter` with options
*
* @param {Object} inputTree
* @param {Object} opts
* @api public
*/
function ReworkFilter(inputTree, opts) {
if (!(this instanceof ReworkFilter)) {
return new ReworkFilter(inputTree, opts);
}
this.inputTree = inputTree;
this.opts = opts || {};
}
/**
* Create object
*/
ReworkFilter.prototype = Object.create(Filter.prototype);
ReworkFilter.prototype.constructor = ReworkFilter;
/**
* Extensions
*/
ReworkFilter.prototype.extensions = ['css'];
ReworkFilter.prototype.targetExtension = 'css';
/**
* Process CSS
*
* @param {String} str
* @api public
*/
ReworkFilter.prototype.processString = function (str) {
var rework = new Rework(str);
if (this.opts.use) {
this.opts.use(rework);
}
return rework.toString(this.opts);
};
/**
* Module exports
*/
module.exports = ReworkFilter;
/**
* Mixin the rework built-in plugins
*/
delete Rework.properties;
assign(module.exports, Rework);
|
'use strict';
var assign = require('object-assign');
var Filter = require('broccoli-filter');
var Rework = require('rework');
/**
* Initialize `ReworkFilter` with options
*
* @param {Object} inputTree
* @param {Object} opts
* @api public
*/
function ReworkFilter(inputTree, opts) {
if (!(this instanceof ReworkFilter)) {
return new ReworkFilter(inputTree, opts);
}
this.inputTree = inputTree;
this.opts = opts || {};
}
/**
* Create object
*/
ReworkFilter.prototype = Object.create(Filter.prototype);
ReworkFilter.prototype.constructor = ReworkFilter;
/**
* Extensions
*/
ReworkFilter.prototype.extensions = ['css'];
ReworkFilter.prototype.targetExtension = 'css';
/**
* Process CSS
*
* @param {String} str
* @api public
*/
ReworkFilter.prototype.processString = function (str, relativePath) {
var rework = new Rework(str, {
source: relativePath
});
if (this.opts.use) {
this.opts.use(rework);
}
return rework.toString(this.opts);
};
/**
* Module exports
*/
module.exports = ReworkFilter;
/**
* Mixin the rework built-in plugins
*/
delete Rework.properties;
assign(module.exports, Rework);
|
Set rework `source` from `relativePath`
|
Set rework `source` from `relativePath`
This will enable sourcemaps generated from rework to refer to the source by
its name, versus the generic `source.css`.
|
JavaScript
|
mit
|
kevva/broccoli-rework
|
828aba16dfb4273329392c369bf637897b80ec87
|
index.js
|
index.js
|
'use strict'
var document = require('global/document')
var Loop = require('main-loop')
var virtualDom = require('virtual-dom')
var assert = require('assert')
var partial = require('ap').partial
var Delegator = require('dom-delegator')
// Instantiate a DOM delegator once, since it caches itself
Delegator()
exports.createComponent = createComponent
function createComponent (Component, data, callback) {
assert(Component, 'Component is required')
if (arguments.length < 2) return partial(createComponent, Component)
if (typeof data === 'function') {
callback = data
data = undefined
}
// Call the component constructor to get a new state
var state = Component(data)
// Add an element for later use
var div = document.createElement('div')
document.body.appendChild(div)
// create a raf rendering loop and add the target element to the dom
var loop = Loop(state(), Component.render, virtualDom)
div.appendChild(loop.target)
// update the loop whenever the state changes
state(loop.update)
return callback(state, loop.target, destroy)
function destroy () {
// remove the element from the DOM
document.body.removeChild(div)
}
}
|
'use strict'
var document = require('global/document')
var Loop = require('main-loop')
var virtualDom = require('virtual-dom')
var assert = require('assert')
var partial = require('ap').partial
var Delegator = require('dom-delegator')
// Instantiate a DOM delegator once, since it caches itself
Delegator()
exports.createComponent = createComponent
function createComponent (Component, data, callback) {
assert(Component, 'Component is required')
if (arguments.length < 2) return partial(createComponent, Component)
if (typeof data === 'function') {
callback = data
data = undefined
}
// Call the component constructor to get a new state
var state = Component(data)
// Add an element for later use
var div = document.createElement('div')
div.style.height = '100%'
document.body.appendChild(div)
// create a raf rendering loop and add the target element to the dom
var loop = Loop(state(), Component.render, virtualDom)
div.appendChild(loop.target)
// update the loop whenever the state changes
state(loop.update)
return callback(state, loop.target, destroy)
function destroy () {
// remove the element from the DOM
document.body.removeChild(div)
}
}
|
Set component div to 100% height
|
Set component div to 100% height
|
JavaScript
|
mit
|
bendrucker/thermometer
|
db8e102e618ef8b49a4887523da6563146a3ea91
|
index.js
|
index.js
|
export class DecoratorUtils {
static declarationType = [
"CLASS",
"CLASS_METHOD",
"CLASS_ACCESSOR",
"OBJECT_LITERAL_METHOD",
"OBJECT_LITERAL_ACCESSOR"
].reduce((obj, name) => {
return Object.defineProperty(obj, name, { value: Symbol(name) });
}, {})
static getDeclarationType(args) {
let [target, name, descriptor] = Array.slice(args);
if (args.length === 1 && typeof target === "function") {
return DecoratorUtils.declarationType.CLASS;
} else if (args.length === 3 && typeof target === "object" && typeof target.constructor === "function") {
let isObjectLiteral = target.constructor.name === "Object";
let isAccessor = descriptor.get || descriptor.set;
return DecoratorUtils.declarationType[`${isObjectLiteral ? "OBJECT_LITERAL" : "CLASS"}_${isAccessor ? "ACCESSOR" : "METHOD"}`];
}
return null;
}
};
|
export class DecoratorUtils {
static declarationType = [
"CLASS",
"CLASS_METHOD",
"CLASS_ACCESSOR",
"OBJECT_LITERAL_METHOD",
"OBJECT_LITERAL_ACCESSOR"
].reduce((obj, name) => {
return Object.defineProperty(obj, name, { value: Symbol(name) });
}, {})
static getDeclarationType(args) {
let [target, name, descriptor] = Array.slice(args);
if (args.length === 1 && typeof target === "function") {
return DecoratorUtils.declarationType.CLASS;
} else if (args.length === 3 && typeof target === "object" && typeof target.constructor === "function") {
let isObjectLiteral = target.constructor.name === "Object";
let isAccessor = descriptor.get || descriptor.set;
return DecoratorUtils.declarationType[`${isObjectLiteral ? "OBJECT_LITERAL" : "CLASS"}_${isAccessor ? "ACCESSOR" : "METHOD"}`];
}
throw new Error("Invalid declaration type.");
}
};
|
Throw an error for invalid declaration types
|
Throw an error for invalid declaration types
|
JavaScript
|
mit
|
lukehorvat/decorator-utils
|
5c4f313e3aff67e71dca344ef46a7cb25851b525
|
jujugui/static/gui/src/app/components/dropdown-menu/test-dropdown-menu.js
|
jujugui/static/gui/src/app/components/dropdown-menu/test-dropdown-menu.js
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const DropdownMenu = require('./dropdown-menu');
const Panel = require('../panel/panel');
const jsTestUtils = require('../../utils/component-test-utils');
describe('Dropdown Menu', function() {
function renderComponent(options={}) {
return jsTestUtils.shallowRender(
<DropdownMenu.WrappedComponent
handleClickOutside={options.handleClickOutside}>
{options.children}
</DropdownMenu.WrappedComponent>, true);
}
it('can render', () => {
const handleClickOutside = sinon.stub();
const renderer = renderComponent({
children: <li>child</li>,
handleClickOutside: handleClickOutside
});
const output = renderer.getRenderOutput();
const expected = (
<Panel instanceName="dropdown-menu" visible={true}>
<ul className="dropdown-menu__list">
<li>child</li>
</ul>
</Panel>
);
expect(output).toEqualJSX(expected);
});
});
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const enzyme = require('enzyme');
const DropdownMenu = require('./dropdown-menu');
describe('Dropdown Menu', function() {
const renderComponent = (options = {}) => enzyme.shallow(
<DropdownMenu.WrappedComponent
handleClickOutside={options.handleClickOutside || sinon.stub()}>
{options.children}
</DropdownMenu.WrappedComponent>
);
it('can render', () => {
const wrapper = renderComponent({
children: <li>child</li>
});
const expected = (
<ul className="dropdown-menu__list">
<li>child</li>
</ul>
);
assert.compareJSX(wrapper.find('.dropdown-menu__list'), expected);
});
});
|
Update dropdown menu tests to use enzyme.
|
Update dropdown menu tests to use enzyme.
|
JavaScript
|
agpl-3.0
|
mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui
|
afe60f1030ac7cdff1e0acca3229f9b1ba19fc00
|
Kinect2Scratch.js
|
Kinect2Scratch.js
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
return {status: 1, msg: 'The File APIs are not fully supported by your browser.'};
//return {status: 2, msg: 'Ready'};
} else {
return {status: 1, msg: 'The File APIs are not fully supported by your browser.'};
}
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['r', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return 1;
case 'heady': return 2;
}
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
return {status: 2, msg: 'Ready'};
} else {
return {status: 0, msg: 'The File APIs are not fully supported by your browser.'};
}
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['r', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return 1;
case 'heady': return 2;
}
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
Put statuses back to correct, adjust unsupported status
|
Put statuses back to correct, adjust unsupported status
|
JavaScript
|
bsd-3-clause
|
visor841/SkelScratch,Calvin-CS/SkelScratch
|
c826899a6c86e1ac96505965ca7ae7a8781328d6
|
js/TimeFilter.js
|
js/TimeFilter.js
|
(function(app){
"use strict"
/**
* Creates a filter to convert a time in milliseconds to
* an hours:minutes:seconds format.
*
* e.g.
* {{60000 | millisecondsToTime}} // 01:00
* {{3600000 | millisecondsToTime}} // 01:00:00
*/
app.filter("millisecondsToTime", MillisecondsToTime);
function MillisecondsToTime(){
return function(time){
if(time < 0 || isNaN(time))
return "";
var seconds = parseInt((time / 1000) % 60);
var minutes = parseInt((time / (60000)) % 60);
var hours = parseInt((time / (3600000)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return ((hours !== "00") ? hours + ":" : "") + minutes + ":" + seconds;
}
};
})(angular.module("ov.player"));
|
(function(app){
"use strict"
/**
* Creates a filter to convert a time in milliseconds to
* an hours:minutes:seconds format.
*
* e.g.
* {{60000 | millisecondsToTime}} // 01:00
* {{3600000 | millisecondsToTime}} // 01:00:00
*/
app.filter("millisecondsToTime", MillisecondsToTime);
function MillisecondsToTime(){
return function(time){
if(time < 0 || isNaN(time))
return "";
time = parseInt(time);
var seconds = parseInt((time / 1000) % 60);
var minutes = parseInt((time / (60000)) % 60);
var hours = parseInt((time / (3600000)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return ((hours !== "00") ? hours + ":" : "") + minutes + ":" + seconds;
}
};
})(angular.module("ov.player"));
|
Add security on time filter to be sure this is an integer and not a float
|
Add security on time filter to be sure this is an integer and not a float
|
JavaScript
|
agpl-3.0
|
veo-labs/openveo-player,veo-labs/openveo-player,veo-labs/openveo-player
|
4df51733774fdbde4e23020127a3084f403d1179
|
src/assets/drizzle/scripts/navigation/mobileNav.js
|
src/assets/drizzle/scripts/navigation/mobileNav.js
|
/* global document window */
import { focusFirstEl } from '../../../../../packages/spark-core/utilities/elementState';
const hideMobileNav = (nav) => {
document.body.classList.remove('sprk-u-OverflowHidden');
nav.classList.remove('is-active');
};
const focusTrap = (nav, mainNav) => {
if (nav.classList.contains('is-active')) {
focusFirstEl(mainNav);
}
};
const bindUIEvents = () => {
const nav = document.querySelector('.drizzle-o-Layout__nav');
const mainNav = nav.querySelector('.drizzle-c-Navigation__main');
const mainLayout = document.querySelector('.drizzle-o-Layout__main');
window.addEventListener('resize', () => {
hideMobileNav(nav);
});
mainLayout.addEventListener('focusin', () => {
focusTrap(nav, mainNav);
});
};
const mobileNav = () => {
bindUIEvents();
};
export { mobileNav, hideMobileNav, focusTrap };
|
/* global document window */
import { focusFirstEl } from '../../../../../packages/spark-core/utilities/elementState';
const hideMobileNav = (nav) => {
document.body.classList.remove('sprk-u-OverflowHidden');
nav.classList.remove('is-active');
};
const focusTrap = (nav, mainNav) => {
if (nav.classList.contains('is-active')) {
focusFirstEl(mainNav);
}
};
const bindUIEvents = () => {
const nav = document.querySelector('.drizzle-o-Layout__nav');
if (nav === null) return;
const mainNav = nav.querySelector('.drizzle-c-Navigation__main');
const mainLayout = document.querySelector('.drizzle-o-Layout__main');
window.addEventListener('resize', () => {
hideMobileNav(nav);
});
mainLayout.addEventListener('focusin', () => {
focusTrap(nav, mainNav);
});
};
const mobileNav = () => {
bindUIEvents();
};
export { mobileNav, hideMobileNav, focusTrap };
|
Add check for if mobilenav exists
|
Add check for if mobilenav exists
|
JavaScript
|
mit
|
sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system
|
696343cd90c8aa3b21a289b363441e005a7413da
|
system.config.js
|
system.config.js
|
'use strict';
const externalDeps = [
'@angular/*',
'angular',
'angular-mocks',
'rxjs/*',
'lodash',
'moment',
'moment-timezone',
];
const map = {
'@angular': 'node_modules/@angular',
'angular': 'node_modules/angular/angular',
'angular-mocks': 'node_modules/angular-mocks/angular-mocks',
'rxjs': 'node_modules/rxjs',
'lodash': 'node_modules/lodash/index',
'node-uuid': 'node_modules/node-uuid/uuid',
'moment': 'node_modules/moment/moment',
'moment-timezone': 'node_modules/moment-timezone/builds/moment-timezone-with-data.min',
}
let meta = {};
externalDeps.forEach(dep => {
meta[dep] = { build: false };
});
System.config({
meta,
map,
paths: {
'*': '*.js',
},
});
|
'use strict';
const externalDeps = [
'@angular/*',
'angular',
'angular-mocks',
'rxjs/*',
'lodash',
'moment',
'moment-timezone',
];
const map = {
'@angular': 'node_modules/@angular',
'angular': 'node_modules/angular/angular',
'angular-mocks': 'node_modules/angular-mocks/angular-mocks',
'rxjs': 'node_modules/rxjs',
'lodash': 'node_modules/lodash/index',
'node-uuid': 'node_modules/node-uuid/uuid',
'moment': 'node_modules/moment/moment',
'moment-timezone': 'node_modules/moment-timezone/builds/moment-timezone-with-data.min',
};
const meta = externalDeps.reduce((curMeta, dep) => {
curMeta[dep] = { build: false };
return curMeta;
}, {});
System.config({
meta,
map,
paths: {
'*': '*.js',
},
});
|
Use reduce to avoid mutating the object unneededly.
|
Use reduce to avoid mutating the object unneededly.
|
JavaScript
|
mit
|
RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities
|
afdf07a331ed5f7dad218f9f23e7466ffcf75597
|
scripts/components/Header.js
|
scripts/components/Header.js
|
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
/*
Header
Top of the full App
*/
var Header = React.createClass({
handleTitleTouch : function() {
this.props.history.push('/');
},
render : function() {
return (
<MuiThemeProvider>
<AppBar
title={<span style={{'cursor':'pointer'}}>MetaSeek</span>}
onTitleTouchTap={this.handleTitleTouch}
iconElementLeft={<div></div>}
iconElementRight={
<IconMenu
iconButtonElement={
<IconButton><MoreVertIcon /></IconButton>
}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="Help" />
<MenuItem primaryText="Sign out" />
</IconMenu>
}
/>
</MuiThemeProvider>
)
}
});
export default Header;
|
import React from 'react';
import { Link } from 'react-router';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
/*
Header
Top of the full App
*/
var Header = React.createClass({
handleTitleTouch : function() {
this.props.history.push('/');
},
render : function() {
return (
<MuiThemeProvider>
<AppBar
title={<span style={{'cursor':'pointer'}}>MetaSeek</span>}
onTitleTouchTap={this.handleTitleTouch}
iconElementLeft={<div></div>}
iconElementRight={
<IconMenu
iconButtonElement={
<IconButton><MoreVertIcon /></IconButton>
}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
>
<Link style={{'text-decoration':'none'}} to='/myaccount'>
<MenuItem primaryText="My Account" />
</Link>
</IconMenu>
}
/>
</MuiThemeProvider>
)
}
});
export default Header;
|
Add my account to header
|
Add my account to header
|
JavaScript
|
mit
|
ahoarfrost/metaseek,ahoarfrost/metaseek,ahoarfrost/metaseek
|
0c59eb01b242e7591bc1a9218f1eb330ec9ec9f4
|
app/components/organization-profile.js
|
app/components/organization-profile.js
|
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['organization-profile'],
credentials: Ember.inject.service(),
organizationMembers: Ember.computed.mapBy('organization.organizationMemberships', 'organization'),
didReceiveAttrs() {
this._super(...arguments);
this.get('credentials').set('currentOrganization', this.get('organization'));
},
});
|
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['organization-profile'],
credentials: Ember.inject.service(),
organizationMembers: Ember.computed.mapBy('organization.organizationMemberships', 'member'),
didReceiveAttrs() {
this._super(...arguments);
this.get('credentials').set('currentOrganization', this.get('organization'));
},
});
|
Fix organization profile by changing computed property
|
Fix organization profile by changing computed property
|
JavaScript
|
mit
|
jderr-mx/code-corps-ember,code-corps/code-corps-ember,jderr-mx/code-corps-ember,code-corps/code-corps-ember
|
b557cbb6c8e98fc5ed0183a8c902561389e4e013
|
EduChainApp/js/common/GlobalStyles.js
|
EduChainApp/js/common/GlobalStyles.js
|
/**
*
* @flow
*/
'use strict';
import {StyleSheet} from 'react-native';
const GlobalStyles = {
contentWrapper: {
paddingLeft: 5,
paddingRight: 5,
},
sectionHeader: {
fontSize: 20,
marginTop: 10,
},
thumbnail: {
height: 45,
width: 45,
borderRadius: 22, // why dafuq is 22 circular??
},
buttonContainer: {
padding:10,
paddingTop: 11,
height:45,
overflow:'hidden',
borderRadius:4,
backgroundColor: '#ededed'
},
separator: {
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: '#8E8E8E',
},
};
module.exports = GlobalStyles;
|
/**
*
* @flow
*/
'use strict';
import {StyleSheet} from 'react-native';
const GlobalStyles = {
contentWrapper: {
paddingLeft: 5,
paddingRight: 5,
},
sectionHeader: {
fontSize: 20,
marginTop: 10,
},
thumbnail: {
height: 45,
width: 45,
borderRadius: 22, // why dafuq is 22 circular??
},
buttonContainer: {
padding:10,
paddingTop: 11,
height:45,
overflow:'hidden',
borderRadius:4,
backgroundColor: '#ededed'
},
separator: {
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: '#8E8E8E',
},
backBtn: {
title: "Back",
layout: "icon",
icon: "ios-arrow-back",
}
};
module.exports = GlobalStyles;
|
Add backBtn styling, fix indentation
|
Add backBtn styling, fix indentation
|
JavaScript
|
mit
|
bkrem/educhain,bkrem/educhain,bkrem/educhain,bkrem/educhain
|
a81e5611622ac50a1c82a26df88e63c87d888e88
|
lib/converter.js
|
lib/converter.js
|
const puppeteer = require("puppeteer")
const defaults = require("../configurations/defaults")
const puppeteerArgs = [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-gpu"
]
const allowedOptions = [
"scale",
"printBackground",
"margin"
]
const formatOptions = options => allowedOptions.reduce((filtered, key) => {
if (options[key] == 'true') {
filtered[key] = true
return filtered
}
if (options[key] == 'false') {
filtered[key] = false
return filtered
}
if (!isNaN(options[key])) {
filtered[key] = +options[key]
return filtered
}
filtered[key] = options[key]
return filtered
}, {})
const pageToPdf = options => page =>
page
.goto(options.uri, { waitUntil: "networkidle" })
.then(() => page.pdf(Object.assign(defaults, formatOptions(options))))
const browserToPdf = options => browser =>
browser
.newPage()
.then(pageToPdf(options))
.then(pdf => {
browser.close()
return pdf
})
const uriToPdf = options =>
puppeteer
.launch({ args: puppeteerArgs })
.then(browserToPdf(options))
module.exports = {
uriToPdf
}
|
const puppeteer = require("puppeteer")
const defaults = require("../configurations/defaults")
const puppeteerArgs = [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-gpu"
]
const allowedOptions = [
"scale",
"displayHeaderFooter",
"printBackground",
"format",
"landscape",
"pageRanges",
"width",
"height",
"margin"
]
const formatOptions = options => allowedOptions.reduce((filtered, key) => {
if (options[key] == 'true') {
filtered[key] = true
return filtered
}
if (options[key] == 'false') {
filtered[key] = false
return filtered
}
if (!isNaN(options[key])) {
filtered[key] = +options[key]
return filtered
}
filtered[key] = options[key]
return filtered
}, {})
const pageToPdf = options => page =>
page
.goto(options.uri, { waitUntil: "networkidle" })
.then(() => page.pdf(Object.assign(defaults, formatOptions(options))))
const browserToPdf = options => browser =>
browser
.newPage()
.then(pageToPdf(options))
.then(pdf => {
browser.close()
return pdf
})
const uriToPdf = options =>
puppeteer
.launch({ args: puppeteerArgs })
.then(browserToPdf(options))
module.exports = {
uriToPdf
}
|
Allow almost all puppeteer pdf configurations
|
Allow almost all puppeteer pdf configurations
|
JavaScript
|
mit
|
tecnospeed/pastor
|
447902934914f8a803a705044252eb71beb7cc62
|
lib/logger.js
|
lib/logger.js
|
'use strict';
const Winston = require('winston');
function Logger(level) {
const logLevel = level.toLowerCase() || 'info';
const logger = new Winston.Logger({
level: logLevel,
transports: [
new Winston.transports.Console({
colorize: false,
timestamp: true,
json: true,
stringify: true
})
]
});
return logger;
}
exports.attach = Logger;
|
'use strict';
const Winston = require('winston');
function Logger(level) {
const logLevel = (level || 'info').toLowerCase();
const logger = new Winston.Logger({
level: logLevel,
transports: [
new Winston.transports.Console({
colorize: false,
timestamp: true,
json: true,
stringify: true
})
]
});
return logger;
}
exports.attach = Logger;
|
Handle null and undefined log levels properly
|
Handle null and undefined log levels properly
|
JavaScript
|
mit
|
rapid7/acs,rapid7/acs,rapid7/acs
|
5b3686c9a28feaeda7e51526f8cdc9e27793b95c
|
bin/config.js
|
bin/config.js
|
'use strict'
var fs = require('fs')
var path = require('path')
var existFile = require('exists-file')
var minimistPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'minimist')
var minimist = require(minimistPath)
var trimNewlinesPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'trim-newlines')
var trimNewlines = require(trimNewlinesPath)
var FILENAME = 'worker-farm.opts'
function readConfig (filepath) {
var yargs = process.argv.slice(2)
if (yargs.length === 0) return yargs
var filepath = path.resolve(yargs[yargs.length - 1], FILENAME)
if (!existFile(filepath)) return yargs
var config = fs.readFileSync(filepath, 'utf8')
config = trimNewlines(config).split('\n')
return config.concat(yargs)
}
module.exports = readConfig()
|
'use strict'
var fs = require('fs')
var path = require('path')
var existFile = require('exists-file')
var minimistPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'minimist')
var minimist = require(minimistPath)
var trimNewlinesPath = path.join(__dirname, '..', 'node_modules', 'meow', 'node_modules', 'trim-newlines')
var trimNewlines = require(trimNewlinesPath)
var FILENAME = 'worker-farm.opts'
function readConfig (filepath) {
var yargs = process.argv.slice(2)
if (yargs.length > 1) return yargs
var filepath = path.resolve(yargs[0], FILENAME)
if (!existFile(filepath)) return yargs
var config = fs.readFileSync(filepath, 'utf8')
config = trimNewlines(config).split('\n')
return config.concat(yargs)
}
module.exports = readConfig()
|
Load file if params are not present
|
Load file if params are not present
|
JavaScript
|
mit
|
Kikobeats/farm-cli,Kikobeats/worker-farm-cli
|
b183de1dbadae83d82c6573ba61dc7b5fa386856
|
app/containers/gif/sagas.js
|
app/containers/gif/sagas.js
|
import { remote } from 'electron';
import { call, select, put, takeLatest } from 'redux-saga/effects';
import GIF from './constants';
import { result, error, clear } from './actions';
import request from '../../utils/request';
export function* requestGif(action) {
const requestURL = `http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=${action.payload}`;
try {
const gif = yield call(request, requestURL);
const state = yield select();
// Only continue displaying this result if the window is visible to the user
// and they haven't blanked out the search box
if (remote.getCurrentWindow().isVisible() && state.gif.currentQuery.length) {
yield put(result(gif));
} else {
yield put(clear());
}
} catch (err) {
yield put(error(err));
}
}
export function* watchRequestGif() {
yield takeLatest([GIF.REQUEST, GIF.NEXT], requestGif);
}
|
import { remote } from 'electron';
import { call, select, put, takeLatest } from 'redux-saga/effects';
import GIF from './constants';
import { result, error, clear } from './actions';
import request from '../../utils/request';
export function* requestGif(action) {
// If there is no query given, grab the latest one from state
const tag = action.payload
? action.payload
: yield select(state => state.gif.currentQuery);
const requestURL = `http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=${tag}`;
try {
const gif = yield call(request, requestURL);
const state = yield select();
// Only continue displaying this result if the window is visible to the user
// and they haven't blanked out the search box
if (remote.getCurrentWindow().isVisible() && state.gif.currentQuery.length) {
yield put(result(gif));
} else {
yield put(clear());
}
} catch (err) {
yield put(error(err));
}
}
export function* watchRequestGif() {
yield takeLatest([GIF.REQUEST, GIF.NEXT], requestGif);
}
|
Fix down button to dp the same tag search
|
Fix down button to dp the same tag search
|
JavaScript
|
mit
|
astrogif/astrogif,astrogif/astrogif
|
7f5f5482fc30ab8f6fd1470f15569023f95d4920
|
app/src/containers/ContactUs.js
|
app/src/containers/ContactUs.js
|
import { connect } from 'react-redux';
import ContactUs from '../components/ContactUs';
import { submitForm } from '../actions/contact';
const mapStateToProps = (state) => ({
contactStatus: state.contactStatus,
defaultUserName: state.user.loggedUser && state.user.loggedUser.displayName,
defaultUserEmail: state.user.loggedUser && state.user.loggedUser.email
});
const mapDispatchToProps = (dispatch) => ({
submitForm: (data, endpoint) => dispatch(submitForm(data, endpoint))
});
export default connect(mapStateToProps, mapDispatchToProps)(ContactUs);
|
import { connect } from 'react-redux';
import ContactUs from '../components/ContactUs';
import { submitForm } from '../actions/contact';
const mapStateToProps = (state) => ({
contactStatus: state.contactStatus,
defaultUserName: state.user.loggedUser ? state.user.loggedUser.displayName : '',
defaultUserEmail: state.user.loggedUser ? state.user.loggedUser.email : ''
});
const mapDispatchToProps = (dispatch) => ({
submitForm: (data, endpoint) => dispatch(submitForm(data, endpoint))
});
export default connect(mapStateToProps, mapDispatchToProps)(ContactUs);
|
Fix issue when logging out on contact page
|
Fix issue when logging out on contact page
|
JavaScript
|
mit
|
Vizzuality/GlobalFishingWatch,Vizzuality/GlobalFishingWatch,Vizzuality/GlobalFishingWatch
|
88d7a14c2640c8ee7eddd6044fe84970a0f724c8
|
Resources/public/scripts/globals.js
|
Resources/public/scripts/globals.js
|
var AJAX_LOADER = '<span class="ajax_loader"></span>';
$(document).bind('ajaxComplete', function () {
$('.ajax_loader').remove();
});
|
var AJAX_LOADER = '<span class="ajax_loader"></span>';
$(document).bind('ajaxComplete', function () {
$('.ajax_loader').remove();
$('form').removeData('submitted');
});
|
Mark forms as not submitted after AJAX complete.
|
Mark forms as not submitted after AJAX complete.
|
JavaScript
|
mit
|
DarvinStudio/DarvinAdminBundle,DarvinStudio/DarvinAdminBundle,DarvinStudio/DarvinAdminBundle
|
6c355830dcf91e90e3fce6f2ff9d59654716c8b7
|
bin/source.js
|
bin/source.js
|
var fs = require('fs'),
path = require('path'),
util = require('../lib/util');
var Source = util.inherit(Object, {
_initialize: function (root) {
this._root = root;
},
travel: function (callback, pathname) {
pathname = pathname || '';
var root = this._root,
node = path.join(root, pathname),
stats = fs.statSync(node),
self = this;
if (stats.isFile()) {
callback(pathname, fs.readFileSync(node));
} else if (stats.isDirectory()) {
fs.readdirSync(node).forEach(function (filename) {
self.travel(callback, path.join(pathname, filename));
});
}
}
});
module.exports = Source;
|
var fs = require('fs'),
path = require('path'),
util = require('../lib/util');
var Source = util.inherit(Object, {
_initialize: function (root) {
this._root = root;
},
travel: function (callback, pathname) {
pathname = pathname || '';
var root = this._root,
node = path.join(root, pathname),
stats = fs.statSync(node),
self = this;
if (stats.isFile()) {
callback(pathname, fs.readFileSync(node));
} else if (stats.isDirectory() && pathname.charAt(0) != '.'){
fs.readdirSync(node).forEach(function (filename) {
self.travel(callback, path.join(pathname, filename));
});
}
}
});
module.exports = Source;
|
Fix read hidden directory error.
|
Fix read hidden directory error.
|
JavaScript
|
mit
|
nqdeng/ucc
|
147b15ee4b14c2a69fb12b17d7742f0760eb63f1
|
server/routes/session.js
|
server/routes/session.js
|
var router = require('express').Router();
var jwt = require('jsonwebtoken');
var jwtSecret = require('../config/jwt_secret');
var User = require('../models/user');
router.post('/', function(req, res) {
User.findOne({ username: req.body.user.username }).then(function(user) {
if (user) {
user.authenticate(req.body.user.password, function(isMatch) {
var token = jwt.sign(user._id, jwtSecret, { expiresInMinutes: 60*24 });
if (isMatch) { res.json({ auth_token: token, user: user }); }
else { res.json({ error: "Could not authenticate." }); }
});
}
});
});
module.exports = router;
|
var router = require('express').Router();
var jwt = require('jsonwebtoken');
var jwtSecret = require('../config/jwt_secret');
var User = require('../models/user');
router.post('/', function(req, res) {
User.findOne({ username: req.body.user.username }).then(function(user) {
if (user) {
user.authenticate(req.body.user.password, function(isMatch) {
var token = jwt.sign(user._id, jwtSecret, { expiresIn: 24*60*60 });
if (isMatch) { res.json({ auth_token: token, user: user }); }
else { res.json({ error: "Could not authenticate." }); }
});
}
});
});
module.exports = router;
|
Use expiresIn instead of expiresInMinutes.
|
Use expiresIn instead of expiresInMinutes.
expiresInMinutes and expiresInSeconds is deprecated.
|
JavaScript
|
mit
|
unixmonkey/caedence.net-2015,unixmonkey/caedence.net-2015
|
386bd63f8d21fde74018815d410179758f5241cf
|
server/store/requests.js
|
server/store/requests.js
|
const redis = require('./redis');
const config = require('./config');
const getRequest = async (requestId) => {
// Set TTL for request
redis.expire(`requests:${requestId}`, config('requests_ttl'));
return await redis.hgetallAsync(`requests:${requestId}`);
};
const createRequest = async (requestDetails) => {
// get new unique id for request
const requestId = await redis.incrAsync('next_request_id');
// create a new request entry in Redis
const {user_id, pickup, dropoff, requested_pickup_time, size, weight} = requestDetails;
const [pickup_lat, pickup_long] = pickup.split(',');
const [dropoff_lat, dropoff_long] = dropoff.split(',');
redis.hmsetAsync(`requests:${requestId}`,
'user_id', user_id,
'pickup_lat', pickup_lat,
'pickup_long', pickup_long,
'dropoff_lat', dropoff_lat,
'dropoff_long', dropoff_long,
'requested_pickup_time', requested_pickup_time,
'size', size,
'weight', weight,
);
// Set TTL for request
redis.expire(`requests:${requestId}`, 43200);
return requestId;
};
const deleteRequest = async (requestId) => {
return await redis.del(`requests:${requestId}`);
};
module.exports = {
createRequest,
getRequest,
deleteRequest
};
|
const redis = require('./redis');
const config = require('../config/index.js');
const getRequest = async (requestId) => {
// Set TTL for request
redis.expire(`requests:${requestId}`, config('requests_ttl'));
return await redis.hgetallAsync(`requests:${requestId}`);
};
const createRequest = async (requestDetails) => {
// get new unique id for request
const requestId = await redis.incrAsync('next_request_id');
// create a new request entry in Redis
const {user_id, pickup, dropoff, requested_pickup_time, size, weight} = requestDetails;
const [pickup_lat, pickup_long] = pickup.split(',');
const [dropoff_lat, dropoff_long] = dropoff.split(',');
redis.hmsetAsync(`requests:${requestId}`,
'user_id', user_id,
'pickup_lat', pickup_lat,
'pickup_long', pickup_long,
'dropoff_lat', dropoff_lat,
'dropoff_long', dropoff_long,
'requested_pickup_time', requested_pickup_time,
'size', size,
'weight', weight,
);
// Set TTL for request
redis.expire(`requests:${requestId}`, 43200);
return requestId;
};
const deleteRequest = async (requestId) => {
return await redis.del(`requests:${requestId}`);
};
module.exports = {
createRequest,
getRequest,
deleteRequest
};
|
Fix dependency inclusion for require statement
|
Fix dependency inclusion for require statement
|
JavaScript
|
mit
|
DAVFoundation/missioncontrol,DAVFoundation/missioncontrol,DAVFoundation/missioncontrol
|
0ab40cc1769b66a7e72891a79a204b8c0455933f
|
lib/loadLists.js
|
lib/loadLists.js
|
var fs = require("fs");
var path = require("path");
var _ = require("lodash");
var animals;
var adjectives;
module.exports = function () {
if (animals && adjectives) {
return { animals : animals, adjectives : adjectives };
}
adjectives = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "adjectives.json")));
animals = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "animals.json")));
_.each(adjectives, function (word, idx) { adjectives[idx] = word.toLowerCase(); });
_.each(animals, function (word, idx) { animals[idx] = word.toLowerCase(); });
return { adjectives : adjectives, animals : animals };
};
module.exports.NUM_ADJECTIVES = 8981;
module.exports.NUM_ANIMALS = 590;
|
var fs = require("fs");
var path = require("path");
var _ = require("lodash");
var animals;
var adjectives;
module.exports = function () {
if (animals && adjectives) {
return { animals : animals, adjectives : adjectives };
}
adjectives = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "adjectives.json")));
animals = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "lists", "animals.json")));
_.each(adjectives, function (word, idx) { adjectives[idx] = word.toLowerCase(); });
_.each(animals, function (word, idx) { animals[idx] = word.toLowerCase(); });
return { adjectives : adjectives, animals : animals };
};NUM_
module.exports.NUM_ADJECTIVES = 1500;
module.exports.NUM_ANIMALS = 1750;
|
Fix adjective and number count to match the updated lists.
|
Fix adjective and number count to match the updated lists.
|
JavaScript
|
mit
|
a-type/adjective-adjective-animal,a-type/adjective-adjective-animal,gswalden/adjective-adjective-animal
|
4ca82da87e04c8b0b2d9a73ae67c7af99e7888da
|
src/store.js
|
src/store.js
|
import { createStore } from 'redux';
import reducer from 'reducers';
import initialState from 'initialState';
const store = createStore(reducer, initialState,
window.devToolsExtension ? window.devToolsExtension() : undefined
);
export default store;
|
import { createStore } from 'redux';
import reducer from 'reducers';
import initialState from 'initialState';
const devToolExtension = (() => {
if ('production' !== process.env.NODE_ENV) {
return window.devToolsExtension ? window.devToolsExtension() : undefined;
} else {
return undefined;
}
})();
export default createStore(reducer, initialState, devToolExtension);
|
Remove Redux devtools from production build
|
Remove Redux devtools from production build
|
JavaScript
|
mit
|
vincentriemer/io-808,vincentriemer/io-808,vincentriemer/io-808
|
a172dc9a3ee1343933140b97f8a2bca48c43cff6
|
js.js
|
js.js
|
var through = require('through')
, falafel = require('falafel')
, unparse = require('escodegen').generate
, util = require('util')
, minimist = require('minimist')
var argv = minimist(process.argv.slice(2))
var defaultLang = argv['jedify-lang'] || process.env['JEDIFY_LANG'] || 'en'
var re = /\.js$/
module.exports = function (file, options) {
if (!re.test(file)) return through()
options = options || {}
var lang = options.lang || defaultLang;
var buf = []
, stream = through(write, end)
return stream
function write(chunk) {
buf.push(chunk)
}
function end () {
var output = buf.join('')
try {
output = falafel(output, function (node) {
if (node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'requirePo')
{
var dir = new Function([], 'return ' + unparse(node.arguments[0]))()
dir = util.format(dir, lang)
node.update('require(' + JSON.stringify(dir) + ')')
}
}).toString()
} catch (err) {
this.emit('error', new Error(err.toString().replace('Error: ', '') + ' (' + file + ')'))
}
stream.queue(output)
stream.queue(null)
}
}
|
var through = require('through')
, falafel = require('falafel')
, unparse = require('escodegen').generate
, util = require('util')
, minimist = require('minimist')
var defaultLang = process.env['JEDIFY_LANG'] || 'en'
var re = /\.js$/
module.exports = function (file, options) {
if (!re.test(file)) return through()
options = options || {}
var lang = options.lang || defaultLang
var buf = []
, stream = through(write, end)
return stream
function write(chunk) {
buf.push(chunk)
}
function end () {
var output = buf.join('')
try {
output = falafel(output, function (node) {
if (node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'requirePo')
{
var dir = new Function([], 'return ' + unparse(node.arguments[0]))()
dir = util.format(dir, lang)
node.update('require(' + JSON.stringify(dir) + ')')
}
}).toString()
} catch (err) {
this.emit('error', new Error(err.toString().replace('Error: ', '') + ' (' + file + ')'))
}
stream.queue(output)
stream.queue(null)
}
}
|
Remove `--jedify-lang` command line option
|
Remove `--jedify-lang` command line option
|
JavaScript
|
mit
|
tellnes/jedify
|
25e44bb5e37df64916cd4d249bbf7d10115e2d49
|
src/utils.js
|
src/utils.js
|
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
throw new Error(response.statusText);
}
export function getShortDate(dateString) {
const d = new Date(dateString);
return `${d.getMonth() + 1}/${d.getDate()}/${d.getFullYear() % 100}`;
}
|
import moment from 'moment';
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.json();
}
throw new Error(response.statusText);
}
export function getShortDate(dateString) {
return moment(dateString).format('MM/DD/YY');
}
|
Fix getShortDate to return leading zeros
|
Fix getShortDate to return leading zeros
|
JavaScript
|
mit
|
ZachGawlik/print-to-resist,ZachGawlik/print-to-resist
|
a8e690949e1ae14faa228a9df9f5dce32183d6fa
|
lib/apis/fetch.js
|
lib/apis/fetch.js
|
import { defaults } from 'lodash';
import request from 'request';
import config from '../../config';
export default (url, options = {}) => {
return new Promise((resolve, reject) => {
const opts = defaults(options, {
method: 'GET',
timeout: config.REQUEST_TIMEOUT_MS,
});
request(url, opts, (err, response) => {
if (!!err || response.statusCode !== 200) {
return reject(err || new Error(response.body));
}
try {
const shouldParse = typeof response.body === 'string';
const parsed = shouldParse ? JSON.parse(response.body) : response.body;
resolve({
body: parsed,
headers: response.headers,
});
} catch (error) {
reject(error);
}
});
});
};
|
import { get, defaults, compact } from 'lodash';
import request from 'request';
import config from '../../config';
export default (url, options = {}) => {
return new Promise((resolve, reject) => {
const opts = defaults(options, {
method: 'GET',
timeout: config.REQUEST_TIMEOUT_MS,
});
request(url, opts, (err, response) => {
if (!!err || response.statusCode !== 200) {
if (err) return reject(err);
const message = compact([
get(response, 'request.uri.href'),
response.body,
]).join(' - ');
const error = new Error(message);
error.statusCode = response.statusCode;
return reject(error);
}
try {
const shouldParse = typeof response.body === 'string';
const parsed = shouldParse ? JSON.parse(response.body) : response.body;
resolve({
body: parsed,
headers: response.headers,
});
} catch (error) {
reject(error);
}
});
});
};
|
Improve error handling by returning the `statusCode` and including the failed URL in the rejected Error
|
Improve error handling by returning the `statusCode` and including the failed URL in the rejected Error
|
JavaScript
|
mit
|
artsy/metaphysics,broskoski/metaphysics,mzikherman/metaphysics-1,1aurabrown/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,craigspaeth/metaphysics,craigspaeth/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1
|
fbc505bfc58d825d5440a260293ea3dcae04d56d
|
addon/services/google-charts.js
|
addon/services/google-charts.js
|
import RSVP from 'rsvp';
import Service from '@ember/service';
export default Service.extend({
language: 'en',
init() {
this._super(...arguments);
this.googlePackages = this.googlePackages || ['corechart', 'bar', 'line', 'scatter'];
this.defaultOptions = this.defaultOptions || {
animation: {
duration: 500,
startup: false,
},
};
},
loadPackages() {
const { google: { charts } } = window;
return new RSVP.Promise((resolve, reject) => {
const packagesAreLoaded = charts.loader;
if (packagesAreLoaded) {
resolve();
} else {
charts.load('current', {
language: this.get('language'),
packages: this.get('googlePackages'),
});
charts.setOnLoadCallback((ex) => {
if (ex) { reject(ex); }
resolve();
});
}
});
},
});
|
import RSVP from 'rsvp';
import Service from '@ember/service';
export default Service.extend({
language: 'en',
init() {
this._super(...arguments);
this.googlePackages = this.googlePackages || ['corechart', 'bar', 'line', 'scatter'];
this.defaultOptions = this.defaultOptions || {
animation: {
duration: 500,
startup: false,
},
};
},
loadPackages() {
const { google: { charts, visualization } } = window;
return new RSVP.Promise((resolve, reject) => {
if (visualization !== undefined) {
resolve();
} else {
charts.load('current', {
language: this.get('language'),
packages: this.get('googlePackages'),
});
charts.setOnLoadCallback((ex) => {
if (ex) { reject(ex); }
resolve();
});
}
});
},
});
|
Fix google visualization undefined error
|
Fix google visualization undefined error
similar to https://github.com/sir-dunxalot/ember-google-charts/pull/56 (with failing tests), see also the comment in https://github.com/sir-dunxalot/ember-google-charts/issues/57
|
JavaScript
|
mit
|
sir-dunxalot/ember-google-charts,sir-dunxalot/ember-google-charts
|
1944548e8ea77174d0929230e07a78220d3fe2ff
|
app/assets/javascripts/url-helpers.js
|
app/assets/javascripts/url-helpers.js
|
var getUrlVar = function(key) {
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
};
var getIDFromURL = function(key) {
var result = new RegExp(key + "/([0-9a-zA-Z\-]*)", "i").exec(window.location.pathname);
if (result === 'new') {
return '';
}
return result && unescape(result[1]) || '';
};
|
var getUrlVar = function(key) {
var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search);
return result && decodeURIComponent(result[1]) || '';
};
var getIDFromURL = function(key) {
var result = new RegExp(key + '/([0-9a-zA-Z\-]*)', 'i').exec(window.location.pathname);
if (result === 'new') {
return '';
}
return result && decodeURIComponent(result[1]) || '';
};
|
Fix mixture of quotes and deprecated unescape method usage
|
Fix mixture of quotes and deprecated unescape method usage
|
JavaScript
|
mit
|
openfarmcc/OpenFarm,RickCarlino/OpenFarm,CloCkWeRX/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,CloCkWeRX/OpenFarm,CloCkWeRX/OpenFarm,CloCkWeRX/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm
|
7fe3fdf119d99e40b9917696a90244f05a0205ee
|
paths.js
|
paths.js
|
var src = exports.src = {};
src.app = [
'src/index.js',
'src/api.js',
'src/app.js'
];
src.dummy = [
'src/dummy.js',
'src/fixtures.js'
];
src.lib = [].concat(
src.app,
src.dummy);
src.demo = [].concat(src.lib, [
'src/demo.js'
]);
src.prd = [].concat(src.app, [
'src/init.js'
]);
src.all = [
'src/**/*.js'
];
module.exports = {
src: src,
dest: {
prd: 'lib/vumi-ureport.js',
demo: 'lib/vumi-ureport.demo.js'
},
test: {
spec: [
'test/**/*.test.js'
],
requires: [
'test/setup.js'
]
}
};
|
var src = exports.src = {};
src.app = [
'src/index.js',
'src/api.js',
'src/app.js'
];
src.dummy = [
'src/fixtures.js',
'src/dummy.js'
];
src.lib = [].concat(
src.app,
src.dummy);
src.demo = [].concat(src.lib, [
'src/demo.js'
]);
src.prd = [].concat(src.app, [
'src/init.js'
]);
src.all = [
'src/**/*.js'
];
module.exports = {
src: src,
dest: {
prd: 'lib/vumi-ureport.js',
demo: 'lib/vumi-ureport.demo.js'
},
test: {
spec: [
'test/**/*.test.js'
],
requires: [
'test/setup.js'
]
}
};
|
Switch around fixtures.js and dummy.js in path config
|
Switch around fixtures.js and dummy.js in path config
|
JavaScript
|
bsd-3-clause
|
praekelt/vumi-ureport,praekelt/vumi-ureport
|
e9c8040befea76e0462f845822d136f39bdfb17a
|
app/components/child-comment.js
|
app/components/child-comment.js
|
import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: ['offset:col-md-offset-1'],
offset: false,
timestamp: function() {
return moment.unix(this.get('comment.time')).fromNow();
}.property('time'),
actions: {
followUser: function(userId) {
var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
var authToken = JSON.parse(sessionData)['token'];
var uid = JSON.parse(sessionData)['uid'];
console.log('Auth token: ' + authToken);
console.log('uid: ' + uid);
var followTarget = userId;
var record = this.store.find('account', uid).then(addFollowing);
function addFollowing(user) {
var newList = user.get('following').push(userId);
user.save().then(null, function(error) {
console.log(error);
});
}
console.log('Following ' + userId);
},
saveComment: function(commentId) {
console.log('Comment saved');
}
}
});
|
import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: ['offset:col-md-offset-1'],
offset: false,
timestamp: function() {
return moment.unix(this.get('comment.time')).fromNow();
}.property('time'),
actions: {
followUser: function(userId) {
var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
var authToken = JSON.parse(sessionData)['token'];
var uid = JSON.parse(sessionData)['uid'];
console.log('Auth token: ' + authToken);
console.log('uid: ' + uid);
var followTarget = userId;
this.store.find('account', uid).then(addFollowing);
function addFollowing(user) {
var newList = user.get('following').push(userId);
user.save().then(null, function(error) {
console.log(error);
});
}
console.log('Following ' + userId);
},
saveComment: function(commentId) {
var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
var authToken = JSON.parse(sessionData)['token'];
var uid = JSON.parse(sessionData)['uid'];
this.store.find('account', uid).then(function(o) {
o.get('favorites').push(commentId);
o.save().then(function(success) {
console.log('Comment saved');
}, function(error) {
console.log('Error: Comment was not saved');
});
});
}
}
});
|
Save favorite comments to account
|
Save favorite comments to account
|
JavaScript
|
mit
|
stevenwu/hacker-news
|
3436424d9d945c3132fa196f219fe08fd6887dcd
|
lib/optionlist.js
|
lib/optionlist.js
|
import PropTypes from "prop-types";
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
View,
TouchableWithoutFeedback,
ViewPropTypes
} from "react-native";
export default class OptionList extends Component {
static defaultProps = {
onSelect: () => {}
};
static propTypes = {
style: ViewPropTypes.style,
onSelect: PropTypes.func
};
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }}
onPress={() => onSelect(item.props.children, item.props.value)}
>
<View
style={[
{ borderWidth: 0 },
item.props.value === selected ? selectedStyle : null
]}
>
{item}
</View>
</TouchableWithoutFeedback>
));
return (
<View style={[styles.scrollView, style]}>
<ScrollView automaticallyAdjustContentInsets={false} bounces={false}>
{renderedItems}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
scrollView: {
height: 120,
width: 300,
borderWidth: 1
}
});
|
import PropTypes from "prop-types";
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
View,
TouchableWithoutFeedback,
ViewPropTypes
} from "react-native";
export default class OptionList extends Component {
static defaultProps = {
onSelect: () => {}
};
static propTypes = {
style: ViewPropTypes.style,
onSelect: PropTypes.func
};
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
if (!item) return null
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }}
onPress={() => onSelect(item.props.children, item.props.value)}
>
<View
style={[
{ borderWidth: 0 },
item.props.value === selected ? selectedStyle : null
]}
>
{item}
</View>
</TouchableWithoutFeedback>
));
return (
<View style={[styles.scrollView, style]}>
<ScrollView automaticallyAdjustContentInsets={false} bounces={false}>
{renderedItems}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
scrollView: {
height: 120,
width: 300,
borderWidth: 1
}
});
|
Make OptionList return gracefully when iterating over falsy values
|
Make OptionList return gracefully when iterating over falsy values
|
JavaScript
|
mit
|
gs-akhan/react-native-chooser
|
c0204e51c9077f8771f495bb1ffa224e25655322
|
website/app/components/project/processes/mc-project-processes.component.js
|
website/app/components/project/processes/mc-project-processes.component.js
|
(function (module) {
module.component('mcProjectProcesses', {
templateUrl: 'components/project/processes/mc-project-processes.html',
controller: 'MCProjectProcessesComponentController'
});
module.controller('MCProjectProcessesComponentController', MCProjectProcessesComponentController);
MCProjectProcessesComponentController.$inject = ["project", "$stateParams"];
function MCProjectProcessesComponentController(project, $stateParams) {
var ctrl = this;
ctrl.processes = project.get().processes;
///////////////////////////
}
}(angular.module('materialscommons')));
|
(function (module) {
module.component('mcProjectProcesses', {
templateUrl: 'components/project/processes/mc-project-processes.html',
controller: 'MCProjectProcessesComponentController'
});
module.controller('MCProjectProcessesComponentController', MCProjectProcessesComponentController);
MCProjectProcessesComponentController.$inject = ['project', '$stateParams', '$state', '$filter'];
function MCProjectProcessesComponentController(project, $stateParams, $state, $filter) {
var ctrl = this;
ctrl.processes = project.get().processes;
if (!$stateParams.process_id && ctrl.processes.length) {
ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
var firstProcess = ctrl.processes[0];
$state.go('project.processes.process', {process_id: firstProcess.id});
}
///////////////////////////
}
}(angular.module('materialscommons')));
|
Sort processes and if there is no process id go to the first one.
|
Sort processes and if there is no process id go to the first one.
|
JavaScript
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
2db58a7024cade6d205a55afcfa40cf12bd43c69
|
index.js
|
index.js
|
'use strict';
var deepFind = function(obj, path) {
if ((typeof obj !== "object") | obj === null) {
return undefined;
}
if (typeof path === 'string') {
path = path.split('.');
}
if (!Array.isArray(path)) {
path = path.concat();
}
return path.reduce(function (o, part) {
var keys = part.match(/\[(.*?)\]/);
if (keys) {
var key = part.replace(keys[0], '');
return o[key][keys[1]];
}
return o[part];
}, obj);
};
module.exports = deepFind;
|
'use strict';
var deepFind = function(obj, path) {
if (((typeof obj !== "object") && (typeof obj !== "function")) | obj === null) {
return undefined;
}
if (typeof path === 'string') {
path = path.split('.');
}
if (!Array.isArray(path)) {
path = path.concat();
}
return path.reduce(function (o, part) {
var keys = part.match(/\[(.*?)\]/);
if (keys) {
var key = part.replace(keys[0], '');
return o[key][keys[1]];
}
return o[part];
}, obj);
};
module.exports = deepFind;
|
Add capability to retrieve properties of functions
|
Add capability to retrieve properties of functions
|
JavaScript
|
mit
|
yashprit/deep-find
|
c9a7cc0dd50e934bb214c7988081b2bbe5bfa397
|
lib/stringutil.js
|
lib/stringutil.js
|
/*jshint node: true */
"use strict";
module.exports = {
/**
* Returns true if and only if the string value of the first argument
* ends with the given suffix. Otherwise, returns false. Does NOT support
* the length argument.
*
* Normally, one would just use String.prototype.endsWith, but since there
* are Node versions out there which don't support ES6 yet, this function
* exists. It either wraps the native method, or alternatively performs
* the check manually.
*/
endsWith: function (str, suffix) {
var subject = str.toString();
if (typeof subject.endsWith === "function") {
return subject.endsWith(suffix);
}
if (suffix === "") {
return true;
}
return subject.slice(-suffix.length) === suffix;
},
};
|
/*jshint node: true */
"use strict";
module.exports = {
/**
* Returns true if and only if the string value of the first argument
* ends with the given suffix. Otherwise, returns false. Does NOT support
* the length argument.
*
* Normally, one would just use String.prototype.endsWith, but since there
* are Node versions out there which don't support ES6 yet, this function
* exists. It either wraps the native method, or alternatively performs
* the check manually.
*/
endsWith: function (str, suffix) {
var subject = str.toString();
suffix = "" + suffix;
if (typeof subject.endsWith === "function") {
return subject.endsWith(suffix);
}
if (suffix === "") {
return true;
}
return subject.slice(-suffix.length) === suffix;
},
};
|
Fix TypeError for endsWith() with `null` suffix
|
Fix TypeError for endsWith() with `null` suffix
|
JavaScript
|
mit
|
JangoBrick/teval,JangoBrick/teval
|
d4a1349279c3218f75db94e3243cd272bf05e5e4
|
app.js
|
app.js
|
/*jshint esversion: 6 */
const primed = angular.module('primed', ['ngRoute', 'ngResource']);
|
/*jshint esversion: 6 */
const primed = angular.module('primed', ['ngRoute', 'ngResource']);
primed.controller('homeController', ['$scope', function($scope) {
}]);
primed.controller('forecastController', ['$scope', function($scope) {
}]);
|
Set up controllers for home and forecast
|
Set up controllers for home and forecast
|
JavaScript
|
mit
|
adam-rice/Primed,adam-rice/Primed
|
4bdcfd07a97de370aead0cbb8a9707568c9e4138
|
test/page.js
|
test/page.js
|
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var page = require('../').parse.page;
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);
describe('Page parsing', function() {
it('should detection sections', function() {
assert.equal(LEXED.length, 3);
});
it('should detection section types', function() {
assert.equal(LEXED[0].type, 'normal');
assert.equal(LEXED[1].type, 'exercise');
assert.equal(LEXED[2].type, 'normal');
});
it('should gen content for normal sections', function() {
assert(LEXED[0].content);
assert(LEXED[2].content);
});
it('should gen code and content for exercise sections', function() {
assert(LEXED[1].content);
assert(LEXED[1].code);
assert(LEXED[1].code.base);
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
});
});
|
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var page = require('../').parse.page;
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);
var HR_CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/HR_PAGE.md'), 'utf8');
var HR_LEXED = page(HR_CONTENT);
describe('Page parsing', function() {
it('should detection sections', function() {
assert.equal(LEXED.length, 3);
});
it('should detection section types', function() {
assert.equal(LEXED[0].type, 'normal');
assert.equal(LEXED[1].type, 'exercise');
assert.equal(LEXED[2].type, 'normal');
});
it('should gen content for normal sections', function() {
assert(LEXED[0].content);
assert(LEXED[2].content);
});
it('should gen code and content for exercise sections', function() {
assert(LEXED[1].content);
assert(LEXED[1].code);
assert(LEXED[1].code.base);
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
});
it('should merge sections correctly', function() {
// One big section
assert.equal(HR_LEXED.length, 1);
// HRs inserted correctly
assert.equal(HR_LEXED[0].content.match(/<hr>/g).length, 2);
});
});
|
Add tests for section merging
|
Add tests for section merging
|
JavaScript
|
apache-2.0
|
svenkatreddy/gitbook,intfrr/gitbook,guiquanz/gitbook,minghe/gitbook,GitbookIO/gitbook,qingying5810/gitbook,ferrior30/gitbook,haamop/documentation,palerdot/gitbook,gaearon/gitbook,ShaguptaS/gitbook,escopecz/documentation,rohan07/gitbook,bjlxj2008/gitbook,gaearon/gitbook,ferrior30/gitbook,jocr1627/gitbook,bjlxj2008/gitbook,iflyup/gitbook,jasonslyvia/gitbook,youprofit/gitbook,alex-dixon/gitbook,guiquanz/gitbook,CN-Sean/gitbook,shibe97/gitbook,xiongjungit/gitbook,switchspan/gitbook,jasonslyvia/gitbook,npracht/documentation,nycitt/gitbook,tshoper/gitbook,gencer/gitbook,youprofit/gitbook,npracht/documentation,hongbinz/gitbook,justinleoye/gitbook,FKV587/gitbook,athiruban/gitbook,wewelove/gitbook,codepiano/gitbook,intfrr/gitbook,vehar/gitbook,a-moses/gitbook,ZachLamb/gitbook,xcv58/gitbook,iamchenxin/gitbook,snowsnail/gitbook,palerdot/gitbook,CN-Sean/gitbook,sunlianghua/gitbook,megumiteam/documentation,grokcoder/gitbook,sunlianghua/gitbook,minghe/gitbook,hujianfei1989/gitbook,qingying5810/gitbook,gdbooks/gitbook,ryanswanson/gitbook,jocr1627/gitbook,webwlsong/gitbook,hujianfei1989/gitbook,iflyup/gitbook,OriPekelman/gitbook,haamop/documentation,grokcoder/gitbook,vehar/gitbook,alex-dixon/gitbook,bradparks/gitbook,wewelove/gitbook,iamchenxin/gitbook,xcv58/gitbook,sudobashme/gitbook,escopecz/documentation,rohan07/gitbook,snowsnail/gitbook,lucciano/gitbook,a-moses/gitbook,nycitt/gitbook,gencer/gitbook,2390183798/gitbook,Abhikos/gitbook,mautic/documentation,thelastmile/gitbook,mruse/gitbook,codepiano/gitbook,anrim/gitbook,mautic/documentation,bradparks/gitbook,kamyu104/gitbook,JohnTroony/gitbook,mruse/gitbook,JohnTroony/gitbook,xxxhycl2010/gitbook,megumiteam/documentation,yaonphy/SwiftBlog,boyXiong/gitbook,OriPekelman/gitbook,justinleoye/gitbook,FKV587/gitbook,lucciano/gitbook,xiongjungit/gitbook,ZachLamb/gitbook,ShaguptaS/gitbook,Keystion/gitbook,JozoVilcek/gitbook,hongbinz/gitbook,gdbooks/gitbook,2390183798/gitbook,kamyu104/gitbook,webwlsong/gitbook,tshoper/gitbook,svenkatreddy/gitbook,tzq668766/gitbook,tzq668766/gitbook,athiruban/gitbook,strawluffy/gitbook,switchspan/gitbook,thelastmile/gitbook,shibe97/gitbook,boyXiong/gitbook,xxxhycl2010/gitbook,sudobashme/gitbook
|
9bb668b1066497413f8abd0fff79e835ff781662
|
index.js
|
index.js
|
var path = require('path');
var findParentDir = require('find-parent-dir');
var fs = require('fs');
function resolve(targetUrl, source) {
var packageRoot = findParentDir.sync(source, 'node_modules');
if (!packageRoot) {
return null;
}
var filePath = path.resolve(packageRoot, 'node_modules', targetUrl);
var isPotentiallyDirectory = !path.extname(filePath);
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
return path.resolve(filePath, 'index');
}
if (fs.existsSync(filePath)) {
return path.resolve(filePath, 'index');
}
}
if (fs.existsSync(path.dirname(filePath))) {
return filePath;
}
return resolve(targetUrl, path.dirname(packageRoot));
}
module.exports = function importer (url, prev, done) {
return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null;
};
|
var path = require('path');
var findParentDir = require('find-parent-dir');
var fs = require('fs');
function resolve(targetUrl, source) {
var packageRoot = findParentDir.sync(source, 'node_modules');
if (!packageRoot) {
return null;
}
var filePath = path.resolve(packageRoot, 'node_modules', targetUrl);
var isPotentiallyDirectory = !path.extname(filePath);
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
return filePath + '.scss';
}
if (fs.existsSync(filePath)) {
return path.resolve(filePath, 'index');
}
}
if (fs.existsSync(path.dirname(filePath))) {
return filePath;
}
return resolve(targetUrl, path.dirname(packageRoot));
}
module.exports = function importer (url, prev, done) {
return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null;
};
|
Fix path on .scss file detected
|
Fix path on .scss file detected
|
JavaScript
|
apache-2.0
|
matthewdavidson/node-sass-tilde-importer
|
d21950affe91ead5be06c1197441577053464dcc
|
index.js
|
index.js
|
'use strict';
var throttle = require('throttleit');
function requestProgress(request, options) {
var reporter;
var delayTimer;
var delayCompleted;
var totalSize;
var previousReceivedSize;
var receivedSize = 0;
var state = {};
options = options || {};
options.throttle = options.throttle == null ? 1000 : options.throttle;
options.delay = options.delay || 0;
request
.on('response', function (response) {
state.total = totalSize = Number(response.headers['content-length']);
receivedSize = 0;
// Check if there's no total size or is invalid (NaN)
if (!totalSize) {
return;
}
// Throttle the function
reporter = throttle(function () {
// If there received size is the same, abort
if (previousReceivedSize === receivedSize) {
return;
}
state.received = previousReceivedSize = receivedSize;
state.percent = Math.round(receivedSize / totalSize * 100);
request.emit('progress', state);
}, options.throttle);
// Delay the progress report
delayTimer = setTimeout(function () {
delayCompleted = true;
delayTimer = null;
}, options.delay);
})
.on('data', function (data) {
receivedSize += data.length;
if (delayCompleted) {
reporter();
}
})
.on('end', function () {
if (!delayCompleted) {
clearTimeout(delayTimer);
}
});
return request;
}
module.exports = requestProgress;
|
'use strict';
var throttle = require('throttleit');
function requestProgress(request, options) {
var reporter;
var delayTimer;
var delayCompleted;
var totalSize;
var previousReceivedSize;
var receivedSize = 0;
var state = {};
options = options || {};
options.throttle = options.throttle == null ? 1000 : options.throttle;
options.delay = options.delay || 0;
request
.on('request', function () {
receivedSize = 0;
})
.on('response', function (response) {
state.total = totalSize = Number(response.headers['content-length']);
receivedSize = 0;
// Check if there's no total size or is invalid (NaN)
if (!totalSize) {
return;
}
// Throttle the function
reporter = throttle(function () {
// If there received size is the same, abort
if (previousReceivedSize === receivedSize) {
return;
}
state.received = previousReceivedSize = receivedSize;
state.percent = Math.round(receivedSize / totalSize * 100);
request.emit('progress', state);
}, options.throttle);
// Delay the progress report
delayTimer = setTimeout(function () {
delayCompleted = true;
delayTimer = null;
}, options.delay);
})
.on('data', function (data) {
receivedSize += data.length;
if (delayCompleted) {
reporter();
}
})
.on('end', function () {
if (!delayCompleted) {
clearTimeout(delayTimer);
}
});
return request;
}
module.exports = requestProgress;
|
Reset size also on 'request'.
|
Reset size also on 'request'.
|
JavaScript
|
mit
|
IndigoUnited/node-request-progress
|
8aef4999d40fa0cedd3deb56daadbcd09eeece09
|
index.js
|
index.js
|
'use strict';
import { NativeAppEventEmitter, NativeModules } from 'react-native';
const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth;
const didChangeState = (callback) => {
var subscription = NativeAppEventEmitter.addListener(
ReactNativeBluetooth.StateChanged,
callback
);
ReactNativeBluetooth.notifyCurrentState();
return function() {
subscription.remove();
};
};
export default {
didChangeState,
};
|
'use strict';
import { NativeAppEventEmitter, NativeModules } from 'react-native';
const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth;
const didChangeState = (callback) => {
var subscription = NativeAppEventEmitter.addListener(
ReactNativeBluetooth.StateChanged,
callback
);
ReactNativeBluetooth.notifyCurrentState();
return function() {
subscription.remove();
};
};
const DefaultScanOptions = {
uuids: [],
timeout: 10000,
};
const Scan = {
stopAfter: (timeout) => {
return new Promise(resolve => {
setTimeout(() => {
ReactNativeBluetooth.stopScan()
.then(resolve)
.catch(console.log.bind(console));
}, timeout);
})
}
}
const startScan = (customOptions = {}) => {
let options = Object.assign({}, DefaultScanOptions, customOptions);
return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan);
}
const didDiscoverDevice = (callback) => {
var subscription = NativeAppEventEmitter.addListener(
ReactNativeBluetooth.DeviceDiscovered,
callback
);
return function() {
subscription.remove();
};
};
export default {
didChangeState,
startScan,
didDiscoverDevice,
};
|
Implement startScan(), stopScan() and didDiscoverDevice()
|
js: Implement startScan(), stopScan() and didDiscoverDevice()
|
JavaScript
|
apache-2.0
|
sogilis/react-native-bluetooth,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth,sogilis/react-native-bluetooth,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth
|
1a88800d7b13b65206818de6e472ceef30054892
|
index.js
|
index.js
|
const ghost = require('ghost');
ghost().then(function (ghostServer) {
ghostServer.start();
});
|
const ghost = require('ghost');
ghost({
config: path.join(__dirname, 'config.js')
}).then(function (ghostServer) {
ghostServer.start();
});
|
Add explicit config.js to ghost constructor
|
Add explicit config.js to ghost constructor
|
JavaScript
|
mit
|
jtanguy/clevercloud-ghost
|
a6542ba90043060ae4a878688a7913497913695d
|
index.js
|
index.js
|
"use strict";
var express = require("express");
module.exports = function () {
var app = express();
// 404 everything
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
return app;
};
|
"use strict";
var express = require("express");
module.exports = function () {
var app = express();
// fake handler for the books endpoints
app.get("/books/:isbn", function (req, res) {
var isbn = req.param("isbn");
res.jsonp({
isbn: isbn,
title: "Title of " + isbn,
author: "Author of " + isbn,
});
});
// 404 everything
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
return app;
};
|
Add handler to return faked book results
|
Add handler to return faked book results
|
JavaScript
|
agpl-3.0
|
OpenBookPrices/openbookprices-api
|
a326ba30f5781c1a1297bb20636023021ed4baab
|
tests/unit/components/tooltip-on-parent-test.js
|
tests/unit/components/tooltip-on-parent-test.js
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
let component;
moduleForComponent('tooltip-on-parent', 'Unit | Component | tooltip on parent', {
unit: true,
setup() {
component = this.subject();
},
});
test('The component registers itself', function(assert) {
const parentView = Ember.View.create({
renderTooltip() {
assert.ok(true,
'The renderTooltip() method should be called on the parent view after render');
}
});
assert.expect(4);
component.set('parentView', parentView);
assert.equal(component._state, 'preRender',
'Should create the component instance');
assert.ok(!!component.registerOnParent,
'The component should have a public registerOnParent method');
this.render();
assert.equal(component._state, 'inDOM');
});
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
let component;
moduleForComponent('tooltip-on-parent', 'Unit | Component | tooltip on parent', {
unit: true,
setup() {
component = this.subject();
},
});
test('The component registers itself', function(assert) {
const parentView = Ember.View.create({
renderTooltip() {
assert.ok(true,
'The renderTooltip() method should be called on the parent view after render');
}
});
assert.expect(3);
component.set('parentView', parentView);
assert.equal(component._state, 'preRender',
'Should create the component instance');
assert.ok(!!component.registerOnParent,
'The component should have a public registerOnParent method');
this.render();
});
|
Fix for tooltip on parent element being removed
|
Fix for tooltip on parent element being removed
|
JavaScript
|
mit
|
sir-dunxalot/ember-tooltips,cdl/ember-tooltips,cdl/ember-tooltips,zenefits/ember-tooltips,zenefits/ember-tooltips,kmiyashiro/ember-tooltips,maxhungry/ember-tooltips,sir-dunxalot/ember-tooltips,maxhungry/ember-tooltips,kmiyashiro/ember-tooltips
|
0ad5c3272b7e63337c4196b2ebc08eac07dfadc1
|
app/assets/javascripts/responses.js
|
app/assets/javascripts/responses.js
|
$(document).ready( function () {
$("button.upvote").click( function() {
var commentId = $(".upvote").data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: commentId },
dataType: 'JSON'
}).done( function (response) {
}).fail( function (response) {
console.log(response);
})
})
})
|
$(document).ready( function () {
$("button.upvote").click( function() {
var commentId = $(".upvote").data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: commentId },
dataType: 'JSON'
}).done( function (response) {
$("button.upvote").closest(".response").append("<p>" + response + "</p>")
}).fail( function (response) {
console.log("Failed. Here is the response:")
console.log(response);
})
})
})
|
Add ajax to upvote a response.
|
Add ajax to upvote a response.
|
JavaScript
|
mit
|
great-horned-owls-2014/dbc-what-is-this,great-horned-owls-2014/dbc-what-is-this
|
cdaf0617ab59f81b251ab92cb7f797e3b626dbc1
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict';
var meow = require('meow');
var zipGot = require('./');
var objectAssign = require('object-assign');
var cli = meow({
help: [
'Usage',
' zip-got <url> <exclude-patterns>... --cleanup --extract',
'',
'Example',
' zip-got http://unicorns.com/unicorns.zip \'__MACOSX/**\' \'bower.json\' \'README.md\' \'LICENSE.md\' --dest=\'./.tmp\' --cleanup --extract',
'',
'Options',
'--dest: dest path to download a zip file',
'--cleanup: remove the zip file after extracting',
'--extract: extract the zip file after downloading',
'',
'<url> url of zip file trying to download',
'<exclude-patterns> pattern to exclude some of the files when it is extracted'
]
});
var url = cli.input.shift();
var opts = objectAssign({
exclude: cli.input,
dest: cli.flags.dest || process.cwd(),
cleanup: cli.flags.cleanup,
extract: cli.flags.extract
});
zipGot(url, opts, function(err) {
if (err) {
console.error(err);
return;
}
console.log(url, 'has been downloaded');
});
|
#!/usr/bin/env node
'use strict';
var meow = require('meow');
var zipGot = require('./');
var objectAssign = require('object-assign');
var cli = meow({
help: [
'Usage',
' zip-got <url> <exclude-patterns>... --cleanup --extract',
'',
'Example',
' zip-got http://unicorns.com/unicorns.zip \'__MACOSX/**\' \'bower.json\' \'README.md\' \'LICENSE.md\' --dest=\'./.tmp\' --cleanup --extract',
'',
'Options',
'--dest: dest path to download a zip file',
'--cleanup: remove the zip file after extracting',
'--extract: extract the zip file after downloading',
'',
'<url> url of zip file trying to download',
'<exclude-patterns> pattern to exclude some of the files when it is extracted'
]
});
var url = cli.input.shift();
var opts = objectAssign({
exclude: cli.input,
dest: process.cwd()
}, cli.flags);
zipGot(url, opts, function(err) {
if (err) {
console.error(err);
return;
}
console.log(url, 'has been downloaded');
});
|
Fix code style of assign
|
Fix code style of assign
|
JavaScript
|
mit
|
ragingwind/zip-got,ragingwind/node-got-zip
|
75ef865f8867e45cfe60b8222de85ea20ac50670
|
server/controllers/userFiles.js
|
server/controllers/userFiles.js
|
//
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const path = require('path'),
send = require('koa-send'),
conf = require('../lib/conf');
const oneYearInSeconds = 60 * 60 * 24 * 365;
let dataDirectory = path.normalize(conf.get('files:upload_directory'));
// TBD: move this to library. Add exists check.
if (dataDirectory.charAt(0) !== path.sep) {
dataDirectory = path.join(__dirname, '..', '..', dataDirectory);
}
module.exports = function*() {
let file = this.params.file;
let firstTwo = file.substring(0, 2);
yield send(this, dataDirectory + path.sep + firstTwo + path.sep + file);
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
};
|
//
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const path = require('path'),
send = require('koa-send'),
conf = require('../lib/conf');
const oneYearInSeconds = 60 * 60 * 24 * 365;
let dataDirectory = path.normalize(conf.get('files:upload_directory'));
// TBD: move this to library. Add exists check.
if (dataDirectory.charAt(0) !== path.sep) {
dataDirectory = path.join(__dirname, '..', '..', dataDirectory);
}
module.exports = function*() {
let file = this.params.file;
let filePath = path.join(file.substring(0, 2), file);
yield send(this, filePath, { root: dataDirectory });
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
};
|
Fix serving of user uploaded files
|
Fix serving of user uploaded files
|
JavaScript
|
apache-2.0
|
ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas
|
81702fccfd16cae2feb1d083cfc782c1fb9ecc3c
|
src/js/utils/ScrollbarUtil.js
|
src/js/utils/ScrollbarUtil.js
|
import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
|
import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef != null && containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
|
Add null check for containerRef
|
Add null check for containerRef
|
JavaScript
|
apache-2.0
|
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
|
ec25aaaa53dcfa271f73a8f45fe65fd6e15f7973
|
src/utils/is-plain-object.js
|
src/utils/is-plain-object.js
|
// Adapted from https://github.com/jonschlinkert/is-plain-object
function isObject(val) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
}
function isObjectObject(o) {
return isObject(o) === true
&& Object.prototype.toString.call(o) === '[object Object]';
}
export default function isPlainObject(o) {
if (isObjectObject(o) === false) return false;
// If has modified constructor
const ctor = o.constructor;
if (typeof ctor !== 'function') return false;
// If has modified prototype
const prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
|
// Adapted from https://github.com/jonschlinkert/is-plain-object
function isObject(val) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
}
function isObjectObject(o) {
return isObject(o) === true
&& Object.prototype.toString.call(o) === '[object Object]';
}
export default function isPlainObject(o) {
if (isObjectObject(o) === false) return false;
// If has modified constructor
const ctor = o.constructor;
if (typeof ctor !== 'function') return false;
// If has modified prototype
const prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) { // eslint-disable-line no-prototype-builtins
return false;
}
// Most likely a plain Object
return true;
}
|
Disable the lint error about using hasOwnProperty. That call should be fine in this context.
|
Disable the lint error about using hasOwnProperty. That call should be fine in this context.
|
JavaScript
|
mit
|
chentsulin/react-redux-sweetalert
|
99f1680999747da59ef4b90bafddb467a92c5e19
|
assets/js/modules/optimize/index.js
|
assets/js/modules/optimize/index.js
|
/**
* Optimize module initialization.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import './datastore';
import { SetupMain as OptimizeSetup } from './components/setup';
import { SettingsMain as OptimizeSettings } from './components/settings';
import { fillFilterWithComponent } from '../../util';
/**
* Add components to the settings page.
*/
addFilter(
'googlesitekit.ModuleSettingsDetails-optimize',
'googlesitekit.OptimizeModuleSettingsDetails',
fillFilterWithComponent( OptimizeSettings )
);
/**
* Add component to the setup wizard.
*/
addFilter(
'googlesitekit.ModuleSetup-optimize',
'googlesitekit.OptimizeModuleSetupWizard',
fillFilterWithComponent( OptimizeSetup )
);
|
/**
* Optimize module initialization.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import './datastore';
import Data from 'googlesitekit-data';
import { SetupMain as OptimizeSetup } from './components/setup';
import { SettingsEdit, SettingsView } from './components/settings';
import { fillFilterWithComponent } from '../../util';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
/**
* Add component to the setup wizard.
*/
addFilter(
'googlesitekit.ModuleSetup-optimize',
'googlesitekit.OptimizeModuleSetupWizard',
fillFilterWithComponent( OptimizeSetup )
);
domReady( () => {
Data.dispatch( CORE_MODULES ).registerModule(
'optimize',
{
settingsEditComponent: SettingsEdit,
settingsViewComponent: SettingsView,
}
);
} );
|
Refactor Optimize with registered components.
|
Refactor Optimize with registered components.
|
JavaScript
|
apache-2.0
|
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
|
d4b9fd4ab129d3e5f8eefcdc368f951e8fd51bee
|
src/js/posts/components/search-posts-well.js
|
src/js/posts/components/search-posts-well.js
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.onSubmit) {
const q = this.q.value.trim();
if (q) {
this.props.onSubmit(q);
}
}
}
render() {
const {q, pending} = this.props;
return (
<Well>
<h4>Blog Search</h4>
<form autoComplete="off" onSubmit={this.handleSubmit}>
<InputGroup>
<FormControl inputRef={ ref => {
this.q = ref;
}}
defaultValue={q} />
<InputGroup.Button>
<Button disabled={pending}>
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</form>
</Well>
);
}
}
SearchPostsWell.propTypes = {
q: PropTypes.string,
pending: PropTypes.bool,
onSubmit: PropTypes.func
};
export default SearchPostsWell;
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.onSubmit) {
const q = this.q.value.trim();
if (q) {
this.props.onSubmit(q);
}
}
}
render() {
const {q, pending} = this.props;
return (
<Well>
<h4>Blog Search</h4>
<form autoComplete="off" onSubmit={this.handleSubmit}>
<InputGroup>
<FormControl inputRef={ ref => {
this.q = ref;
}}
defaultValue={q} />
<InputGroup.Button>
<Button disabled={pending} type="submit">
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</form>
</Well>
);
}
}
SearchPostsWell.propTypes = {
q: PropTypes.string,
pending: PropTypes.bool,
onSubmit: PropTypes.func
};
export default SearchPostsWell;
|
Use submit button type in search posts well.
|
Use submit button type in search posts well.
|
JavaScript
|
mit
|
akornatskyy/sample-blog-react-redux,akornatskyy/sample-blog-react-redux
|
507b31b8ec5b3234db3a32e2c0a0359c9ac2cccb
|
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/app/src/components/Counter/Counter.js
|
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/app/src/components/Counter/Counter.js
|
import React, {useState} from 'react';
import PropTypes from 'prop-types';
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
const increment = () => setCount(count + 1);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={increment}
>
Increment
</button>
</div>
);
};
Counter.propTypes = {
initialCount: PropTypes.number,
};
Counter.defaultProps = {
initialCount: 0,
};
export default Counter;
|
import React, {useState} from 'react';
import PropTypes from 'prop-types';
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
const increment = useCallback(() => setCount(count + 1), [count]);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={increment}
>
Increment
</button>
</div>
);
};
Counter.propTypes = {
initialCount: PropTypes.number,
};
Counter.defaultProps = {
initialCount: 0,
};
export default Counter;
|
Use useCallback so that `increment` is memoized
|
Use useCallback so that `increment` is memoized
|
JavaScript
|
isc
|
thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template
|
f24990cf94729e2aa25ea6e8cf4a32e0e38b150f
|
lib/control-panel.js
|
lib/control-panel.js
|
"use strict";
var messages = require("./messages");
var config = require("./config");
var snippetUtils = require("./snippet").utils;
var connect = require("connect");
var http = require("http");
/**
* Launch the server for serving the client JS plus static files
* @param {String} scriptTags
* @param {Object} options
* @param {Function} scripts
* @returns {http.Server}
*/
module.exports.launchControlPanel = function (scriptTags, options, scripts) {
var clientScripts = messages.clientScript(options, true);
var app =
connect()
.use(clientScripts.versioned, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
return http.createServer(app);
};
|
"use strict";
var messages = require("./messages");
var config = require("./config");
var snippetUtils = require("./snippet").utils;
var connect = require("connect");
var http = require("http");
/**
* Launch the server for serving the client JS plus static files
* @param {String} scriptTags
* @param {Object} options
* @param {Function} scripts
* @returns {http.Server}
*/
module.exports.launchControlPanel = function (scriptTags, options, scripts) {
var clientScripts = messages.clientScript(options, true);
var app =
connect()
.use(clientScripts.versioned, scripts)
.use(clientScripts.path, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
return http.createServer(app);
};
|
Make un-versioned client script return the latest
|
Make un-versioned client script return the latest
|
JavaScript
|
apache-2.0
|
EdwonLim/browser-sync,stevemao/browser-sync,stevemao/browser-sync,zhelezko/browser-sync,EdwonLim/browser-sync,syarul/browser-sync,BrowserSync/browser-sync,Plou/browser-sync,nitinsurana/browser-sync,schmod/browser-sync,chengky/browser-sync,BrowserSync/browser-sync,schmod/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,chengky/browser-sync,michaelgilley/browser-sync,d-g-h/browser-sync,mcanthony/browser-sync,felixdae/browser-sync,pepelsbey/browser-sync,beni55/browser-sync,harmoney-nikr/browser-sync,michaelgilley/browser-sync,Plou/browser-sync,nitinsurana/browser-sync,pmq20/browser-sync,syarul/browser-sync,guiquanz/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,d-g-h/browser-sync,mnquintana/browser-sync,lookfirst/browser-sync,markcatley/browser-sync,guiquanz/browser-sync,pepelsbey/browser-sync,naoyak/browser-sync,BrowserSync/browser-sync,zhelezko/browser-sync,BrowserSync/browser-sync,shelsonjava/browser-sync,cnbin/browser-sync,portned/browser-sync,pmq20/browser-sync,Iced-Tea/browser-sync,Iced-Tea/browser-sync,harmoney-nikr/browser-sync,portned/browser-sync,mcanthony/browser-sync,felixdae/browser-sync,nothiphop/browser-sync,beni55/browser-sync,shelsonjava/browser-sync,nothiphop/browser-sync,naoyak/browser-sync
|
57a15a5194bc95b77110150d06d05a7b870804ce
|
lib/graceful-exit.js
|
lib/graceful-exit.js
|
var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
function() {
process.exit(1);
}
);
function clearPlayers(players) {
var playerIds = Object.keys(players),
resolved = utils.promise.resolve();
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
};
};
|
var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
function() {
process.exit(0);
},
function() {
process.exit(1);
}
);
function clearPlayers(players) {
var playerIds = Object.keys(players),
resolved = utils.promise.resolve();
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
};
};
|
Add exit(1) if any promises fail during exit
|
Add exit(1) if any promises fail during exit
|
JavaScript
|
apache-2.0
|
radiodan/magic-button,radiodan/magic-button
|
8baf5366ca919593fe2f00dc245cba9eac984139
|
bot.js
|
bot.js
|
var Twit = require('twit');
var twitInfo = [consumer_key, consumer_secret, access_token, access_token_secret];
//use when testing locally
// var twitInfo = require('./config.js')
var twitter = new Twit(twitInfo);
var useUpperCase = function(wordList) {
var tempList = Object.keys(wordList).filter(function(word) {
return word[0] >= "A" && word[0] <= "Z";
});
return tempList[~~(Math.random()*tempList.length)];
};
var MarkovChain = require('markovchain')
, fs = require('fs')
, quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8'));
function generateSentence() {
return quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + ".";
}
function postTweet(sentence) {
var tweet = {
status: sentence
};
twitter.post('statuses/update', tweet , function(err, data, response) {
if (err) {
// console.log("5OMeTh1nG weNt wR0ng");
} else {
// console.log("Tweet sucessful");
}
});
}
postTweet(generateSentence);
// second parameter is in miliseconds
setInterval(postTweet(generateSentence), 1000*60*60*11);
|
var Twit = require('twit');
var twitInfo = [CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET];
//use when testing locally
// var twitInfo = require('./config.js')
var twitter = new Twit(twitInfo);
var useUpperCase = function(wordList) {
var tempList = Object.keys(wordList).filter(function(word) {
return word[0] >= "A" && word[0] <= "Z";
});
return tempList[~~(Math.random()*tempList.length)];
};
var MarkovChain = require('markovchain')
, fs = require('fs')
, quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8'));
function generateSentence() {
return quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + ".";
}
function postTweet(sentence) {
var tweet = {
status: sentence
};
twitter.post('statuses/update', tweet , function(err, data, response) {
if (err) {
// console.log("5OMeTh1nG weNt wR0ng");
} else {
// console.log("Tweet sucessful");
}
});
}
postTweet(generateSentence);
// second parameter is in miliseconds
MNMNsetInterval(postTweet(generateSentence), 1000*60*60*11);
|
Change API keys to uppercase
|
Change API keys to uppercase
|
JavaScript
|
mit
|
almightyboz/RabelaisMarkov
|
cb7990566b9ac406946d57a0c4f00fb625d21efd
|
cli.js
|
cli.js
|
#!/usr/bin/env node
var browserslist = require('./');
var pkg = require('./package.json');
var args = process.argv.slice(2);
if ( args.length <= 0 || args.indexOf('--help') >= 0 ) {
console.log([
'',
pkg.name + ' - ' + pkg.description,
'',
'Usage:',
'',
' ' + pkg.name + ' query ...'
].join('\n'));
return;
}
if ( args.indexOf('--version') >= 0 ) {
console.log(pkg.version);
return;
}
browserslist(args).forEach(function (browser) {
console.log(browser);
});
|
#!/usr/bin/env node
var browserslist = require('./');
var pkg = require('./package.json');
var args = process.argv.slice(2);
function isArg(arg) {
return args.indexOf(arg) >= 0;
}
if ( args.length === 0 || isArg('--help') >= 0 || isArg('-h') >= 0 ) {
console.log([
'',
pkg.name + ' - ' + pkg.description,
'',
'Usage:',
'',
' ' + pkg.name + ' query ...'
].join('\n'));
return;
}
if ( args.indexOf('--version') >= 0 ) {
console.log(pkg.version);
return;
}
browserslist(args).forEach(function (browser) {
console.log(browser);
});
|
Add -h option to CLI
|
Add -h option to CLI
|
JavaScript
|
mit
|
mdix/browserslist,ai/browserslist
|
7cd66b92b824262a898bf539b0faba5ace6eaa0c
|
raf.js
|
raf.js
|
/*
* raf.js
* https://github.com/ngryman/raf.js
*
* original requestAnimationFrame polyfill by Erik Möller
* inspired from paul_irish gist and post
*
* Copyright (c) 2013 ngryman
* Licensed under the MIT license.
*/
(function(window) {
var lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
i = vendors.length;
// try to un-prefix existing raf
while (--i >= 0 && !requestAnimationFrame) {
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'];
}
// polyfill with setTimeout fallback
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
var now = Date.now(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now);
};
cancelAnimationFrame = clearTimeout;
}
// export to window
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
}(window));
|
/*
* raf.js
* https://github.com/ngryman/raf.js
*
* original requestAnimationFrame polyfill by Erik Möller
* inspired from paul_irish gist and post
*
* Copyright (c) 2013 ngryman
* Licensed under the MIT license.
*/
(function(window) {
var lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
i = vendors.length;
// try to un-prefix existing raf
while (--i >= 0 && !requestAnimationFrame) {
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'];
}
// polyfill with setTimeout fallback
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
var now = new Date().getTime(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now);
};
cancelAnimationFrame = clearTimeout;
}
// export to window
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
}(window));
|
Fix IE 8 by using compatible date methods
|
Fix IE 8 by using compatible date methods
`Date.now()` is not supported in IE8
|
JavaScript
|
mit
|
ngryman/raf.js
|
315f321d0c0d55669519cee39d0218cc4b71323f
|
src/js/actions/NotificationsActions.js
|
src/js/actions/NotificationsActions.js
|
import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
export default {
add: function(type, content) {
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_ADD,
notification : notification
});
setTimeout(() => {
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
}, 2000);
}
}
|
import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
export default {
add: function(type, content, duration) {
if(duration === undefined) duration = 3000;
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_ADD,
notification : notification
});
setTimeout(() => {
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
}, duration);
}
}
|
Add duration to notifications API
|
Add duration to notifications API
|
JavaScript
|
mit
|
KeitIG/museeks,KeitIG/museeks,MrBlenny/museeks,KeitIG/museeks,MrBlenny/museeks
|
33904221107d2f521b743ad06162b7b274f2d9ca
|
html/js/code.js
|
html/js/code.js
|
$(document).ready(function(){
var latlng = new google.maps.LatLng(45.5374054, -122.65028);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function correctHeight() {
var window_height = $(window).height();
var header_height = $("#search-container").offset().top;
$("#search-results").height(window_height - header_height - 20); //-20 for padding
$("#map_canvas").height(window_height - header_height);
}
correctHeight();
jQuery.event.add(window, "resize", correctHeight);
});
|
var makeMap = function() {
var latlng = new google.maps.LatLng(45.5374054, -122.65028);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function correctHeight() {
var window_height = $(window).height();
var header_height = $("#search-container").offset().top;
$("#search-results").height(window_height - header_height - 20); //-20 for padding
$("#map_canvas").height(window_height - header_height);
}
correctHeight();
jQuery.event.add(window, "resize", correctHeight);
};
$(document).ready(makeMap);
|
Create makeMap function (helps for testing later)
|
Create makeMap function (helps for testing later)
|
JavaScript
|
mit
|
jlavallee/HotGator,jlavallee/HotGator
|
da7a5d7b717df6312bba26de5cf83fab651c37d8
|
src/validation-strategies/one-valid-issue.js
|
src/validation-strategies/one-valid-issue.js
|
import issueStrats from '../issue-strategies/index.js';
import * as promiseUtils from '../promise-utils.js';
function validateStrategies(issueKey, jiraClientAPI) {
return jiraClientAPI.findIssue(issueKey)
.then(content =>
issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI)
)
.catch(content => Promise.reject(new Error(`${issueKey} does not have a valid issuetype`)));
}
export default function apply(issues, jiraClientAPI) {
return promiseUtils.anyPromise(issues.map(i => validateStrategies(i, jiraClientAPI)));
}
|
import issueStrats from '../issue-strategies/index.js';
import * as promiseUtils from '../promise-utils.js';
function validateStrategies(issueKey, jiraClientAPI) {
return jiraClientAPI.findIssue(issueKey)
.then(content => {
if (!issueStrats[content.fields.issuetype.name]) {
return Promise.reject(new Error(`${issueKey} does not have a valid issuetype`));
}
return issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI);
});
}
export default function apply(issues, jiraClientAPI) {
return promiseUtils.anyPromise(issues.map(i => validateStrategies(i, jiraClientAPI)));
}
|
Fix bug in no issue validation logic
|
Fix bug in no issue validation logic
|
JavaScript
|
mit
|
TWExchangeSolutions/jira-precommit-hook,DarriusWrightGD/jira-precommit-hook
|
761be726ceecbbd6857e1d229729ad78d327a685
|
src/utils/packetCodes.js
|
src/utils/packetCodes.js
|
module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
UPGRADES: "16",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
}
|
module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
PLAYER_UPGRADE: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
UPGRADES: "16",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
}
|
Add player upgrade packet code
|
Add player upgrade packet code
|
JavaScript
|
mit
|
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww/m.io
|
c8de21c9a250922a26741e98d79df683ccdcaa65
|
www/src/app/pages/admin/organizations/list/organizations.page.controller.js
|
www/src/app/pages/admin/organizations/list/organizations.page.controller.js
|
'use strict';
import _ from 'lodash/core';
export default class OrganizationsPageController {
constructor($log, OrganizationService) {
'ngInject';
this.$log = $log;
this.OrganizationService = OrganizationService;
}
$onInit() {
this.state = {
showForm: false,
formData: {}
};
}
create() {
this.OrganizationService.create(
_.pick(this.state.formData, ['name', 'description'])
).then(response => {
this.$log.log('Organization created', response);
this.reload();
this.$onInit();
});
}
disable(id) {
this.OrganizationService.disable(id).then(response => {
this.$log.log(`Organization ${id} deleted`, response);
this.reload();
});
}
enable(id) {
this.OrganizationService.enable(id).then(response => {
this.$log.log(`Organization ${id} deleted`, response);
this.reload();
});
}
reload() {
this.OrganizationService.list().then(
organizations => (this.organizations = organizations)
);
}
}
|
'use strict';
import _ from 'lodash/core';
export default class OrganizationsPageController {
constructor($log, OrganizationService, NotificationService, ModalService) {
'ngInject';
this.$log = $log;
this.OrganizationService = OrganizationService;
this.NotificationService = NotificationService;
this.ModalService = ModalService;
}
$onInit() {
this.state = {
showForm: false,
formData: {}
};
}
create() {
this.OrganizationService.create(
_.pick(this.state.formData, ['name', 'description'])
).then(response => {
this.$log.log('Organization created', response);
this.reload();
this.$onInit();
});
}
disable(id) {
let modalInstance = this.ModalService.confirm(
'Disable organization',
`Are your sure you want to disable this organization? Its users will no longer be able to have access to Cortex.`,
{
flavor: 'danger',
okText: 'Yes, disable it'
}
);
modalInstance.result
.then(() => this.OrganizationService.disable(id))
.then(() => {
this.reload();
this.NotificationService.success('The organization has been disabled');
})
.catch(err => {
if (!_.isString(err)) {
this.NotificationService.error('Unable to disable the organization.');
}
});
}
enable(id) {
let modalInstance = this.ModalService.confirm(
'Enable organization',
`Are your sure you want to enable this organization? Its users will have access to Cortex.`,
{
flavor: 'primary',
okText: 'Yes, enable it'
}
);
modalInstance.result
.then(() => this.OrganizationService.enable(id))
.then(() => {
this.reload();
this.NotificationService.success('The organization has been enabled');
})
.catch(err => {
if (!_.isString(err)) {
this.NotificationService.error('Unable to enabled the organization.');
}
});
}
reload() {
this.OrganizationService.list().then(
organizations => (this.organizations = organizations)
);
}
}
|
Add confirmation dialog when enabling/disabling an organization
|
Add confirmation dialog when enabling/disabling an organization
|
JavaScript
|
agpl-3.0
|
CERT-BDF/Cortex,CERT-BDF/Cortex,CERT-BDF/Cortex,CERT-BDF/Cortex
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.