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
25376ac4975c5d5021b40438f8954a6faa24e21d
lib/config.js
lib/config.js
var Fs = require('fs'); var config = module.exports = {}; // Configuring TLS config.tls = { key: Fs.readFileSync('./lib/certs/key.key'), cert: Fs.readFileSync('./lib/certs/cert.crt'), // Only necessary if using the client certificate authentication. requestCert: true, // Only necessary only if client is using the self-signed certificate. ca: [] }; config.crumb = { cookieOptions: { isSecure: true }, autoGenerate: true }; config.monitor = { opsInterval: 1000, reporters: [{ reporter: require('good-console'), events: { log: '*', response: '*' } }, { reporter: require('good-file'), events: { ops: '*' }, config: './test/fixtures/monitor_log' }, { reporter: 'good-http', events: { ops: '*', log: '*', response: '*' }, config: { endpoint: 'http://localhost:3000', wreck: { headers: { 'x-api-key': 12345 } } } }] };
var Fs = require('fs'); var config = module.exports = {}; // Configuring TLS config.tls = { key: Fs.readFileSync('./lib/certs/key.key'), cert: Fs.readFileSync('./lib/certs/cert.crt'), // Only necessary if using the client certificate authentication. requestCert: true, // Only necessary only if client is using the self-signed certificate. ca: [] }; config.crumb = { cookieOptions: { isSecure: true }, autoGenerate: true }; config.monitor = { opsInterval: 1000, reporters: [{ reporter: require('good-console'), events: { log: '*', response: '*' } }, { reporter: require('good-file'), events: { ops: '*' }, config: './test/fixtures/monitor_log' }] }; // @Example of logging to a remote server. // config.monitor = { // opsInterval: 1000, // reporters: [{ // reporter: require('good-console'), // events: { log: '*', response: '*' } // }, { // reporter: require('good-file'), // events: { ops: '*' }, // config: './test/fixtures/monitor_log' // }, { // reporter: 'good-http', // events: { ops: '*', log: '*', response: '*' }, // config: { // endpoint: 'http://localhost:3000', // wreck: { // headers: { 'x-api-key': 12345 } // } // } // }] // };
Refactor good stop sending logs to remote server
Refactor good stop sending logs to remote server Comments in lib/config.js still show how to send logs to remote server. But, it is not used.
JavaScript
bsd-3-clause
jd73/university,jd73/university
2b261f89e9820a4697e0a812defaec05385fad51
test/spec/controllers/main.js
test/spec/controllers/main.js
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('quakeStatsApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('quakeStatsApp')); var MainCtrl, scope, mockStats = { gamesStats: [] }; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope, Constants: {}, stats: mockStats }); })); it('should attach a list of games to the scope', function () { expect(scope.games).toBeDefined(); }); });
Make the first dummy test pass
Tests: Make the first dummy test pass
JavaScript
mit
mbarzeev/quake-stats,mbarzeev/quake-stats
d111e99ba98e357e1f13eb8b8e83da5e188b9d0a
lib/readTemplate.js
lib/readTemplate.js
'use strict'; const fs = require('fs'); const Promise = require('bluebird'); const readFile = Promise.promisify(fs.readFile, { context: fs }); const cache = require('./cache'); module.exports = readTemplate; function readTemplate(path, callback) { const cacheKey = `template.${path}`; if (process.env.NODE_ENV === 'production') { return cache.get(cacheKey) .catch((err) => { return readFile(path) .then((buf) => buf.toString()) .then((value) => cache.put(cacheKey, value, { ttl: 0 })); }) .asCallback(callback); } else { return readFile(path) .then((buf) => buf.toString()) .asCallback(callback); } };
'use strict'; const fs = require('fs'); const Promise = require('bluebird'); const readFile = Promise.promisify(fs.readFile, { context: fs }); const cache = require('./cache'); module.exports = readTemplate; function readTemplate(path, callback) { const cacheKey = `template.${path}`; return cache.get(cacheKey) .catch((err) => { return readFile(path) .then((buf) => buf.toString()) .then((value) => cache.put(cacheKey, value, { ttl: 0 })); }) .asCallback(callback); };
Revert "only cache templates in production"
Revert "only cache templates in production" This reverts commit 4e2bf7d48d60bba8b4d4497786e4db0ab8f81bef.
JavaScript
apache-2.0
carsdotcom/windshieldjs,carsdotcom/windshieldjs
25ecb5e4f4bfeac33198913ec49bdb8b2412f462
MovieFinder/src/main/webapp/public/src/controllers/nav-controller.js
MovieFinder/src/main/webapp/public/src/controllers/nav-controller.js
// // nav-controller.js // Contains the controller for the nav-bar. // (function () { 'use strict'; angular.module('movieFinder.controllers') .controller('NavCtrl', function ($scope, $modal, user) { var _this = this; var signInModal; this.error = { signIn: '' }; this.showSignInModal = function () { signInModal = $modal({ scope: $scope, template: 'partials/modals/sign-in.html', container: 'body' }); }; this.login = function (username, password) { user.login(username, password).success(function(){ signInModal.$promise.then(signInModal.hide); }).error(function(){ _this.error.signIn = 'Some error message'; }); }; this.logout = function() { user.logout(); }; }); })();
// // nav-controller.js // Contains the controller for the nav-bar. // (function () { 'use strict'; angular.module('movieFinder.controllers') .controller('NavCtrl', function ($scope, $modal, user) { var _this = this; var signInModal; this.error = { signIn: '' }; this.showSignInModal = function () { this.error.signIn = ''; signInModal = $modal({ scope: $scope, template: 'partials/modals/sign-in.html', container: 'body' }); }; this.login = function (username, password) { user.login(username, password).success(function(){ signInModal.$promise.then(signInModal.hide); }).error(function(){ _this.error.signIn = 'Some error message'; }); }; this.logout = function() { user.logout(); }; }); })();
Reset error message when dialog re-opened.
Reset error message when dialog re-opened.
JavaScript
mit
we4sz/DAT076,we4sz/DAT076
633dd358d078e50503406f15f8b46b8ba9fce951
src/modules/sound.js
src/modules/sound.js
let lastPachiIndex = -1 let lastCaptureIndex = -1 let captureSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/capture${x}.mp3`)) let pachiSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/${x}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') exports.playPachi = function(delay = 0) { let index = lastPachiIndex while (index === lastPachiIndex) { index = Math.floor(Math.random() * pachiSounds.length) } lastPachiIndex = index setTimeout(() => pachiSounds[index].play(), delay) } exports.playCapture = function(delay = 0) { let index = lastCaptureIndex while (index === lastCaptureIndex) { index = Math.floor(Math.random() * captureSounds.length) } lastCaptureIndex = index setTimeout(() => captureSounds[index].play(), delay) } exports.playPass = function(delay = 0) { setTimeout(() => passSound.play(), delay) } exports.playNewGame = function(delay = 0) { setTimeout(() => newGameSound.play(), delay) }
const helper = require('./helper') let lastPachiIndex = -1 let lastCaptureIndex = -1 let captureSounds = [...Array(5)].map((_, i) => new Audio(`./data/capture${i}.mp3`)) let pachiSounds = [...Array(5)].map((_, i) => new Audio(`./data/${i}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') exports.playPachi = function(delay = 0) { let index = lastPachiIndex while (index === lastPachiIndex) { index = Math.floor(Math.random() * pachiSounds.length) } lastPachiIndex = index setTimeout(() => pachiSounds[index].play().catch(helper.noop), delay) } exports.playCapture = function(delay = 0) { let index = lastCaptureIndex while (index === lastCaptureIndex) { index = Math.floor(Math.random() * captureSounds.length) } lastCaptureIndex = index setTimeout(() => captureSounds[index].play().catch(helper.noop), delay) } exports.playPass = function(delay = 0) { setTimeout(() => passSound.play().catch(helper.noop), delay) } exports.playNewGame = function(delay = 0) { setTimeout(() => newGameSound.play().catch(helper.noop), delay) }
Fix weird error messages about play() and pause()
Fix weird error messages about play() and pause()
JavaScript
mit
yishn/Sabaki,yishn/Goban,yishn/Goban,yishn/Sabaki
87407f3dbd25b823d05f2f5b03475a7ecc391438
lib/geoloc.js
lib/geoloc.js
var geoip = require('geoip'); function Point(latitude, longitude) { this.latitude = latitude; this.longitude = longitude; } module.exports = { /* * Returns geoloc Point from the requester's ip adress * @throws Exception */ getPointfromIp: function(ip, geoliteConfig) { var latitude, longitude; var city = new geoip.City(geoliteConfig.geolitepath); var geo = city.lookupSync(ip); if (!geo) { return null; } longitude = geo.longitude; latitude = geo.latitude; return new Point(latitude, longitude); }, getCityFromIp : function (ip, geoliteConfig) { var city = new geoip.City(geoliteConfig.geolitepath); return city.lookupSync(ip); } };
var geoip = require('geoip'); function Point(latitude, longitude) { this.latitude = latitude; this.longitude = longitude; } module.exports = { /* * Returns geoloc Point from the requester's ip adress * @throws Exception */ getPointfromIp: function(ip, geolitePath) { var latitude, longitude; var city = new geoip.City(geolitePath); var geo = city.lookupSync(ip); if (!geo) { return null; } longitude = geo.longitude; latitude = geo.latitude; return new Point(latitude, longitude); }, getCityFromIp : function (ip, geolitePath) { var city = new geoip.City(geolitePath); return city.lookupSync(ip); } };
Change getPointFromIp & getCityFromIp methods signature
Change getPointFromIp & getCityFromIp methods signature
JavaScript
mit
Jumplead/GeonamesServer,Jumplead/GeonamesServer,xjewer/GeonamesServer,xjewer/GeonamesServer,xjewer/GeonamesServer,Jumplead/GeonamesServer,Jumplead/GeonamesServer
152c0faec45c4b754b3496a37de0884df11eb5bb
isProduction.js
isProduction.js
if (process && process.env && process.env.NODE_ENV === 'production') { console.warn([ 'You are running Mimic in production mode,', 'in most cases you only want to run Mimic in development environments.\r\n', 'For more information on how to load Mimic in development environments only please see:', 'https://github.com/500tech/mimic#loading-mimic-only-in-development-environments' ].join(' ')); }
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') { console.warn([ 'You are running Mimic in production mode,', 'in most cases you only want to run Mimic in development environments.\r\n', 'For more information on how to load Mimic in development environments only please see:', 'https://github.com/500tech/mimic#loading-mimic-only-in-development-environments' ].join(' ')); }
Fix a bug where checking process.env.NODE_ENV was not safe enough
fix(bootstrapping): Fix a bug where checking process.env.NODE_ENV was not safe enough the check for process variable existence threw an error in some build systems which do not take care of the process global variable such as angular cli.
JavaScript
mit
500tech/bdsm,500tech/mimic,500tech/mimic,500tech/bdsm
7a2e50e7634ead72e8301fb99da246f20e92c961
libs/connections.js
libs/connections.js
//Get required modules var Connection = require( 'ssh2' ); var domain = require( 'domain' ); //Add my libs var handlers = require( './handlers.js' ); //Auxiliary function to initialize/re-initialize ssh connection function initializeConnection() { //Initialize the ssh connection connection = new Connection(), handler = domain.create(); //Handling "error" event inside domain handler. handler.add(connection); //Add global connection handlers handlers.setGlobalConnectionHandlers(); //Start connection connection.connect(OptionsForSFTP); } function resetConnection() { //Mark inactive connection active_connection = false; //Start connection connection.connect(OptionsForSFTP); } //Expose handlers public API module.exports = { initializeConnection: initializeConnection, resetConnection: resetConnection };
//Get required modules var Connection = require( 'ssh2' ); var domain = require( 'domain' ); //Auxiliary function to initialize/re-initialize ssh connection function initializeConnection() { //Add my libs var handlers = require( './handlers.js' ); //Initialize the ssh connection connection = new Connection(), handler = domain.create(); //Handling "error" event inside domain handler. handler.add(connection); //Add global connection handlers handlers.setGlobalConnectionHandlers(); //Start connection connection.connect(OptionsForSFTP); } function resetConnection() { //Mark inactive connection active_connection = false; //Start connection connection.connect(OptionsForSFTP); } //Expose handlers public API module.exports = { resetConnection: resetConnection, initializeConnection: initializeConnection };
Fix module require chicken-egg problem
Fix module require chicken-egg problem
JavaScript
mit
ctimoteo/syncmaster
9bbcea12f0db82cf583d9fcc42998b2b79ef4372
lib/parser.js
lib/parser.js
'use babel'; export default class Parser { source: null editor: null parse(source, editor) { this.source = source; this.editor = editor; return this.scan(); } scan() { let result = [], count = 0; // Find 'describes', set indexs, find 'it' this.findInstanceOf('describe(\'', result, 0, this.source.length); this.getEndIndex(result); result.map((obj) => obj.children = []); result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex)); return result; } findInstanceOf(word, result, startIndex, endIndex) { let index = startIndex, wordLength = word.length, name, position; while (index != -1 && index < endIndex) { index++; index = this.source.indexOf(word, index); if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); result.push({index, name, position}); } } getEndIndex(arr){ arr.map((obj, index, arr) => { if (arr[index + 1]) { obj.endIndex = arr[index + 1]['index']; } else { obj.endIndex = this.source.length; } }); } }
'use babel'; export default class Parser { source: null editor: null parse(source, editor) { this.source = source; this.editor = editor; return this.scan(); } scan() { let result = [], count = 0; // Find 'describes', set indexs, find 'it' this.findInstanceOf('describe(\'', result, 0, this.source.length); this.getEndIndex(result); result.map((obj) => obj.children = []); result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex)); return result; } findInstanceOf(word, result, startIndex, endIndex) { let index = startIndex, wordLength = word.length, name, position; while (index != -1 && index < endIndex) { index++; index = this.source.indexOf(word, index); if (index == -1 || index > endIndex) break; name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1)); position = this.editor.buffer.positionForCharacterIndex(index); result.push({index, name, position, expanded: true,}); } } getEndIndex(arr){ arr.map((obj, index, arr) => { if (arr[index + 1]) { obj.endIndex = arr[index + 1]['index']; } else { obj.endIndex = this.source.length; } }); } }
Expand the tree view by defualt
Expand the tree view by defualt
JavaScript
mit
chiragchoudhary66/test-list-maker
9413f0cb3b4bd6545d29e79e9b656469b209a417
jquery.linkem.js
jquery.linkem.js
// jquery.linkem.js // Copyright Michael Hanson // https://github.com/mybuddymichael/jquery-linkem (function( $ ) { $.fn.linkem = function() { var linked = this; this.on( "keydown keyup mousedown mouseup", function() { linked.text( $(this).val() ); }); }; return this; })( jQuery );
// jquery.linkem.js // Copyright Michael Hanson // https://github.com/mybuddymichael/jquery-linkem (function( $ ) { $.fn.linkem = function() { var linked = this; this.on( "input change", function() { linked.text( $(this).val() ); }); }; return this; })( jQuery );
Change events to "input" and "change"
Change events to "input" and "change"
JavaScript
mit
mybuddymichael/jquery-linkem
47b311db68aa5343f66e3f5a5fd77602bd3e2e9e
server/models/products.js
server/models/products.js
// npm dependencies const mongoose = require('mongoose'); // defines Product model // contains 3 fields (title, description, and price) let Product = mongoose.model('Product', { title: { type: String, required: true, minlength: 5, trim: true }, description: { type: String, required: true, minlength: 10, trim: true }, price: { type: Number, default: null } }); module.exports = { Product }
// npm dependencies const mongoose = require('mongoose'); // defines Product model // contains 3 fields (title, description, and price) let Product = mongoose.model('Product', { title: { type: String, required: true, minlength: 5, trim: true }, description: { type: String, minlength: 10, trim: true }, price: { type: Number, default: null } }); module.exports = { Product }
Remove 'required' validation from 'description' field
Remove 'required' validation from 'description' field
JavaScript
mit
dshaps10/full-stack-demo-site,dshaps10/full-stack-demo-site
8e54f1bd3f215ada478b6fb41644bcb777b29ab2
js/app/viewer.js
js/app/viewer.js
/*jslint browser: true, white: true, plusplus: true */ /*global angular, console, alert*/ (function () { 'use strict'; var app = angular.module('status', ['ui.bootstrap', 'chieffancypants.loadingBar', 'tableSort']); app.controller("StatusController", function($scope, $http) { $scope.serverName = app.serverName; var request = app.api + "search/tickets?unresolved=1"; $http.get( request ) .success(function(data, status, header, config) { $scope.apiLoaded = true; $scope.ticketsCount = data.length; if ($scope.ticketsCount > 0) { $scope.tickets = data; } }) .error(function(data, status, header, config) { $scope.apiLoaded = false; console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?closedBy=0"); }); }); }());
/*jslint browser: true, white: true, plusplus: true */ /*global angular, console, alert*/ (function () { 'use strict'; var app = angular.module('status', ['ui.bootstrap', 'chieffancypants.loadingBar', 'tableSort']); app.controller("StatusController", function($scope, $http) { $scope.serverName = app.serverName; var request = app.api + "search/tickets?unresolved=1"; $http.get( request ) .success(function(data, status, header, config) { $scope.apiLoaded = true; $scope.ticketsCount = data.length; if ($scope.ticketsCount > 0) { $scope.tickets = data; } }) .error(function(data, status, header, config) { $scope.apiLoaded = false; console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?unresolved=1"); }); }); }());
Update console log error text
Update console log error text
JavaScript
agpl-3.0
ShinDarth/TC-Ticket-Web-Viewer,ShinDarth/TC-Ticket-Web-Viewer
74386ac41257a7ea865aefd09631ff87815c23a5
src/components/App/index.js
src/components/App/index.js
import React, { Component } from 'react'; /* global styles for app */ import './styles/app.scss'; /* application components */ import { Header } from '../../components/Header'; import { Footer } from '../../components/Footer'; export class App extends Component { static propTypes = { children: React.PropTypes.any, }; render() { return ( <section> <Header /> <main className="container"> {this.props.children} </main> <Footer /> </section> ); } }
import React, { Component } from 'react'; /* global styles for app */ import './styles/app.scss'; /* application components */ import { Header } from '../../components/Header'; import { Footer } from '../../components/Footer'; export class App extends Component { static propTypes = { children: React.PropTypes.any, }; render() { return ( <section> <Header /> <main> <div className="container"> {this.props.children} </div> </main> <Footer /> </section> ); } }
Change markup so that main el is outside of container, can take a full width bg color
Change markup so that main el is outside of container, can take a full width bg color
JavaScript
mit
dramich/Chatson,badT/twitchBot,badT/Chatson,badT/twitchBot,dramich/Chatson,dramich/twitchBot,TerryCapan/twitchBot,TerryCapan/twitchBot,dramich/twitchBot,badT/Chatson
ada006bbcee7e855f9ee44acbd777928a0c58d1b
addon/initializers/mutation-observer.js
addon/initializers/mutation-observer.js
/** * Simple initializer that implements the mutationObserverMixin * in all the Components. It uses a flag defined in the app * environment for it. */ import Ember from 'ember'; import mutationObserver from '../mixins/mutation-observer'; export function initialize(app) { const config = app.lookupFactory ? app.lookupFactory('config:environment') : app.__container__.lookupFactory('config:environment'); if (!config || !config.mutationObserverInjection) {return;} Ember.Component.reopen(mutationObserver); } export default { name: 'mutation-observer', initialize: initialize };
/** * Simple initializer that implements the mutationObserverMixin * in all the Components. It uses a flag defined in the app * environment for it. */ import Ember from 'ember'; import mutationObserver from '../mixins/mutation-observer'; export function initialize(app) { let config; try { // Ember 2.15+ config = app.resolveRegistration('config:environment'); } catch (e) { // Older Ember approach config = app.lookupFactory ? app.lookupFactory('config:environment') : app.__container__.lookupFactory('config:environment'); } if (!config || !config.mutationObserverInjection) {return;} Ember.Component.reopen(mutationObserver); } export default { name: 'mutation-observer', initialize: initialize };
Fix initializer for Ember 2.15+
Fix initializer for Ember 2.15+
JavaScript
mit
zzarcon/ember-cli-Mutation-Observer,zzarcon/ember-cli-Mutation-Observer
1f13a1254fbf5303a58bf75b14b160e11d7dd30e
src/components/Lotteries.js
src/components/Lotteries.js
/** * Created by mgab on 14/05/2017. */ import React,{ Component } from 'react' import Title from './common/styled-components/Title' import Lottery from './Lottery' export default class Lotteries extends Component { render() { const lotteries = [] this.props.lotteriesData.forEach((entry) => { lotteries.push(<Lottery name={entry.id} jackpot={entry.jackpots[0].jackpot} drawingDate={entry.drawingDate} key={entry.id} />) }) return ( <div> <Title>Lotteries</Title> <div> {lotteries} </div> </div> ) } }
/** * Created by mgab on 14/05/2017. */ import React,{ Component } from 'react' import Title from './common/styled-components/Title' import Lottery from './Lottery' export default class Lotteries extends Component { render() { const lotteries = [] if (this.props.lotteriesData) { this.props.lotteriesData.forEach((entry) => { lotteries.push(<Lottery name={entry.id} jackpot={entry.jackpots[0].jackpot} drawingDate={entry.drawingDate} key={entry.id} />) }) } return ( <div> <Title>Lotteries</Title> <div> {lotteries} </div> </div> ) } }
Check for lotteries data before trying to process them.
Check for lotteries data before trying to process them.
JavaScript
mit
mihailgaberov/lottoland-react-demo,mihailgaberov/lottoland-react-demo
28c89588650841686f1c0c515360686a5ac0afd8
src/middleware/authenticate.js
src/middleware/authenticate.js
import handleAdapter from '../handleAdapter' export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var verifyHeader = ( !! config.header) var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} if (verifyHeader) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken !== false) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } handleAdapter(req, config, next, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
import handleAdapter from '../handleAdapter' export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} if (header) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken !== false) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } handleAdapter(req, config, next, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
Fix header not being validated if 'auth.header' option is not given.
Fix header not being validated if 'auth.header' option is not given. In authenticate middleware.
JavaScript
mit
kukua/concava
fc9bdc4a183ea90c596603bdc5cdc62e2902c1ce
lib/Subheader.js
lib/Subheader.js
import { getColor } from './helpers'; import { StyleSheet, View, Text } from 'react-native'; import { TYPO, THEME_NAME } from './config'; import React, { Component, PropTypes } from 'react'; const styles = StyleSheet.create({ container: { padding: 16 }, text: TYPO.paperFontBody1 }); export default class Subheader extends Component { static propTypes = { text: PropTypes.string.isRequired, color: PropTypes.string, inset: PropTypes.bool, theme: PropTypes.oneOf(THEME_NAME), lines: PropTypes.number }; static defaultProps = { color: 'rgba(0,0,0,.54)', inset: false, theme: 'light', lines: 1 }; render() { const { text, color, inset, lines } = this.props; return ( <View style={[styles.container, { paddingLeft: inset ? 72 : 16 }]} > <Text numberOfLines={lines} style={[styles.text, { color: getColor(color), fontWeight: '500' }]} > {text} </Text> </View> ); } }
import { getColor } from './helpers'; import { StyleSheet, View, Text } from 'react-native'; import { TYPO, THEME_NAME } from './config'; import React, { Component, PropTypes } from 'react'; const styles = StyleSheet.create({ container: { padding: 16 }, text: TYPO.paperFontBody1 }); export default class Subheader extends Component { static propTypes = { text: PropTypes.string.isRequired, color: PropTypes.string, inset: PropTypes.bool, theme: PropTypes.oneOf(THEME_NAME), lines: PropTypes.number, style: PropTypes.object, }; static defaultProps = { color: 'rgba(0,0,0,.54)', inset: false, theme: 'light', lines: 1 }; render() { const { text, color, inset, lines, style } = this.props; return ( <View style={[styles.container, { paddingLeft: inset ? 72 : 16 }, style]} > <Text numberOfLines={lines} style={[styles.text, { color: getColor(color), fontWeight: '500' }]} > {text} </Text> </View> ); } }
Add ability to set state of subheader
Add ability to set state of subheader
JavaScript
mit
xotahal/react-native-material-ui,mobileDevNativeCross/react-native-material-ui,xvonabur/react-native-material-ui,blovato/sca-mobile-components,ajaxangular/react-native-material-ui,kenma9123/react-native-material-ui
edbcdb75813fdd8149c147f0c7dc5138e06307e6
test/unit/history/setLimit.test.js
test/unit/history/setLimit.test.js
import History from '../../../src/history' describe('History::setLimit', function() { const action = n => n it('sets the correct size given Infinity', function() { const history = new History() history.setLimit(Infinity) expect(history.limit).toEqual(Infinity) }) it('sets the correct size given an integer', function() { const history = new History() history.setLimit(10) expect(history.limit).toEqual(10) }) it('sets the limit to 0 given a negative integer', function() { const history = new History() history.setLimit(-10) expect(history.limit).toEqual(0) }) })
import History from '../../../src/history' describe('History::setLimit', function() { it('sets the correct size given Infinity', function() { const history = new History() history.setLimit(Infinity) expect(history.limit).toEqual(Infinity) }) it('sets the correct size given an integer', function() { const history = new History() history.setLimit(10) expect(history.limit).toEqual(10) }) it('sets the limit to 0 given a negative integer', function() { const history = new History() history.setLimit(-10) expect(history.limit).toEqual(0) }) })
Remove unused variable that caused linter warning
Remove unused variable that caused linter warning
JavaScript
mit
vigetlabs/microcosm,vigetlabs/microcosm,vigetlabs/microcosm
2990ed3071a0969145e0a76beae6ad057e6e14f9
subsystem/click.js
subsystem/click.js
phoxy._ClickHook = { _: {}, }; phoxy._ClickHook._.click = { InitClickHook: function() { document.querySelector('body').addEventListener('click', function(event) { var target = event.target; while (true) { if (target === null) return; if (target.nodeName === 'A') break; // only click on A is triggered target = target.parentElement; } var url = target.getAttribute('href'); if (url === undefined || target.hasAttribute('not-phoxy')) return; if (phoxy._.click.OnClick(url, false)) return; event.preventDefault() }, true); window.onpopstate = phoxy._.click.OnPopState; } , OnClick: function (url, not_push) { if (url.indexOf('#') !== -1) return true; if (url[0] === '/') url = url.substring(1); phoxy.MenuCall(url); return false; } , OnPopState: function(e) { var path = e.target.location.pathname; var hash = e.target.location.hash; phoxy._.click.OnClick(path, true); } };
phoxy._ClickHook = { _: {}, }; phoxy._ClickHook._.click = { InitClickHook: function() { document.querySelector('body').addEventListener('click', function(event) { var target = event.target; while (true) { if (target === null) return; if (target.nodeName === 'A') break; // only click on A is triggered target = target.parentElement; } var url = target.getAttribute('href'); if (url === undefined || target.hasAttribute('not-phoxy')) return; if (phoxy._.click.OnClick(url, false)) return; event.preventDefault() }, true); window.onpopstate = phoxy._.click.OnPopState; } , OnClick: function (url, not_push) { if (url.indexOf('#') !== -1) return true; if (url[0] === '/') url = url.substring(1); if (not_push) phoxy.ApiRequest(url); else phoxy.MenuCall(url); return false; } , OnPopState: function(e) { var path = e.target.location.pathname; var hash = e.target.location.hash; phoxy._.click.OnClick(path, true); } };
Fix empty history issue, when we never could go back
Fix empty history issue, when we never could go back
JavaScript
apache-2.0
phoxy/phoxy,phoxy/phoxy
675134d0bb49567fade2501538dc088b21cdab64
StructureMaintainer.js
StructureMaintainer.js
module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); var newCandidates = [], links = [], spawns = []; Object.keys(Game.structures).forEach(function(structureId) { structure = Game.structures[structureId]; if(structure.hits < (structure.hitsMax / 2)) { newCandidates.push(structure); } if(structure.structureType === STRUCTURE_LINK) { links.push(structure.id); } }); Memory.repairList.forEach(function (id) { var structure = Game.getObjectById(id); if(!structure || structure.hits >= structure.hitsMax*0.75) { Memory.repairList.splice(Memory.repairList.indexOf(id), 1); } }); Memory.linkList = links; Memory.spawnList = Game.spawns; newCandidates.forEach(function (structure) { if(Memory.repairList.indexOf(structure.id) === -1) { Memory.repairList.push(structure.id); } }); console.log("Finished " + Game.getUsedCpu()); };
module.exports = function() { console.log("Maintaining Structures... " + Game.getUsedCpu()); var structures = Object.keys(Game.rooms).forEach(function (roomName) { Game.rooms[roomName].find(FIND_STRUCTURES, { filter: function (structure) { return (structure.my === true || structure.structureType === "STRUCTURE_ROAD"); } }); }); var newCandidates = [], links = [], spawns = []; structures.forEach(function(structure) { if(structure.hits < (structure.hitsMax / 2)) { newCandidates.push(structure); } if(structure.structureType === STRUCTURE_LINK) { links.push(structure.id); } }); Memory.repairList.forEach(function (id) { var structure = Game.getObjectById(id); if(!structure || structure.hits >= structure.hitsMax*0.75) { Memory.repairList.splice(Memory.repairList.indexOf(id), 1); } }); Memory.linkList = links; Memory.spawnList = Game.spawns; newCandidates.forEach(function (structure) { if(Memory.repairList.indexOf(structure.id) === -1) { Memory.repairList.push(structure.id); } }); console.log("Finished " + Game.getUsedCpu()); };
Make it so that the Structure Maintainer includes roads as well.
Make it so that the Structure Maintainer includes roads as well.
JavaScript
mit
pmaidens/screeps,pmaidens/screeps
e29974b1adcb91af1a65ac474fcb36d7a0e24098
test/17_image/definitions.js
test/17_image/definitions.js
define(function () { return [ { "default": { name: "TestForm", label: "TestForm", _elements: [ { "default": { name: "Name", type: "text", label: "Name" } }, { "default": { name: "Photo", type: "file", label: "Photo", accept: "image/*" } }, { "default": { name: "Photo1", type: "file", label: "Photo1", accept: "image/*" } }, { "default": { name: "Photo2", type: "file", label: "Photo2", accept: "image/*" } }, { 'default': { name: 'location', label: 'Location', type: 'location' } }, { 'default': { name: 'draw', label: 'Sign', type: 'draw', size: 'signature' } }, { "default": { name: "Rank", type: "number", label: "Rank" } }, { "default": { name: "Details", type: "text", label: "Details" } } ] } } ]; });
define(function () { return [ { "default": { name: "TestForm", label: "TestForm", _elements: [ { "default": { name: "Name", type: "text", label: "Name" } }, { "default": { name: "Photo", type: "file", label: "Photo", accept: "image/*", capture: true } }, { "default": { name: "Photo1", type: "file", label: "Photo1", accept: "image/*", capture: false } }, { "default": { name: "Photo2", type: "file", label: "Photo2", accept: "image/*", capture: true } }, { 'default': { name: 'location', label: 'Location', type: 'location' } }, { 'default': { name: 'draw', label: 'Sign', type: 'draw', size: 'signature' } }, { "default": { name: "Rank", type: "number", label: "Rank" } }, { "default": { name: "Details", type: "text", label: "Details" } } ] } } ]; });
Update form definition in tests to demonstrate functionality
Update form definition in tests to demonstrate functionality
JavaScript
bsd-3-clause
blinkmobile/forms,blinkmobile/forms
819345213938c7b6df4eaeb2dac2c39b2078e1d0
public/javascripts/app/views/gameController.js
public/javascripts/app/views/gameController.js
define([ 'Backbone', //Collection 'app/collections/games' ], function( Backbone, Games ){ var GameController = Backbone.View.extend({ events: { 'keyup .js-create-game' : 'create' }, initialize: function(){ this.collection = new Games(this.options.projectId); this.collection.bind('add', this.addGame, this); this.collection.bind('reset', this.render, this).fetch(); }, create: function(event){ if(event.keyCode === 13){ this.collection.create({ name: event.currentTarget.value, projectId: this.options.projectId }); } }, addGame: function(){ console.log(this.collection); }, render: function(){ console.log(this.collection); } }); return GameController; });
define([ 'Backbone', //Collection 'app/collections/games', //Template 'text!templates/project-page/gameTemplate.html', ], function( Backbone, //Collection Games, //Template gameTemplate ){ var GameController = Backbone.View.extend({ template: _.template(gameTemplate), events: { 'keyup .js-create-game' : 'create' }, initialize: function(){ this.collection = new Games(this.options.projectId); this.collection.bind('add', this.addGame, this); this.collection.bind('reset', this.render, this); }, guid: function(){ var S4 = function (){ return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, create: function(event){ if(event.keyCode === 13){ this.collection.create({ _id: this.guid(), name: event.currentTarget.value, projectId: this.options.projectId }); event.currentTarget.value=''; } }, addGame: function(newModel){ var newGame = newModel.toJSON(); this.$el.append(this.template(newGame)); }, render: function(){ var template = this.template; var $list = this.$el; _.each(this.collection.models, function(model){ var game = template(model.toJSON()); $list.append(game); }); } }); return GameController; });
Add game logic on game controller
front-end: Add game logic on game controller
JavaScript
mit
tangosource/pokerestimate,tangosource/pokerestimate
56c2e6b543e51ec44a5bcb133ef9511c50d0f4ff
ui/src/shared/middleware/errors.js
ui/src/shared/middleware/errors.js
// import {replace} from 'react-router-redux' import {authExpired} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' const notificationsBlackoutDuration = 5000 let allowNotifications = true // eslint-disable-line const errorsMiddleware = store => next => action => { if (action.type === 'ERROR_THROWN') { const {error, error: {status, auth}, altText} = action console.error(error) if (status === HTTP_FORBIDDEN) { const {auth: {me}} = store.getState() const wasSessionTimeout = me !== null next(authExpired(auth)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Session timed out. Please login again.')) allowNotifications = false setTimeout(() => { allowNotifications = true }, notificationsBlackoutDuration) } else { store.dispatch(notify('error', 'Please login to use Chronograf.')) } } else if (altText) { store.dispatch(notify('error', altText)) } else { store.dispatch(notify('error', 'Cannot communicate with server.')) } } next(action) } export default errorsMiddleware
import {authExpired} from 'shared/actions/auth' import {publishNotification as notify} from 'shared/actions/notifications' import {HTTP_FORBIDDEN} from 'shared/constants' const actionsAllowedDuringBlackout = ['@@', 'AUTH_', 'ME_', 'NOTIFICATION_', 'ERROR_'] const notificationsBlackoutDuration = 5000 let allowNotifications = true // eslint-disable-line const errorsMiddleware = store => next => action => { const {auth: {me}} = store.getState() if (action.type === 'ERROR_THROWN') { const {error: {status, auth}, altText} = action if (status === HTTP_FORBIDDEN) { const wasSessionTimeout = me !== null store.dispatch(authExpired(auth)) if (wasSessionTimeout) { store.dispatch(notify('error', 'Session timed out. Please login again.')) allowNotifications = false setTimeout(() => { allowNotifications = true }, notificationsBlackoutDuration) } else { store.dispatch(notify('error', 'Please login to use Chronograf.')) } } else if (altText) { store.dispatch(notify('error', altText)) } else { store.dispatch(notify('error', 'Cannot communicate with server.')) } } // if auth has expired, do not execute any further actions or redux state // changes in order to prevent changing notification that indiciates why // logout occurred and any attempts to change redux state by actions that may // have triggered AJAX requests prior to auth expiration and whose response // returns after logout if (me === null && !(actionsAllowedDuringBlackout.some((allowedAction) => action.type.includes(allowedAction)))) { return } next(action) } export default errorsMiddleware
Refactor error middleware to suppress redux actions after auth expires and always show correct logout reason error notification
Refactor error middleware to suppress redux actions after auth expires and always show correct logout reason error notification
JavaScript
mit
mark-rushakoff/influxdb,influxdb/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb
2825711cff4a32829bfa94afb00ec5168f524382
webapp/src/ui/view/sidenav-view.js
webapp/src/ui/view/sidenav-view.js
const Backbone = require('backbone'); require('backbone.marionette'); const Repository = require('../../domain/repository'); const TeamItemViewTemplate = require('../template/team-item-view-template.hbs'); const Template = require('../template/sidenav-view-template.hbs'); const TeamItemView = Backbone.Marionette.View.extend({ template: TeamItemViewTemplate, tagName: 'li' }); const TeamListView = Backbone.Marionette.CollectionView.extend({ childView: TeamItemView }); module.exports = Backbone.Marionette.View.extend({ template: Template, ui: { addTeamButton: '.btn.add-team' }, events: { 'click @ui.addTeamButton': 'addTeam' }, regions: { teams: '.teams' }, onRender: function() { Repository.getTeams() .then(teams => { this.showChildView('teams', new TeamListView({collection: teams})); }); }, onDomRefresh: function() { this.$('.sidenav-button').sideNav(); }, addTeam: function() { Repository.addTeam(); } });
const Backbone = require('backbone'); require('backbone.marionette'); const Repository = require('../../domain/repository'); const TeamItemViewTemplate = require('../template/team-item-view-template.hbs'); const Template = require('../template/sidenav-view-template.hbs'); const TeamItemView = Backbone.Marionette.View.extend({ template: TeamItemViewTemplate, tagName: 'li' }); const TeamListView = Backbone.Marionette.CollectionView.extend({ childView: TeamItemView }); module.exports = Backbone.Marionette.View.extend({ template: Template, ui: { addTeamButton: '.btn.add-team' }, events: { 'click @ui.addTeamButton': 'addTeam', 'click .teams': 'closeSidenav' }, regions: { teams: '.teams' }, onRender: function() { Repository.getTeams() .then(teams => { this.showChildView('teams', new TeamListView({collection: teams})); }); }, onDomRefresh: function() { this.$('.sidenav-button').sideNav(); }, addTeam: function() { Repository.addTeam(); }, closeSidenav: function() { this.$('.sidenav-button').sideNav('hide'); } });
Hide sidenav when selecting team
Hide sidenav when selecting team
JavaScript
mit
hagifoo/gae-pomodoro,hagifoo/gae-pomodoro,hagifoo/gae-pomodoro
00e9721fef7c4438a6fae92ace89fbd59397912d
public/app/services/searchService.js
public/app/services/searchService.js
(function () { 'use strict'; define( [ 'lodash', 'jquery' ], function (_, $) { return function (baseUrl, ajaxOptions, noCache, logErrors) { var queryString; queryString = function (parameters) { return '(' + _.map(parameters.children, function (child) { return child.hasOwnProperty('children') ? queryString(child) : '(' + child.key + ':' + child.value + ')'; }) .join(' ' + parameters.operator + ' ') + ')'; }; return function (parameters, callback) { $.ajax(_.merge({}, ajaxOptions, { url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''), success: function (result) { if (!result.ok) { return callback(new Error('Invalid response received from server')); } delete result.ok; callback(undefined, _.values(result)); }, error: function (jqXHR, textStatus, err) { if (logErrors && console && typeof console.error === 'function') { console.error(jqXHR, textStatus, err); } callback(err || 'An unknown error occurred'); } })); }; }; } ); }());
(function () { 'use strict'; define( [ 'lodash', 'jquery' ], function (_, $) { return function (baseUrl, ajaxOptions, noCache, logErrors) { var queryString; queryString = function (parameters) { return _.map(parameters.children, function (child) { return child.hasOwnProperty('children') ? '(' + queryString(child) + ')' : '(' + child.key + ':' + child.value + ')'; }) .join(' ' + parameters.operator + ' '); }; return function (parameters, callback) { $.ajax(_.merge({}, ajaxOptions, { url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''), success: function (result) { if (!result.ok) { return callback(new Error('Invalid response received from server')); } delete result.ok; callback(undefined, _.values(result)); }, error: function (jqXHR, textStatus, err) { if (logErrors && console && typeof console.error === 'function') { console.error(jqXHR, textStatus, err); } callback(err || 'An unknown error occurred'); } })); }; }; } ); }());
Fix issue with brackets in generated queries.
Fix issue with brackets in generated queries.
JavaScript
mit
rwahs/research-frontend,rwahs/research-frontend
82344afed3636343877719fa3aa03377ec6c4159
app/assets/javascripts/student_signup.js
app/assets/javascripts/student_signup.js
var studentSignUp = function(timeslot_id){ var data = {}; data.subject = $("#subject-input").val(); $("#modal_remote").modal('hide'); $.ajax({ data: data, type: "PATCH", url: "/api/timeslots/" + timeslot_id, beforeSend: customBlockUi(this) }).done(function(){ swal({ title: "Great!", text: "You have scheduled a tutoring session!", confirmButtonColor: "#66BB6A", type: "success" }); $('#tutor-cal').fullCalendar('refetchEvents'); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }
var studentSignUp = function(timeslot_id){ var data = {}; data.subject = $("#subject-input").val(); $("#modal_remote").modal('hide'); $.ajax({ data: data, type: "PATCH", url: "/api/timeslots/" + timeslot_id, beforeSend: customBlockUi(this) }).done(function(){ swal({ title: "Great!", text: "You have scheduled a tutoring session!", confirmButtonColor: "#FFFFFF", showConfirmButton: false, allowOutsideClick: true, timer: 1500, type: "success" }); $('#tutor-cal').fullCalendar('refetchEvents'); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }
Add timer and remove confirm buttonk, overall cleanup for better ux
Add timer and remove confirm buttonk, overall cleanup for better ux
JavaScript
mit
theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board
49dfd4fea21ee7868a741c770db551c6e3bcdf5b
commonjs/frontend-core.js
commonjs/frontend-core.js
var _ = require('underscore'); _.extend(Array.prototype, { //deprecated! -> forEach (ist auch ein JS-Standard!) each: function(fn, scope) { _.each(this, fn, scope); }, //to use array.forEach directly forEach: function(fn, scope) { _.forEach(this, fn, scope); } }); if (typeof Array.prototype.add != 'function') { //add is alias for push Array.prototype.add = function () { this.push.apply(this, arguments); }; } if (typeof Array.prototype.shuffle != 'function') { //+ Jonas Raoni Soares Silva //@ http://jsfromhell.com/array/shuffle [rev. #1] Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
var _ = require('underscore'); if (typeof Array.prototype.forEach != 'function') { Array.prototype.forEach = function (fn, scope) { _.forEach(this, fn, scope); }; } //source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; }
Revert "Revert "set only forEach globally for Array.prototyp if not exists (ie8 fallback)""
Revert "Revert "set only forEach globally for Array.prototyp if not exists (ie8 fallback)"" This reverts commit 86586d27805750e77dd598669d12336be35c4d51.
JavaScript
bsd-2-clause
kaufmo/koala-framework,kaufmo/koala-framework,koala-framework/koala-framework,kaufmo/koala-framework,koala-framework/koala-framework
dfd8429c117fa2bf0af2a336807d40296b68ab84
frontend/src/shogi/pieces/nullPiece.js
frontend/src/shogi/pieces/nullPiece.js
import Base from './base'; import * as CONST from '../constants/pieceTypes'; export default class NullPiece extends Base { constructor({ type, x, y, movable = false, isPlaced = false }) { super({ type, x, y, movable, isPlaced }); this.type = CONST.USI_NULL_TYPE; return this; } promote() { return this; } unpromote() { return this; } isPromoted() { return true; } moveDef() { } }
import Base from './base'; import * as CONST from '../constants/pieceTypes'; export default class NullPiece extends Base { constructor({ type, x, y, movable = false, isPlaced = false }) { super({ type, x, y, movable, isPlaced }); this.type = CONST.USI_NULL_TYPE; return this; } promote() { return this; } unpromote() { return this; } isPromoted() { return true; } toOpponentPiece() { } moveDef() { } }
Add `toOpponentPiece` method for NullPiece
Add `toOpponentPiece` method for NullPiece * return undefined. because NullPiece can't captured.
JavaScript
mit
mgi166/usi-front,mgi166/usi-front
eb05d0a5b3b2fd16b1056d23118f1bfc093cb00f
GruntFile.js
GruntFile.js
module.exports = function(grunt) { grunt.config.init({ pkg: grunt.file.readJSON('package.json') }); grunt.loadNpmTasks('grunt-eslint'); grunt.config('eslint', { dist: { options: { configFile: '.eslintrc', }, src: ['touchtap-event.js'] } }); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.config('jasmine', { test: { src: 'touchtap-event.js', options: { specs: 'test/*-spec.js' } } }); grunt.registerTask('test', [ 'jasmine:test', ]); grunt.registerTask('default', [ 'eslint', 'test' ]); };
module.exports = function(grunt) { grunt.config.init({ pkg: grunt.file.readJSON('package.json') }); grunt.loadNpmTasks('grunt-eslint'); grunt.config('eslint', { dist: { options: { configFile: '.eslintrc', }, src: ['touchtap-event.js'] } }); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.config('jasmine', { test: { src: 'touchtap-event.js', options: { specs: 'test/*-spec.js' } } }); grunt.registerTask('test', [ 'eslint', 'jasmine:test', ]); grunt.registerTask('default', [ 'test' ]); };
Move eslint in to test grunt task
Move eslint in to test grunt task
JavaScript
mit
Tyriar/touchtap-event,Tyriar/touchtap-event
66deb115264bfccba20ce5daac9ee252febd245d
test/index.js
test/index.js
var PI = require("../lib"); // Two decimals console.log(PI(3)); console.log(PI(16)); // 100 decimals console.log(PI(100));
var PI = require("../lib"); // Two decimals console.log("3." + PI(3)); console.log("3." + PI(16)); // 100 decimals console.log("3." + PI(1000));
Prepend "3." since the function returns the decimals.
Prepend "3." since the function returns the decimals.
JavaScript
mit
IonicaBizau/pi-number
5af9b4617fd2f0fc3e613d6695ec876814deb793
test/setup.js
test/setup.js
/*! * React Native Autolink * * Copyright 2016-2019 Josh Swan * Released under the MIT license * https://github.com/joshswan/react-native-autolink/blob/master/LICENSE */ import Adapter from 'enzyme-adapter-react-16'; import Enzyme from 'enzyme'; Enzyme.configure({ adapter: new Adapter() }); require('react-native-mock-render/mock');
/*! * React Native Autolink * * Copyright 2016-2019 Josh Swan * Released under the MIT license * https://github.com/joshswan/react-native-autolink/blob/master/LICENSE */ import Adapter from 'enzyme-adapter-react-16'; import Enzyme from 'enzyme'; Enzyme.configure({ adapter: new Adapter() }); require('react-native-mock-render/mock'); require('@babel/register')({ only: [ 'src/**/*.js', 'test/**/*.js', 'node_modules/autolinker/dist/es2015/**/*.js', ], });
Fix transpiling issue in tests
Fix transpiling issue in tests
JavaScript
mit
joshswan/react-native-autolink,joshswan/react-native-autolink
66768e0aae1eeb622d0a901ee376d3f4d108f765
test/karma.config.js
test/karma.config.js
const serverEndpoints = require('./server') module.exports = function(config) { config.set({ basePath: '..', frameworks: ['detectBrowsers', 'mocha', 'chai'], detectBrowsers: { preferHeadless: true, usePhantomJS: false }, client: { mocha: { ui: 'tdd' } }, files: [ 'node_modules/promise-polyfill/promise.js', 'node_modules/abortcontroller-polyfill/dist/abortcontroller-polyfill-only.js', 'node_modules/url-search-params/build/url-search-params.max.js', 'dist/fetch.umd.js', 'test/test.js' ], reporters: process.env.CI ? ['dots'] : ['progress'], port: 9876, colors: true, logLevel: process.env.CI ? config.LOG_WARN : config.LOG_INFO, autoWatch: false, singleRun: true, concurrency: Infinity, beforeMiddleware: ['custom'], plugins: [ 'karma-*', { 'middleware:custom': ['value', serverEndpoints] } ] }) }
const serverEndpoints = require('./server') module.exports = function(config) { config.set({ basePath: '..', frameworks: ['detectBrowsers', 'mocha', 'chai'], detectBrowsers: { preferHeadless: true, usePhantomJS: false, postDetection: availableBrowsers => availableBrowsers.map(browser => (browser.startsWith('Chrom') ? `${browser}NoSandbox` : browser)) }, client: { mocha: { ui: 'tdd' } }, files: [ 'node_modules/promise-polyfill/promise.js', 'node_modules/abortcontroller-polyfill/dist/abortcontroller-polyfill-only.js', 'node_modules/url-search-params/build/url-search-params.max.js', 'dist/fetch.umd.js', 'test/test.js' ], reporters: process.env.CI ? ['dots'] : ['progress'], port: 9876, colors: true, logLevel: process.env.CI ? config.LOG_WARN : config.LOG_INFO, autoWatch: false, singleRun: true, concurrency: Infinity, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'] }, ChromiumHeadlessNoSandbox: { base: 'ChromiumHeadless', flags: ['--no-sandbox'] } }, beforeMiddleware: ['custom'], plugins: [ 'karma-*', { 'middleware:custom': ['value', serverEndpoints] } ] }) }
Bring back `--no-sandbox` for Travis CI compatibility
Bring back `--no-sandbox` for Travis CI compatibility
JavaScript
mit
github/fetch,aleclarson/fetch
386fbab3484a3bec5c2dcb538825c17979c0233e
lib/assets/javascripts/drop.js
lib/assets/javascripts/drop.js
//= require ./core //= require ./config //= require_self //= require_tree ./routers //= require_tree ./views //= require_tree ./models (function () { var Drop = window.Drop; _.extend(Drop, Marbles.Events, { Models: {}, Collections: {}, Routers: {}, Helpers: { fullPath: function (path) { prefix = Drop.config.PATH_PREFIX || '/'; return (prefix + '/').replace(/\/+$/, '') + path; } }, run: function (options) { if (!Marbles.history || Marbles.history.started) { return; } if (!options) { options = {}; } if (!this.config.container) { this.config.container = { el: document.getElementById('main') }; } Marbles.history.start(_.extend({ root: (this.config.PATH_PREFIX || '') + '/' }, options.history || {})); this.ready = true; this.trigger('ready'); } }); if (Drop.config_ready) { Drop.trigger('config:ready'); } })();
//= require ./core //= require ./config //= require_self //= require_tree ./routers //= require_tree ./views //= require_tree ./models (function () { var Drop = window.Drop; _.extend(Drop, Marbles.Events, { Views: {}, Models: {}, Collections: {}, Routers: {}, Helpers: { fullPath: function (path) { prefix = Drop.config.PATH_PREFIX || '/'; return (prefix + '/').replace(/\/+$/, '') + path; } }, run: function (options) { if (!Marbles.history || Marbles.history.started) { return; } if (!options) { options = {}; } if (!this.config.container) { this.config.container = { el: document.getElementById('main') }; } Marbles.history.start(_.extend({ root: (this.config.PATH_PREFIX || '') + '/' }, options.history || {})); this.ready = true; this.trigger('ready'); } }); if (Drop.config_ready) { Drop.trigger('config:ready'); } })();
Add Drop.Views object to hold React components
Add Drop.Views object to hold React components
JavaScript
bsd-3-clause
cupcake/files-web,cupcake/files-web
74c191b2f5058ecff0755b44eb55f79953e13808
blueprints/ember-sweetalert/index.js
blueprints/ember-sweetalert/index.js
module.exports = { normalizeEntityName: function() {}, afterInstall: function() {} };
module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addBowerPackageToProject('sweetalert2', '^6.1.0'); } };
Add bower package to project
Add bower package to project Believe this will fix issue #3, plus is desired behaviour anyway because you need the installing Ember project to have sweetalert2 installed via bower.
JavaScript
mit
Tonkpils/ember-sweetalert,Tonkpils/ember-sweetalert
1a55b57d10c44c0e036cf1a5d0ee35ab3b79a90e
lib/Helper/EventHandlerHelper.js
lib/Helper/EventHandlerHelper.js
"use babel"; import { Emitter } from 'atom' export default class EventHandlerHelper { constructor() { this.emitter = new Emitter(); } onClose(callback) { this.emitter.on("maperwiki-wordcount-close",callback); } close() { this.emitter.emit("maperwiki-wordcount-close"); } onViewWordcountFrame(callback) { this.emitter.on("maperwiki-wordcount-visibility",callback); } viewWordcountFrame(visible) { this.emitter.emit("maperwiki-wordcount-visibility",visible); } onCloseExportPanel(callback) { this.emitter.on("maperwiki-export-panel-close",callback); } closeExportPanel(visible) { this.emitter.emit("maperwiki-export-panel-close",visible); } onClear(callback) { this.emitter.on("clear-control",callback); } clear() { this.emitter.emit("clear-control"); } destroy() { this.emitter.clear(); this.emitter.dispose(); } dispose() { this.destroy(); } }
"use babel"; import { Emitter } from 'atom' export default class EventHandlerHelper { constructor() { this.emitter = new Emitter(); } onClose(callback) { return this.emitter.on("maperwiki-wordcount-close",callback); } close() { this.emitter.emit("maperwiki-wordcount-close"); } onViewWordcountFrame(callback) { return this.emitter.on("maperwiki-wordcount-visibility",callback); } viewWordcountFrame(visible) { this.emitter.emit("maperwiki-wordcount-visibility",visible); } onCloseExportPanel(callback) { return this.emitter.on("maperwiki-export-panel-close",callback); } closeExportPanel(visible) { this.emitter.emit("maperwiki-export-panel-close",visible); } onClear(callback) { return this.emitter.on("clear-control",callback); } clear() { this.emitter.emit("clear-control"); } destroy() { this.emitter.clear(); this.emitter.dispose(); } }
Patch for Event handler (second try) :)
Patch for Event handler (second try) :) Real patch for event handler...
JavaScript
mit
rkaradas/MaPerWiki,rkaradas/MaPerWiki
1c97af1dba133a014295c692135c2c194b500435
example/src/app.js
example/src/app.js
var App = Ember.Application.create(); App.Boards = ['common', 'intermediate', 'advanced']; App.Host = "http://localhost:5984";
var App = Ember.Application.create(); App.Boards = ['common', 'intermediate', 'advanced']; App.Host = "http://ember-couchdb-kit.roundscope.pw:15984";
Revert "reverted change of couchdb host"
Revert "reverted change of couchdb host" This reverts commit 6d60341ba077ef645c1f2f6dbf8a4030e07b2812.
JavaScript
mit
Zatvobor/ember-couchdb-kit,ValidUSA/ember-couch,Zatvobor/ember-couchdb-kit,ValidUSA/ember-couch
48992018fc9bb6fa38bac553fe2132ce84a50a8a
server/Media/FileScanner/getFiles.js
server/Media/FileScanner/getFiles.js
const debug = require('debug') const log = debug('app:media:fileScanner:getFiles') const { promisify } = require('util') const { resolve } = require('path') const fs = require('fs') const readdir = promisify(fs.readdir) const stat = promisify(fs.stat) async function getFiles (dir, extra) { let list = [] try { list = await readdir(dir) } catch (err) { log(err) } const files = await Promise.all(list.map(async (item) => { const file = resolve(dir, item) return (await stat(file)).isDirectory() ? getFiles(file, extra) : { file, ...extra } })) return files.reduce((a, f) => a.concat(f), []) } module.exports = getFiles
const { promisify } = require('util') const { resolve } = require('path') const fs = require('fs') const readdir = promisify(fs.readdir) const stat = promisify(fs.stat) async function getFiles (dir, extra) { const list = await readdir(dir) const files = await Promise.all(list.map(async (item) => { const file = resolve(dir, item) return (await stat(file)).isDirectory() ? getFiles(file, extra) : { file, ...extra } })) return files.reduce((a, f) => a.concat(f), []) } module.exports = getFiles
Fix path offline detection (don't catch readdir() errors)
Fix path offline detection (don't catch readdir() errors)
JavaScript
isc
bhj/karaoke-forever,bhj/karaoke-forever
0ef64c70248efaf7cd051d7d3d4db619cdae5589
ember_debug/models/profile_node.js
ember_debug/models/profile_node.js
/** A tree structure for assembling a list of render calls so they can be grouped and displayed nicely afterwards. @class ProfileNode **/ var ProfileNode = function(start, payload, parent) { this.start = start; this.timestamp = Date.now(); if (payload) { if (payload.template) { this.name = payload.template; } if (payload.object) { this.name = payload.object.toString(); var match = this.name.match(/:(ember\d+)>$/); if (match && match.length > 1) { this.viewGuid = match[1]; } } } else { this.name = "unknown view"; } if (parent) { this.parent = parent; } this.children = []; }; ProfileNode.prototype = { finish: function(timestamp) { this.time = (timestamp - this.start); this.calcDuration(); // Once we attach to our parent, we remove that reference // to avoid a graph cycle when serializing: if (this.parent) { this.parent.children.push(this); this.parent = null; } }, calcDuration: function() { this.duration = Math.round(this.time * 100) / 100; } }; export default ProfileNode;
/** A tree structure for assembling a list of render calls so they can be grouped and displayed nicely afterwards. @class ProfileNode **/ var ProfileNode = function(start, payload, parent) { this.start = start; this.timestamp = Date.now(); if (payload) { if (payload.template) { this.name = payload.template; } if (payload.object) { var name = payload.object.toString(); var match = name.match(/:(ember\d+)>$/); this.name = name.replace(/:?:ember\d+>$/, '').replace(/^</, ''); if (match && match.length > 1) { this.viewGuid = match[1]; } } } else { this.name = "unknown view"; } if (parent) { this.parent = parent; } this.children = []; }; ProfileNode.prototype = { finish: function(timestamp) { this.time = (timestamp - this.start); this.calcDuration(); // Once we attach to our parent, we remove that reference // to avoid a graph cycle when serializing: if (this.parent) { this.parent.children.push(this); this.parent = null; } }, calcDuration: function() { this.duration = Math.round(this.time * 100) / 100; } }; export default ProfileNode;
Clean up view name in render performance tree
Clean up view name in render performance tree
JavaScript
mit
karthiick/ember-inspector,Patsy-issa/ember-inspector,jryans/ember-inspector,knownasilya/ember-inspector,chrisgame/ember-inspector,chrisgame/ember-inspector,jayphelps/ember-inspector,Patsy-issa/ember-inspector,jayphelps/ember-inspector,sly7-7/ember-inspector,teddyzeenny/ember-inspector,pete-the-pete/ember-inspector,emberjs/ember-inspector,karthiick/ember-inspector,NikkiDreams/ember-inspector,pete-the-pete/ember-inspector,maheshsenni/ember-inspector,vvscode/js--ember-inspector,teddyzeenny/ember-extension,emberjs/ember-inspector,knownasilya/ember-inspector,sivakumar-kailasam/ember-inspector,teddyzeenny/ember-inspector,teddyzeenny/ember-extension,NikkiDreams/ember-inspector,aceofspades/ember-inspector,cibernox/ember-inspector,dsturley/ember-inspector,sly7-7/ember-inspector,maheshsenni/ember-inspector,sivakumar-kailasam/ember-inspector,dsturley/ember-inspector,cibernox/ember-inspector,vvscode/js--ember-inspector,aceofspades/ember-inspector,rwjblue/ember-inspector,jryans/ember-inspector
99c293ce2bd0f0e5ac297d62b1b158a9b4208d5d
slurp/src/main/webapp/scripts/init-firebase.js
slurp/src/main/webapp/scripts/init-firebase.js
// Copyright 2019 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. // Initialize Firebase and its related product we use using the provided // Firebase project configuation. var firebaseConfig = { apiKey: "AIzaSyAAJgRhJY_rRn_q_On1HdA3hx15YHSkEJg", authDomain: "step53-2020.firebaseapp.com", databaseURL: "https://step53-2020.firebaseio.com", projectId: "step53-2020", storageBucket: "step53-2020.appspot.com", messagingSenderId: "905834221913", appId: "1:905834221913:web:25e711f1132b2c0537fc48", measurementId: "G-PLVY991DHW" }; firebase.initializeApp(firebaseConfig);
// Copyright 2019 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. // Initialize Firebase and its related product we use using the provided // Firebase project configuation. var firebaseConfig = { apiKey: "AIzaSyAAJgRhJY_rRn_q_On1HdA3hx15YHSkEJg", authDomain: "step53-2020.firebaseapp.com", databaseURL: "https://step53-2020.firebaseio.com", projectId: "step53-2020", storageBucket: "step53-2020.appspot.com", messagingSenderId: "905834221913", appId: "1:905834221913:web:25e711f1132b2c0537fc48", measurementId: "G-PLVY991DHW" }; firebase.initializeApp(firebaseConfig); const db = firebase.firestore();
Add initializaton of Cloud Firestore instance for use accross all scripts.
Add initializaton of Cloud Firestore instance for use accross all scripts.
JavaScript
apache-2.0
googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP
056be57007a61135c167b4474bca96b015e8b34b
cfg/.vim/templates/react-native/fire.js
cfg/.vim/templates/react-native/fire.js
'use strict'; import React, { PropTypes, Component } from 'react'; import { InteractionManager } from 'react-native'; import SkeletonNameHOC from './skeleton-name.hoc.js'; export default class FierySkeletonName extends Component { constructor(props) { super(props); } static propTypes = { db: PropTypes.object, } static defaultProps = { db: {}, } render() { return ( <SkeletonNameHOC {...this.props} /> ); } }
'use strict'; import React, { PropTypes, Component } from 'react'; import { InteractionManager } from 'react-native'; import SkeletonNameHOC from './skeleton-name.hoc.js'; export default class FierySkeletonName extends Component { constructor(props) { super(props); } static propTypes = {} render() { return ( <SkeletonNameHOC {...this.props} /> ); } }
Remove db from props in template
Remove db from props in template Now that I have a React Native project where I take db and friends from context, I find that the automatic db in propTypes is a hassle to delete, so I've removed it for now.
JavaScript
mit
igemnace/vim-config,igemnace/my-vim-config,igemnace/vim-config,igemnace/vim-config
1e9c3b9c669c78e42fa9b6636ae72f5499b2175e
tests/directivesSpec.js
tests/directivesSpec.js
(function () { 'use strict'; describe('directives module', function () { var $compile, $rootScope, DropletMock; beforeEach(module('directives')); beforeEach(inject(function ($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', 'memory': '512' }; })); describe('status', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<status></status>')($scope); $rootScope.$digest(); }); it('should contains the "Status: active" string in a child node', function () { expect(element[0].innerText).toBe('Status: active'); }); }); describe('memory', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<memory></memory>')($scope); $rootScope.$digest(); }); it('should contains the "Memory: 512MB" string in a child node', function () { expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); }); })();
(function () { 'use strict'; describe('directives module', function () { var $compile, $rootScope, DropletMock; beforeEach(module('directives')); beforeEach(inject(function ($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); DropletMock = { 'status': 'active', 'memory': '512', 'vcpus': 1 }; })); describe('status', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<status></status>')($scope); $rootScope.$digest(); }); it('should contains the "Status: active" string in a child node', function () { expect(element[0].innerText).toBe('Status: active'); }); }); describe('memory', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<memory></memory>')($scope); $rootScope.$digest(); }); it('should contains the "Memory: 512MB" string in a child node', function () { expect(element[0].innerText).toBe('Memory: 512 MB'); }); }); describe('cpus', function () { var $scope, element; beforeEach(function () { $scope = $rootScope.$new(); $scope.droplet = DropletMock; element = $compile('<cpus></cpus>')($scope); $rootScope.$digest(); }); it('should contains the "CPUs: 1" string in a child node', function () { expect(element[0].innerText).toBe("CPUs: 1"); }); }); }); })();
Add cpus directive unit test
Add cpus directive unit test
JavaScript
mit
DojoGeekRA/DigitalOcean,DojoGeekRA/DigitalOcean
756929079aaf1dbef8b869d917e0fc8a0f4f3a10
examples/vue-apollo/nuxt.config.js
examples/vue-apollo/nuxt.config.js
module.exports = { build: { vendor: ['vue-apollo', 'apollo-client'] }, router: { middleware: 'apollo' }, plugins: [ // Will inject the plugin in the $root app and also in the context as `i18n` { src: '~plugins/apollo.js', injectAs: 'apolloProvider' } ] }
module.exports = { build: { vendor: ['vue-apollo', 'apollo-client'] }, router: { middleware: 'apollo' }, plugins: [ // Will inject the plugin in the $root app and also in the context as `apolloProvider` { src: '~plugins/apollo.js', injectAs: 'apolloProvider' } ] }
Fix copy paste typo in the comments
Fix copy paste typo in the comments
JavaScript
mit
jfroffice/nuxt.js,mgesmundo/nuxt.js,mgesmundo/nuxt.js,jfroffice/nuxt.js
239bc0fe0eeae2c309902e2b56dafbd2298cb3aa
app/services/logger.js
app/services/logger.js
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), rollbar: Ember.inject.service(), getReason(reason) { return reason instanceof Error || typeof reason !== "object" ? reason : JSON.stringify(reason); }, error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var userName = this.get("session.currentUser.fullName"); var currentUser = this.get("session.currentUser"); var userId = this.get("session.currentUser.id"); var error = this.getReason(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`; var airbrake = new airbrakeJs.Client({ projectId: config.APP.AIRBRAKE_PROJECT_ID, projectKey: config.APP.AIRBRAKE_PROJECT_KEY }); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.notify({ error, context: { userId, userName, environment, version } }); this.set('rollbar.currentUser', currentUser); this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment}); } } });
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), rollbar: Ember.inject.service(), getReason(reason) { return reason instanceof Error || typeof reason !== "object" ? reason : JSON.stringify(reason); }, error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var currentUser = this.get("session.currentUser"); var userName = currentUser.get("fullName"); var userId = currentUser.get("id"); var error = this.getReason(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`; var airbrake = new airbrakeJs.Client({ projectId: config.APP.AIRBRAKE_PROJECT_ID, projectKey: config.APP.AIRBRAKE_PROJECT_KEY }); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.notify({ error, context: { userId, userName, environment, version } }); this.set('rollbar.currentUser', currentUser); this.get('rollbar').error(error, data = { id: userId, username: userName, environment: environment}); } } });
Use currenUser instead of getting it from session
Use currenUser instead of getting it from session
JavaScript
mit
crossroads/shared.goodcity,crossroads/shared.goodcity
3689be16a26bd3f95eda6c57a4232952f6a87eca
ghost/admin/utils/codemirror-mobile.js
ghost/admin/utils/codemirror-mobile.js
/*global CodeMirror*/ import mobileUtils from 'ghost/utils/mobile-utils'; import createTouchEditor from 'ghost/assets/lib/touch-editor'; var setupMobileCodeMirror, TouchEditor, init; setupMobileCodeMirror = function setupMobileCodeMirror() { var noop = function () {}, key; for (key in CodeMirror) { if (CodeMirror.hasOwnProperty(key)) { CodeMirror[key] = noop; } } CodeMirror.fromTextArea = function (el, options) { return new TouchEditor(el, options); }; CodeMirror.keyMap = { basic: {} }; }; init = function init() { if (mobileUtils.hasTouchScreen()) { $('body').addClass('touch-editor'); // make editor tabs touch-to-toggle in portrait mode $('.floatingheader').on('touchstart', function () { $('.entry-markdown').toggleClass('active'); $('.entry-preview').toggleClass('active'); }); Ember.touchEditor = true; mobileUtils.initFastClick(); TouchEditor = createTouchEditor(); setupMobileCodeMirror(); } }; export default { createIfMobile: init };
/*global CodeMirror, device*/ import mobileUtils from 'ghost/utils/mobile-utils'; import createTouchEditor from 'ghost/assets/lib/touch-editor'; var setupMobileCodeMirror, TouchEditor, init; setupMobileCodeMirror = function setupMobileCodeMirror() { var noop = function () {}, key; for (key in CodeMirror) { if (CodeMirror.hasOwnProperty(key)) { CodeMirror[key] = noop; } } CodeMirror.fromTextArea = function (el, options) { return new TouchEditor(el, options); }; CodeMirror.keyMap = { basic: {} }; }; init = function init() { //Codemirror does not function on mobile devices, // nor on any iDevice. if (device.mobile() || (device.tablet() && device.ios())) { $('body').addClass('touch-editor'); // make editor tabs touch-to-toggle in portrait mode $('.floatingheader').on('touchstart', function () { $('.entry-markdown').toggleClass('active'); $('.entry-preview').toggleClass('active'); }); Ember.touchEditor = true; mobileUtils.initFastClick(); TouchEditor = createTouchEditor(); setupMobileCodeMirror(); } }; export default { createIfMobile: init };
Use Device.js to determine mobile editor use
Use Device.js to determine mobile editor use Ref #2570 - Adds new library, device.js to determine if the user is on an ios mobile or tablet.
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
b7491beeae4340a1d73d484c0b7671bb2f682edd
src/services/helpers/scopePermissions/ScopeMembersService.js
src/services/helpers/scopePermissions/ScopeMembersService.js
const auth = require('@feathersjs/authentication'); const globalHooks = require('../../../hooks'); const { ScopeService } = require('./ScopeService'); const { lookupScope, checkScopePermissions } = require('./hooks'); /** * Implements retrieving a list of all users who are associated with a scope. * @class ScopeMembersService * @extends {ScopeService} */ class ScopeMembersService extends ScopeService { /** * Custom set of hooks. * @static * @returns Object<FeathersHooksCollection> * @override ScopeService#hooks * @memberof ScopeMembersService */ static hooks() { return { before: { all: [ globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')), lookupScope, checkScopePermissions(['SCOPE_PERMISSIONS_VIEW']), ], }, }; } /** * Implements the route * @param {Object} params Feathers request params * @returns {Array<ObjectId>} a list of userIds * @memberof ScopeMembersService */ async find(params) { const members = await this.handler.apply(this, [params]) || []; return members; } } module.exports = { ScopeMembersService, };
const auth = require('@feathersjs/authentication'); const globalHooks = require('../../../hooks'); const { ScopeService } = require('./ScopeService'); const { lookupScope, checkScopePermissions } = require('./hooks'); /** * Implements retrieving a list of all users who are associated with a scope. * @class ScopeMembersService * @extends {ScopeService} */ class ScopeMembersService extends ScopeService { /** * Custom set of hooks. * @static * @returns Object<FeathersHooksCollection> * @override ScopeService#hooks * @memberof ScopeMembersService */ static hooks() { return { before: { all: [ globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')), lookupScope, globalHooks.ifNotLocal(checkScopePermissions(['SCOPE_PERMISSIONS_VIEW'])), ], }, }; } /** * Implements the route * @param {Object} params Feathers request params * @returns {Array<ObjectId>} a list of userIds * @memberof ScopeMembersService */ async find(params) { const members = await this.handler.apply(this, [params]) || []; return members; } } module.exports = { ScopeMembersService, };
Check for permission only in external calls
Check for permission only in external calls
JavaScript
agpl-3.0
schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server
63b38bdb6b304d495ed17ae2defa1f7512491c5c
aritgeo/src/aritgeo.js
aritgeo/src/aritgeo.js
'use strict' module.exports = { aritGeo: function(numlist) { if (!Array.isArray(numlist)) { return null; } if (numlist.length === 0) { return 0; } if (numlist.length === 1 || numlist.length === 2) { return -1; } } }
'use strict' module.exports = { aritGeo: function(numlist) { if (!Array.isArray(numlist)) { return null; } if (numlist.length === 0) { return 0; } if (numlist.length === 1 || numlist.length === 2) { return -1; } if (module.compute.isArithmetic(numlist.slice(1), numlist[1] - numlist[0])) { return 'Arithmetic'; } } } module.compute = { isArithmetic: function(numlist, diff) { if (numlist[1] - numlist[0] === diff) { if (numlist.length === 2) { return true; } else return true && this.isArithmetic(numlist.slice(1), numlist[1] - numlist[0]); } else return false; } }
Implement case for arithmetic sequences
Implement case for arithmetic sequences
JavaScript
mit
princess-essien/andela-bootcamp-slc
4471d6844864cb28e5ddd883781b690a48490089
public/app.js
public/app.js
/* jslint node: true */ 'use strict'; var AUTHORIZED_URLS = [ '/index.html' ]; var HOST = '0.0.0.0'; var PORT = 9917; function handleIo(socket) { socket.on('slide-update', function(msg) { socket.broadcast.emit("slide-update", msg); }); } function handleHTTP(req, res) { var path = url.parse(req.url).pathname; switch(path) { case '/': res.writeHeader(200, {'Content-Type': 'text/html'}); res.end('Hello'); break; case '/index.html': fs.readFile(__dirname + path, function(error, data) { if (error) { res.writeHeader(404); res.end('foo oops, this doesn\'t exist - 404'); } else { res.writeHeader(200, {'Content-Type': 'text/html'}); res.end(data, 'utf8'); } }); break; default: res.writeHeader(404); res.end('oops, this doesn\'t exist - 404'); break; } } var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(handleHTTP); server.listen(PORT, HOST); var io = require('socket.io')(server); io.on('connection', handleIo);
/* jslint node: true */ 'use strict'; var AUTHORIZED_URLS = [ '/index.html' ]; var HOST = '0.0.0.0'; var PORT = 9917; function handleIo(socket) { socket.on('slide-update', function(msg) { socket.broadcast.emit("slide-update", msg); }); } function handleHTTP(req, res) { var path = url.parse(req.url).pathname; switch(path) { case '/': fs.readFile(__dirname + '/index.html', function(error, data) { if (error) { res.writeHeader(404); res.end('foo oops, this doesn\'t exist - 404'); } else { res.writeHeader(200, {'Content-Type': 'text/html'}); res.end(data, 'utf8'); } }); break; default: res.writeHeader(404); res.end('oops, this doesn\'t exist - 404'); break; } } var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(handleHTTP); server.listen(PORT, HOST); var io = require('socket.io')(server); io.on('connection', handleIo);
Update router to default to slide control
Update router to default to slide control
JavaScript
mit
mbasanta/bespoke-remote-server,mbasanta/bespoke-remote-server
a8e892e298630309646cd9f6f3862d17c680f80d
app/scripts/utils.js
app/scripts/utils.js
'use strict'; (function() { angular.module('ncsaas') .factory('ncUtilsFlash', ['Flash', ncUtilsFlash]); function ncUtilsFlash(Flash) { return { success: function(message) { this.flashMessage('success', message); }, error: function(message) { this.flashMessage('danger', message); }, info: function(message) { this.flashMessage('info', message); }, warning: function(message) { this.flashMessage('warning', message); }, flashMessage: function(type, message) { Flash.create(type, message); } }; } angular.module('ncsaas') .factory('ncUtils', ['$rootScope', 'blockUI', ncUtils]); function ncUtils($rootScope, blockUI) { return { deregisterEvent: function(eventName) { $rootScope.$$listeners[eventName] = []; }, updateIntercom: function() { window.Intercom('update'); }, blockElement: function(element, promise) { var block = blockUI.instances.get(element); block.start(); promise.finally(function() { block.stop(); }); } } } })();
'use strict'; (function() { angular.module('ncsaas') .factory('ncUtilsFlash', ['Flash', ncUtilsFlash]); function ncUtilsFlash(Flash) { return { success: function(message) { this.flashMessage('success', message); }, error: function(message) { this.flashMessage('danger', message); }, info: function(message) { this.flashMessage('info', message); }, warning: function(message) { this.flashMessage('warning', message); }, flashMessage: function(type, message) { if (message) { Flash.create(type, message); } } }; } angular.module('ncsaas') .factory('ncUtils', ['$rootScope', 'blockUI', ncUtils]); function ncUtils($rootScope, blockUI) { return { deregisterEvent: function(eventName) { $rootScope.$$listeners[eventName] = []; }, updateIntercom: function() { window.Intercom('update'); }, blockElement: function(element, promise) { var block = blockUI.instances.get(element); block.start(); promise.finally(function() { block.stop(); }); } } } })();
Add check for message exist in ncUtilsFlash.flashMessage (SAAS-822)
Add check for message exist in ncUtilsFlash.flashMessage (SAAS-822) Added condition for ncUtilsFlash.flashMessage function.
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
80dbd6b199ab4a8a014150731303d31e7f7ba529
lib/factory-boy.js
lib/factory-boy.js
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { return _.findWhere(FactoryBoy._factories, {name: name}); }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; var deepExtend = Npm.require('deep-extend'); // Allow to overwrite the attribute definitions var attr = deepExtend(factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, collection, attrOverwrite) { var factory = this._getFactory(name); return factory.attributes; };
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory by that name'); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; var deepExtend = Npm.require('deep-extend'); // Allow to overwrite the attribute definitions var attr = deepExtend(factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, collection, attrOverwrite) { var factory = this._getFactory(name); return factory.attributes; };
Throw error if factory is not found
Throw error if factory is not found
JavaScript
mit
sungwoncho/factory-boy
150f734f4aae7a73a9fd3a6e6dd6017fc07cdd4d
imports/server/seed-data/seed-posts.js
imports/server/seed-data/seed-posts.js
import moment from 'moment'; import { Posts } from '../../api/collections'; const seedPosts = () => { const postCount = Posts.find().count(); if (postCount === 0) { for (let i = 0; i < 50; i++) { Posts.insert({ createdAt: moment().utc().toDate(), userId: 'QBgyG7MsqswQmvm7J', message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { type: 'Video', source: 'Facebook', thumb: '/images/feeds.jpg', url: 'https://www.meteor.com/', }, totalViews: 30, totalLikes: 14, totalShares: 3, totalComments: 3, }); Posts.insert({ createdAt: moment().utc().toDate(), userId: 'QBgyG7MsqswQmvm7J', message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { type: 'Photo', source: 'Instagram', thumb: '/images/feeds-2.jpg', url: 'https://www.meteor.com/', }, totalViews: 30, totalLikes: 14, totalShares: 3, totalComments: 3, }); } } }; export default seedPosts;
import moment from 'moment'; import { Posts } from '../../api/collections'; const seedPosts = () => { const post = Posts.findOne(); if (!post) { for (let i = 0; i < 50; i++) { Posts.insert({ userId: 'QBgyG7MsqswQmvm7J', username: 'evancorl', createdAt: moment().utc().toDate(), message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { type: 'Video', source: 'YouTube', thumbnail: '/images/feeds.jpg', url: 'https://www.meteor.com/', }, likeCount: 14, commentCount: 3, }); Posts.insert({ userId: 'QBgyG7MsqswQmvm7J', username: 'evancorl', createdAt: moment().utc().toDate(), message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { type: 'Photo', thumbnail: '/images/feeds-2.jpg', url: 'https://www.meteor.com/', }, likeCount: 14, commentCount: 3, }); } } }; export default seedPosts;
Reformat posts in seed data
Reformat posts in seed data
JavaScript
apache-2.0
evancorl/portfolio,evancorl/skate-scenes,evancorl/portfolio,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio
00d756fce1fc1f4baa3a0698fcba18421027b119
vue.config.js
vue.config.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const { NewLineKind } = require('typescript'); module.exports = { transpileDependencies: ['vuetify'], outputDir: './nest_desktop/app', // https://stackoverflow.com/questions/55258355/vue-clis-type-checking-service-ignores-memory-limits#55810460 // and https://cli.vuejs.org/config/#parallel configureWebpack: config => { // save the current ForkTsCheckerWebpackPlugin const existingForkTsChecker = config.plugins.filter( plugin => plugin instanceof ForkTsCheckerWebpackPlugin )[0]; // remove it config.plugins = config.plugins.filter( plugin => !(plugin instanceof ForkTsCheckerWebpackPlugin) ); // copy the options from the original ones, but modify memory and CPUs const newForkTsCheckerOptions = existingForkTsChecker.options; newForkTsCheckerOptions.memoryLimit = 8192; newForkTsCheckerOptions.workers = require('os').cpus().length - 1; config.plugins.push( new ForkTsCheckerWebpackPlugin(newForkTsCheckerOptions) ); }, };
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const { NewLineKind } = require('typescript'); module.exports = { productionSourceMap: false, transpileDependencies: ['vuetify'], outputDir: './nest_desktop/app', // https://stackoverflow.com/questions/55258355/vue-clis-type-checking-service-ignores-memory-limits#55810460 // and https://cli.vuejs.org/config/#parallel configureWebpack: config => { // save the current ForkTsCheckerWebpackPlugin const existingForkTsChecker = config.plugins.filter( plugin => plugin instanceof ForkTsCheckerWebpackPlugin )[0]; // remove it config.plugins = config.plugins.filter( plugin => !(plugin instanceof ForkTsCheckerWebpackPlugin) ); // copy the options from the original ones, but modify memory and CPUs const newForkTsCheckerOptions = existingForkTsChecker.options; newForkTsCheckerOptions.memoryLimit = 8192; newForkTsCheckerOptions.workers = require('os').cpus().length - 1; config.plugins.push( new ForkTsCheckerWebpackPlugin(newForkTsCheckerOptions) ); }, };
Disable source map for production
Disable source map for production
JavaScript
mit
babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop
53990bb3625947fc37c643b33842e7f3ba8340f7
lib/urlresolver.js
lib/urlresolver.js
var standardPageTypes = { 'event': /^(19|20)[0-9]{2}\// }; var resolveUrl = function(urlFragment) { return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, ''); }; var shortenUrl = function(url) { return url.replace(/^(http:\/\/){1}(www\.)?(lanyrd\.com\/){1}|\//, ''); }; var resolvePageType = function(url, types) { url = resolveUrl(url); types = types || standardPageTypes; var matches = Object.keys(types).filter(function(type) { var urlRegExp = types[type]; return urlRegExp.test(url); }); return matches.length ? matches[0] : null; }; module.exports = { resolveUrl: resolveUrl, shortenUrl: shortenUrl, resolvePageType: resolvePageType };
var standardPageTypes = { 'event': /^(19|20)[0-9]{2}\// }; var resolveUrl = function(urlFragment) { return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, ''); }; var shortenUrl = function(url) { return url.replace(/^(http:\/\/.*?)?\//, ''); }; var resolvePageType = function(url, types) { url = resolveUrl(url); types = types || standardPageTypes; var matches = Object.keys(types).filter(function(type) { var urlRegExp = types[type]; return urlRegExp.test(url); }); return matches.length ? matches[0] : null; }; module.exports = { resolveUrl: resolveUrl, shortenUrl: shortenUrl, resolvePageType: resolvePageType };
Make URL shortener more forgiving
Make URL shortener more forgiving
JavaScript
mit
markdalgleish/node-lanyrd-scraper
b3d6d0ea244499c44eb0d3f8c50b1b4ddc3625f8
src/controllers/SpotifyController.js
src/controllers/SpotifyController.js
controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#main, #app-player', playStateSelector: '#play, #play-pause', playStateClass: 'playing', playPauseSelector: '#play, #play-pause', nextSelector: '#next', previousSelector: '#previous', titleSelector: '.caption .track, #track-name', artistSelector: '.caption .artist, #track-artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image, #cover-art .sp-image-img').style.backgroundImage.slice(4, -1); });
if (!!document.querySelector('#app-player')) { // Old Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#app-player', playStateSelector: '#play-pause', playStateClass: 'playing', playPauseSelector: '#play-pause', nextSelector: '#next', previousSelector: '#previous', titleSelector: '#track-name', artistSelector: '#track-artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1); }); } else { // New Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#main', playStateSelector: '#play', playStateClass: 'playing', playPauseSelector: '#play', nextSelector: '#next', previousSelector: '#previous', titleSelector: '.caption .track', artistSelector: '.caption .artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1); }); }
Support New and Old Spotify
Support New and Old Spotify
JavaScript
agpl-3.0
cwal/chrome-media-keys,ahmedalsudani/chrome-media-keys,msfeldstein/chrome-media-keys,PeterMinin/chrome-media-keys,ahmedalsudani/chrome-media-keys,PeterMinin/chrome-media-keys,cwal/chrome-media-keys
cb906f55fa6f5ad491d0828a343a6d407cdd8e80
client/src/app.js
client/src/app.js
import createLogger from 'redux-logger'; import thunk from 'redux-thunk'; import transactionReducer from './reducers' import { applyMiddleware, createStore } from 'redux'; import { render } from 'react-dom'; import React from 'react'; import Main from './components/Main'; import { Provider } from 'react-redux'; const store = createStore( transactionReducer, applyMiddleware(thunk), applyMiddleware(createLogger()) ); render( <Provider store={store} > <Main /> </Provider>, document.getElementById('app') );
import createLogger from 'redux-logger'; import thunk from 'redux-thunk'; import transactionReducer from './reducers' import { applyMiddleware, createStore } from 'redux'; import { render } from 'react-dom'; import React from 'react'; import Main from './components/Main'; import { Provider } from 'react-redux'; const store = createStore( transactionReducer, applyMiddleware(thunk, createLogger()) ); render( <Provider store={store} > <Main /> </Provider>, document.getElementById('app') );
Fix middlewares order for proper thunk logging
Fix middlewares order for proper thunk logging
JavaScript
mit
Nauktis/inab,Nauktis/inab,Nauktis/inab
10fd21e05457f0225d39102002565cff2fff264f
src/util/filters.js
src/util/filters.js
export function filterByText(data, textFilter) { if (textFilter === '') { return data; } // case-insensitive textFilter = textFilter.toLowerCase(); const exactMatches = []; const substringMatches = []; data.forEach(i => { const name = i.name.toLowerCase(); if (name.split(' ').includes(textFilter)) { exactMatches.push(i); } else if (name.includes(textFilter)) { substringMatches.push(i); } }); return exactMatches.concat(substringMatches); } export function filterByCheckbox(data, checkboxFilters) { let filtered = data; Object.keys(checkboxFilters).forEach(i => { const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]); if (currentFilters.length) { filtered = filtered.filter(j => currentFilters.includes(j.filterable[i])); } }); return filtered; }
export function filterByText(data, textFilter) { if (textFilter === '') { return data; } // case-insensitive textFilter = textFilter.toLowerCase(); const exactMatches = []; const substringMatches = []; data.forEach(i => { const name = i.name.toLowerCase(); if (name.split(' ').includes(textFilter)) { exactMatches.push(i); } else if (name.includes(textFilter)) { substringMatches.push(i); } }); // return in ascending order return substringMatches.concat(exactMatches); } export function filterByCheckbox(data, checkboxFilters) { let filtered = data; Object.keys(checkboxFilters).forEach(i => { const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]); if (currentFilters.length) { filtered = filtered.filter(j => currentFilters.includes(j.filterable[i])); } }); return filtered; }
Return exact results by default
Return exact results by default
JavaScript
agpl-3.0
Johj/cqdb,Johj/cqdb
c0a1c31d1b49fddcdb790897176d9e5802da117e
client/config/bootstrap.js
client/config/bootstrap.js
/** * Client entry point */ // Polyfills import 'babel-polyfill' // Styles import 'components/styles/resets.css' // Modules import { browserHistory } from 'react-router' import React from 'react' import ReactDOM from 'react-dom' import Relay from 'react-relay' import { RelayRouter } from 'react-router-relay' // Routes import routes from './routes' // Configure Relay's network layer to include cookies Relay.injectNetworkLayer( new Relay.DefaultNetworkLayer('/graphql', { credentials: 'same-origin' }) ) // Create the app node appended to the body const app = document.body.appendChild(document.createElement('div')) // Mount the app ReactDOM.render( <RelayRouter history={browserHistory} routes={routes} />, app )
/** * Client entry point */ // Polyfills import 'babel-polyfill' // Styles import 'components/styles/resets.css' // Modules import { browserHistory } from 'react-router' import React from 'react' import ReactDOM from 'react-dom' import Relay from 'react-relay' import { RelayRouter } from 'react-router-relay' // Routes import routes from './routes' // Configure Relay's network layer to include cookies Relay.injectNetworkLayer( new Relay.DefaultNetworkLayer('/graphql', { credentials: 'same-origin' }) ) // Configure Relay's task scheduler to spread out task execution import raf from 'raf' Relay.injectTaskScheduler(task => raf(task)) // Create the app node appended to the body const app = document.body.appendChild(document.createElement('div')) // Mount the app ReactDOM.render( <RelayRouter history={browserHistory} routes={routes} />, app )
Use raf for Relay's task scheduler
Use raf for Relay's task scheduler
JavaScript
apache-2.0
cesarandreu/bshed,cesarandreu/bshed
88a806cb56dadead5f48eb1a7cdec6a26fc4d166
www/submit.js
www/submit.js
$('#task').on('change', function() { if ( $(this).val() == 'custom') { $('#custom_videos').removeClass('hidden'); } else { $('#custom_videos').addClass('hidden'); } });
$('#task').on('change', function() { if ( $(this).val() == 'custom') { $('#custom_videos').removeClass('hidden'); } else { $('#custom_videos').addClass('hidden'); } }); $('#task').trigger('change');
Make sure UI is consistent on load
Make sure UI is consistent on load
JavaScript
mit
mdinger/awcy,tdaede/awcy,tdaede/awcy,mdinger/awcy,mdinger/awcy,mdinger/awcy,tdaede/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,tdaede/awcy
df21faead2b427c56152eca744f12ce8fcc1e0ca
package/index.js
package/index.js
/* eslint global-require: 0 */ /* eslint import/no-dynamic-require: 0 */ const Environment = require('./environment') const { existsSync } = require('fs') function createEnvironment() { const path = `./environments/${process.env.NODE_ENV}` const constructor = existsSync(path) ? require(path) : Environment return new constructor() } const environment = createEnvironment() module.exports = { environment, Environment }
/* eslint global-require: 0 */ /* eslint import/no-dynamic-require: 0 */ const Environment = require('./environment') const { resolve } = require('path') const { existsSync } = require('fs') function createEnvironment() { const path = resolve(__dirname, 'environments', `${process.env.NODE_ENV}.js`) const constructor = existsSync(path) ? require(path) : Environment return new constructor() } const environment = createEnvironment() module.exports = { environment, Environment }
Resolve full file path + name to fix existsSync check
Resolve full file path + name to fix existsSync check
JavaScript
mit
gauravtiwari/webpacker,gauravtiwari/webpacker,usertesting/webpacker,rossta/webpacker,rossta/webpacker,rails/webpacker,usertesting/webpacker,rails/webpacker,rossta/webpacker,rossta/webpacker,usertesting/webpacker,gauravtiwari/webpacker
be877f2c612fa5a4049e563193feed3f349dca75
static/js/pedido.js
static/js/pedido.js
$(document).ready(function () { $("#id_type_1").click(function () { $("#id_inbound_date").parents('.row').hide(); $("#id_inbound_date_preference").parents('.row').hide(); }); $("#id_type_0").click(function () { $("#id_inbound_date").parents('.row').show(); $("#id_inbound_date_preference").parents('.row').show(); }); });
$(document).ready(function () { $("#id_type_1").click(function () { $("#id_inbound_date").parents('.row').hide(); $("#id_inbound_date_preference").parents('.row').hide(); }); $("#id_type_0").click(function () { $("#id_inbound_date").parents('.row').show(); $("#id_inbound_date_preference").parents('.row').show(); }); if (id_type_1.checked){ $("#id_inbound_date").parents('.row').hide(); $("#id_inbound_date_preference").parents('.row').hide(); } });
Hide or show inbound date according with type of trip selected
Hide or show inbound date according with type of trip selected
JavaScript
mpl-2.0
neuromat/nira,neuromat/nira,neuromat/nira
86b19d7030564176a56d2c1ab20ebe16df33066f
src/countdown/countdown.js
src/countdown/countdown.js
angular.module('ngIdle.countdown', ['ngIdle.idle']) .directive('idleCountdown', ['Idle', function(Idle) { return { restrict: 'A', scope: { value: '=idleCountdown' }, link: function($scope) { // Initialize the scope's value to the configured timeout. $scope.value = Idle._options().timeout; $scope.$on('IdleWarn', function(e, countdown) { $scope.$apply(function() { $scope.value = countdown; }); }); $scope.$on('IdleTimeout', function() { $scope.$apply(function() { $scope.value = 0; }); }); } }; }]);
angular.module('ngIdle.countdown', ['ngIdle.idle']) .directive('idleCountdown', ['Idle', function(Idle) { return { restrict: 'A', scope: { value: '=idleCountdown' }, link: function($scope) { // Initialize the scope's value to the configured timeout. $scope.value = Idle.getTimeout(); $scope.$on('IdleWarn', function(e, countdown) { $scope.$apply(function() { $scope.value = countdown; }); }); $scope.$on('IdleTimeout', function() { $scope.$apply(function() { $scope.value = 0; }); }); } }; }]);
Use Idle.getTimeout() instead of internal _options()
Use Idle.getTimeout() instead of internal _options()
JavaScript
mit
dgoncalves1/ng-idle,JCherryhomes/ng-idle,HackedByChinese/ng-idle,koitoer/ng-idle,MasterFacilityList/ng-idle,JCherryhomes/ng-idle,koitoer/ng-idle,karthilxg/ng-idle,MasterFacilityList/ng-idle,karthilxg/ng-idle,msuresu/ng-idle,seegno-forks/ng-idle,jpribesh/ng-idle,dgoncalves1/ng-idle,seegno-forks/ng-idle,msuresu/ng-idle,jpribesh/ng-idle
d377b7d8bfaf88408fdf3ef3182fb15df4689924
src/configs/webpack/project-config.js
src/configs/webpack/project-config.js
'use strict'; var tmpl = require('blueimp-tmpl').tmpl; var path = require('path'); var readTemplate = require('../../utils/read-template'); var projectName = require('project-name'); function buildProjectWebpackConfig(options) { var params = options || {}; var config = {}; if (params.env !== 'development' && params.env !== 'test' && params.env !== 'production') { throw new Error('INVALID ENVIROMENT: ' + params.env + '. Supported: [development, test, production]'); } config = { env: params.env }; config.webpackConfigPath = './' + path.join('node_modules', projectName(process.cwd()), 'dist', params.group); return config; } module.exports = function generateWebpackConfig(options) { var source = path.resolve(__dirname, '../../templates/project-webpack.js.tmpl'); var webpackTemplate = readTemplate(source); var webpackConfig = buildProjectWebpackConfig(options); var template = tmpl(webpackTemplate, webpackConfig); return { template: template, json: webpackConfig }; };
'use strict'; var tmpl = require('blueimp-tmpl').tmpl; var path = require('path'); var readTemplate = require('../../utils/read-template'); var projectName = require('project-name'); function buildProjectWebpackConfig(options) { var params = options || {}; var config = {}; if (params.env !== 'development' && params.env !== 'test' && params.env !== 'production') { throw new Error('INVALID ENVIROMENT: ' + params.env + '. Supported: [development, test, production]'); } config = { env: params.env }; config.webpackConfigPath = './' + path.join('node_modules', projectName(process.cwd()), 'dist', params.group, 'project-webpack.config.' + options.env + '.js'); return config; } module.exports = function generateWebpackConfig(options) { var source = path.resolve(__dirname, '../../templates/project-webpack.js.tmpl'); var webpackTemplate = readTemplate(source); var webpackConfig = buildProjectWebpackConfig(options); var template = tmpl(webpackTemplate, webpackConfig); return { template: template, json: webpackConfig }; };
Update webpack project config path
Update webpack project config path
JavaScript
mit
mikechau/js-config-gen,mikechau/js-config-gen
55474b5c3cb32f1cc53fe56b82d21c04a98a560e
app/assets/javascripts/evZoom.js
app/assets/javascripts/evZoom.js
$(function() { $('#zoom_01').elevateZoom(); });
$(function() { $('#zoom_01').elevateZoom(); $('.zoom').each(function(element) { $(this).elevateZoom() }); });
Update ElevateZoom uses class .zoom
Update ElevateZoom uses class .zoom
JavaScript
mit
gouf/test_elevate_zoom,gouf/test_elevate_zoom
37a73986d3d36353a30e661b3989dcd8a646bc39
04/jjhampton-ch4-list.js
04/jjhampton-ch4-list.js
// Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element. function arrayToList(array) { const arrayLength = array.length; let list = null; for (let i = array.length - 1; i >= 0; i-- ) { list = { value: array[i], rest: list }; } return list; } const theArray = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(arrayToList(theArray)); function listToArray(list) { console.log(list); const array = [ list.value, list.rest.value, list.rest.rest.value ]; return array; } // const theList = arrayToList([1, 2, 3]); // console.log(listToArray(theList)); // write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list function prepend(element, list) { let newList; // do some stuff here return newList; }
// Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element. function arrayToList(array) { const arrayLength = array.length; let list = null; for (let i = array.length - 1; i >= 0; i-- ) { list = { value: array[i], rest: list }; } return list; } const theArray = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(arrayToList(theArray)); function listToArray(list) { let array = []; for (let currentNode = list; currentNode; currentNode = currentNode.rest) { array.push(currentNode.value); } return array; } const theList = arrayToList([1, 2, 3, 4, 5, 6, 7, 8]); console.log(listToArray(theList)); // write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list function prepend(element, list) { let newList; // do some stuff here return newList; }
Refactor listToArray to work with list parameters of dynamic sizes
Refactor listToArray to work with list parameters of dynamic sizes
JavaScript
mit
OperationCode/eloquent-js
338634c1d6baeb464d3f723452427a8cd0d60929
test/smoke-tests.js
test/smoke-tests.js
var assert = require('assert') // , expresso = require('expresso') , dustx = require('dust-x') module.exports = { 'test 1': function(end) { assert.ok(true, 'pre-test') end(function() { assert.ok(false, 'post-test') }) } }
var assert = require('assert') , app = require('../example/app') module.exports = { 'GET /': function() { assert.response(app, { url: '/' }, { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' }}, function(res) { assert.includes(res.body, '<title>Dust-X Demo</title>'); } ) } }
Fix smoke-test to do something useful.
Fix smoke-test to do something useful.
JavaScript
mit
laurie71/dust-x
4a189c3a3dd1f0304a788c280d1839d94c40dc47
tests/acceptance.js
tests/acceptance.js
var assert = require('chai').assert; var http = require('http'); var mathServer = require('../lib/mathServer.js'); var request = require('supertest'); process.env.NODE_ENV = 'test'; describe('Acceptance test', function () { var port = 8006; var server; before(function () { process.on('stdout', function(data) { console.log('**' + data); }); process.on('stderr', function(data) { console.log('**' + data); }); server = mathServer.MathServer({ port: port, CONTAINERS: './dummy_containers.js' }); server.listen(); }); after(function (done) { server.close(); done(); }); describe('As basic behavior we', function () { it('should be able to create server and get title from html body', function (done) { http.get("http://127.0.0.1:" + port, function (res) { res.on('data', function (body) { var str = body.toString('utf-8'); var n = str.match(/<title>\s*([^\s]*)\s*<\/title>/); assert.equal(n[1], 'Macaulay2'); done(); }); }); }); it('should show title', function (done) { request = request('http://localhost:' + port); request.get('/').expect(200).end(function(error, result) { assert.match(result.text, /<title>\s*Macaulay2\s*<\/title>/); done(); }); }); }); });
var assert = require('chai').assert; var http = require('http'); var mathServer = require('../lib/mathServer.js'); var request = require('supertest'); process.env.NODE_ENV = 'test'; describe.only('Acceptance test', function () { var port = 8006; var server; before(function () { server = mathServer.MathServer({ port: port, CONTAINERS: './dummy_containers.js' }); server.listen(); request = request('http://localhost:' + port); }); after(function (done) { server.close(); done(); }); describe('As basic behavior we', function () { it('should be able to create server and get title from html body', function (done) { http.get("http://127.0.0.1:" + port, function (res) { res.on('data', function (body) { var str = body.toString('utf-8'); var n = str.match(/<title>\s*([^\s]*)\s*<\/title>/); assert.equal(n[1], 'Macaulay2'); done(); }); }); }); it('should show title', function (done) { request.get('/').expect(200).end(function(error, result) { assert.match(result.text, /<title>\s*Macaulay2\s*<\/title>/); done(); }); }); }); });
Fix supertest to not overwrite request
Fix supertest to not overwrite request
JavaScript
mit
antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell
15eb9523a92822b762a6e2c1cdc2a3d1f8426a8e
tests/test-utils.js
tests/test-utils.js
import { underscore } from '@ember/string'; export function serializer(payload) { const serializedPayload = {}; Object.keys(payload.attrs).map((_key) => { serializedPayload[underscore(_key)] = payload[_key]; }); return serializedPayload; }
import { underscore } from '@ember/string'; function _serialize_object(payload) { const serializedPayload = {}; Object.keys(payload.attrs).map((_key) => { serializedPayload[underscore(_key)] = payload[_key]; }); return serializedPayload; } export function serializer(data, many = false) { if (many == true) { return { count: data.length, next: null, previous: null, results: data.models.map((d) => { return _serialize_object(d); }), }; } else { return _serialize_object(data); } }
Refactor serializer to support list
Refactor serializer to support list
JavaScript
agpl-3.0
appknox/irene,appknox/irene,appknox/irene
1060df09e87e63a0a14e5cfa9d206721fa6d14cf
katas/tags.js
katas/tags.js
export const SPECIFICATION = 'spec'; export const MDN = 'mdn'; export const VIDEO = 'video'; export const ARTICLE = 'article'; export const DOCS = 'docs'; export const ANNOUNCEMENT = 'announcement'; export const BOOK = 'book'; export const QUOTE = 'quote'; export const DISCUSSION = 'discussion';
export const SPECIFICATION = 'spec'; export const MDN = 'mdn'; export const VIDEO = 'video'; export const ARTICLE = 'article'; export const DOCS = 'docs'; export const ANNOUNCEMENT = 'announcement'; export const BOOK = 'book'; export const QUOTE = 'quote'; export const DISCUSSION = 'discussion'; export const WIKIPEDIA = 'wikipedia';
Add wikipedia as a tag.
Add wikipedia as a tag.
JavaScript
mit
tddbin/katas,tddbin/katas,tddbin/katas
9fe0c1a5abd33fdbf4e2c90dd60874ec56b1e58c
src/js/xhr.js
src/js/xhr.js
var Q = require("../vendor/q/q"); exports.post = function (url, data) { console.log('posting to', url); var defer = Q.defer(); var xhr = new XMLHttpRequest(); xhr.onerror = function(err) { console.log('XMLHttpRequest error: ' + err); defer.reject(err); }; xhr.onreadystatechange = function () { console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status); if (xhr.readyState === 4 && xhr.status === 200) { defer.resolve(JSON.parse(xhr.responseText)); } else if (this.readyState === 4 && this.status === 401) { console.log('HTTP 401 returned'); defer.reject({code: 401}); } }; xhr.open('POST', url, true); xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); xhr.setRequestHeader("X-Accept", "application/json"); xhr.send(data || null); console.log('HTTP req sent to', url, data); return defer.promise; };
var Q = require("../vendor/q/q"); exports.post = function (url, data) { console.log('posting to', url); var defer = Q.defer(); var xhr = new XMLHttpRequest(); xhr.onerror = function(err) { console.log('XMLHttpRequest error: ' + err); defer.reject(err); }; xhr.onreadystatechange = function () { console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status); if (xhr.readyState === 4 && xhr.status === 200) { if(xhr.responseType === 'json') { defer.resolve(xhr.response); } else { // backward compatibility with previous versions of Kitt defer.resolve(JSON.parse(xhr.responseText)); } } else if (this.readyState === 4 && this.status === 401) { console.log('HTTP 401 returned'); defer.reject({code: 401}); } }; xhr.open('POST', url, true); xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); xhr.setRequestHeader("X-Accept", "application/json"); xhr.send(data || null); console.log('HTTP req sent to', url, data); return defer.promise; };
Make XHR compatible with new Kitt implementation
Make XHR compatible with new Kitt implementation
JavaScript
apache-2.0
kitt-browser/pocket,kitt-browser/pocket
3f1b7263c9f33ff205ac5ca3fa1466532906b3d1
client/common/actions/index.js
client/common/actions/index.js
import types from '../constants/ActionTypes' import utils from '../../shared/utils' function replaceUserInfo(userInfo) { return { type: types.REPLACE_USER_INFO, userInfo } } function fetchUserInfo() { return dispatch => { utils.ajax({url: '/api/user/getUserInfo'}).then(res => { dispatch(replaceUserInfo(res)) }) } } export default { replaceUserInfo, fetchUserInfo, clearUserInfo }
import types from '../constants/ActionTypes' import utils from '../../shared/utils' function replaceUserInfo(userInfo) { return { type: types.REPLACE_USER_INFO, userInfo } } function clearUserInfo() { return {type: types.CLEAR_USER_INFO} } function fetchUserInfo() { return dispatch => { utils.ajax({url: '/api/user/getUserInfo'}).then(res => { dispatch(replaceUserInfo(res)) }) } } export default { replaceUserInfo, fetchUserInfo, clearUserInfo }
Add plain object action clearUserInfo
Add plain object action clearUserInfo
JavaScript
mit
chikara-chan/react-isomorphic-boilerplate,qiuye1027/screenInteraction,qiuye1027/screenInteraction,chikara-chan/react-isomorphic-boilerplate
e5ce6180efaea8382a8514501ebb7bae88c3b541
views/crud-model.js
views/crud-model.js
var app = require('ridge'); module.exports = require('ridge/view').extend({ events: { 'click button': function(e) { e.preventDefault(); e.stopPropagation(); }, 'click button[data-command="publish"]': 'publish', 'click button[data-command="unpublish"]': 'unpublish', 'click button[data-command="delete"]': 'delete' }, delete: function(e) { if(confirm('Are you sure you want to delete the ' + this.model.name + '?')) { this.model.destroy(); this.remove(); } }, unpublish: function(e) { this.model.save({ datePublished: null }, { patch: true, wait: true }); }, publish: function(e) { this.model.save({ datePublished: new Date() }, { patch: true, wait: true }); }, initialize: function(options) { this.listenTo(this.model, 'sync', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'change:datePublished', function(model, value) { this.$el.toggleClass('published', !!value).toggleClass('unpublished', !value); }); } });
var app = require('ridge'); module.exports = require('ridge/view').extend({ events: { 'click button,select,input': function(e) { e.stopPropagation(); }, 'click button': function(e) { e.preventDefault(); }, 'click button[data-command="publish"]': 'publish', 'click button[data-command="unpublish"]': 'unpublish', 'click button[data-command="delete"]': 'delete' }, delete: function(e) { if(confirm('Are you sure you want to delete the ' + this.model.name + '?')) { this.model.destroy(); this.remove(); } }, unpublish: function(e) { this.model.save({ datePublished: null }, { patch: true, wait: true }); }, publish: function(e) { this.model.save({ datePublished: new Date() }, { patch: true, wait: true }); }, initialize: function(options) { this.listenTo(this.model, 'sync', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'change:datePublished', function(model, value) { this.$el.toggleClass('published', !!value).toggleClass('unpublished', !value); }); } });
Stop propagation for clicks (since a click on model view can toggle more information.
Stop propagation for clicks (since a click on model view can toggle more information.
JavaScript
mit
thecodebureau/ridge
e033d945329bb146ee82fc9d51f04665b950aa6b
src/server.js
src/server.js
let Path = require('path'); let Hapi = require('hapi'); var Good = require('good'); let server = new Hapi.Server({ connections: { routes: { files: { relativeTo: Path.join(__dirname, 'public') } } } }); server.connection({ port: 3000 }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply.file('index.html'); } }); server.route({ method: 'GET', path: '/{name}', handler: function (request, reply) { reply.file('index.html'); } }); // Serve everythign else from the public folder server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './' } } }); server.register({ register: Good, options: { reporters: [{ reporter: require('good-console'), events: { response: '*', log: '*' } }] } }, function (err) { if (err) { throw err; // something bad happened loading the plugin } server.start(function () { server.log('info', 'Server running at: ' + server.info.uri); }); });
let Path = require('path'); let Hapi = require('hapi'); var Good = require('good'); let server = new Hapi.Server({ connections: { routes: { files: { relativeTo: Path.join(__dirname, 'public') } } } }); server.connection({ port: 3000 }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply.file('index.html'); } }); server.route({ method: 'GET', path: '/{name}', handler: function (request, reply) { reply.file('index.html'); } }); server.route({ method: 'GET', path: '/blog/{name}', handler: function (request, reply) { reply.file('index.html'); } }); // Serve everythign else from the public folder server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './' } } }); server.register({ register: Good, options: { reporters: [{ reporter: require('good-console'), events: { response: '*', log: '*' } }] } }, function (err) { if (err) { throw err; // something bad happened loading the plugin } server.start(function () { server.log('info', 'Server running at: ' + server.info.uri); }); });
Add handler for blog path
Add handler for blog path
JavaScript
mit
bbondy/brianbondy.node,bbondy/brianbondy.node,bbondy/brianbondy.node
fa60bd7e2d0eec674595bff231c05d364f4d4aa1
lib/helper.js
lib/helper.js
var helper = exports; var copyDir = helper.copyDir = function (source, target) { var fs = require('fs'); var dir = fs.readdirSync(source); dir.forEach(function(item){ var s = fs.statSync(source + '/' + item); if(s.isDirectory()) { try { fs.mkdirSync(target + '/' + item); } catch (err) { // do nothing } copyDir(source + '/' + item, target + '/' + item); } else { var file = fs.readFileSync(source + '/' + item, 'utf8'); fs.writeFileSync(target + '/' + item, file); } }); }; // // Ascertain the root folder of the user's application. // var appDir = helper.appDir = (function () { var path = require('path'), fs = require('fs'), p; // // This is a list of the paths node looks through when resolving modules. // They should be in order of precedence. // process.mainModule.paths.some(function (q) { // // Look to see if big is installed in this node_modules folder, or // alternately if the folder actually belongs to big itself. // var bigIsInstalled = fs.existsSync(path.resolve(q, 'big')), thisIsBig = fs.existsSync(path.resolve(q, '..', 'big.js')); if (bigIsInstalled || thisIsBig) { p = q; // short circuit return true; } }); // p is the node_modules folder, so we should return the folder *above* it. return path.resolve(p, '..'); })();
var helper = exports; var copyDir = helper.copyDir = function (source, target) { var fs = require('fs'); var dir = fs.readdirSync(source); dir.forEach(function(item){ var s = fs.statSync(source + '/' + item); if(s.isDirectory()) { try { fs.mkdirSync(target + '/' + item); } catch (err) { // do nothing } copyDir(source + '/' + item, target + '/' + item); } else { var file = fs.readFileSync(source + '/' + item, 'utf8'); fs.writeFileSync(target + '/' + item, file); } }); }; // // Determine the root folder of the user's application // var appDir = helper.appDir = (function () { var path = require('path'), fs = require('fs'), p = process.cwd(); // // If we're in the repl, use process.cwd // if (!process.mainModule) { return p; } // // This is a list of the paths node looks through when resolving modules, // they should be in order of precedence. // process.mainModule.paths.some(function (q) { if (fs.existsSync(path.resolve(q, 'resource'))) { p = path.resolve(q, '..'); // short circuit return true; } }); return p; })();
Remove references to "big" in resource installing code. Resources should now install to the correct application directory.
[fix] Remove references to "big" in resource installing code. Resources should now install to the correct application directory.
JavaScript
mit
bigcompany/resource
3dcafb57bbc59709e5722fbdac07ad9493db4949
CalcuMan/src/classes/SoundsManager.js
CalcuMan/src/classes/SoundsManager.js
/** * @flow */ import {default as Sound} from 'react-native-sound' export default class SoundsManager { constructor (onChangeCallback) { this.muted = false this.sounds = {} this.onChangeCallback = onChangeCallback this.loadSound('toggle_on') this.loadSound('toggle_off') this.loadSound('timeout') } loadSound (key) { this.sounds[key] = new Sound(`${key}.mp3`, Sound.MAIN_BUNDLE) } play (key) { if (!this.muted) { this.sounds[key].play() } } setMuted (muted) { this.muted = muted this.onChangeCallback(muted) } }
/** * @flow */ import {default as Sound} from 'react-native-sound' export default class SoundsManager { constructor (onChangeCallback) { this.muted = false this.sounds = {} this.onChangeCallback = onChangeCallback this.lastPlayed = null this.loadSound('toggle_on') this.loadSound('toggle_off') this.loadSound('timeout') } loadSound (key) { this.sounds[key] = new Sound(`${key}.mp3`, Sound.MAIN_BUNDLE) } play (key) { if (!this.muted) { if (this.lastPlayed && this.lastPlayed.stop) { this.lastPlayed.stop() } this.lastPlayed = this.sounds[key] this.sounds[key].play() } } setMuted (muted) { this.muted = muted this.onChangeCallback(muted) } }
Stop previous sound before play new one
Stop previous sound before play new one
JavaScript
mit
antonfisher/game-calcuman,antonfisher/game-calcuman,antonfisher/game-calcuman
185e50fb0d94bbde6abb94c47e36046746912306
.gificiency/.gificiency.js
.gificiency/.gificiency.js
var Gificiency = (function() { 'use strict'; var search = function(filter) { $('a').each(function() { var elem = $(this); if (elem.text().search( new RegExp(filter, 'i') ) < 0) { elem.hide(); } else { elem.show(); } }); }; var getHash = function() { var filter; if (window.location.hash != '') { filter = window.location.hash.substring(1); } else { filter = false; } return filter; }; var clearImages = function() { $('img').each(function() { $(this).remove(); }); }; var popup = function(image) { return $('<img src="'+ image +'" />'); }; var Gificiency = { init: function() { if ( getHash() ) { search( getHash() ); } $('.search').on('keyup', function() { search( $(this).val() ); }); $('li').on('mouseover', function() { var elem = $(this).find('a'), image = elem.attr('href'); elem.parent().append( popup(image) ); }).on('mouseout', function() { clearImages(); }); } }; return Gificiency; })();
var Gificiency = (function() { 'use strict'; var searchField = $('.search'); var items = $('li'); var links = $('a'); var search = function(filter) { links.each(function() { var elem = $(this); if (elem.text().search( new RegExp(filter, 'i') ) < 0) { elem.hide(); } else { elem.show(); } }); }; var getHash = function() { var filter; if (window.location.hash != '') { filter = window.location.hash.substring(1); } else { filter = false; } return filter; }; var clearImages = function() { $('img').each(function() { $(this).remove(); }); }; var popup = function(image) { return $('<img src="'+ image +'" />'); }; var Gificiency = { init: function() { if ( getHash() ) { search( getHash() ); } Gificiency.events(); }, events: function() { searchField.on('keyup', function() { search( $(this).val() ); }); items.on('mouseover', function() { var elem = $(this).find('a'), image = elem.attr('href'); elem.parent().append( popup(image) ); }).on('mouseout', function() { clearImages(); }); } }; return Gificiency; })();
Set private vars, move events to public function
Set private vars, move events to public function
JavaScript
mit
drewbarontini/gificiency,drewbarontini/gificiency,drewbarontini/gificiency
a29a99b9a2bfedd5528be677ff24c4db2b19115a
backend/app/assets/javascripts/spree/backend/product_picker.js
backend/app/assets/javascripts/spree/backend/product_picker.js
$.fn.productAutocomplete = function (options) { 'use strict'; // Default options options = options || {}; var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true; this.select2({ minimumInputLength: 3, multiple: multiple, initSelection: function (element, callback) { $.get(Spree.routes.product_search, { ids: element.val().split(',') }, function (data) { callback(multiple ? data.products : data.products[0]); }); }, ajax: { url: Spree.routes.product_search, datatype: 'json', data: function (term, page) { return { q: { name_cont: term, sku_cont: term }, m: 'OR', token: Spree.api_key }; }, results: function (data, page) { var products = data.products ? data.products : []; return { results: products }; } }, formatResult: function (product) { return product.name; }, formatSelection: function (product) { return product.name; } }); }; $(document).ready(function () { $('.product_picker').productAutocomplete(); });
$.fn.productAutocomplete = function (options) { 'use strict'; // Default options options = options || {}; var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true; this.select2({ minimumInputLength: 3, multiple: multiple, initSelection: function (element, callback) { $.get(Spree.routes.product_search, { ids: element.val().split(','), token: Spree.api_key }, function (data) { callback(multiple ? data.products : data.products[0]); }); }, ajax: { url: Spree.routes.product_search, datatype: 'json', data: function (term, page) { return { q: { name_cont: term, sku_cont: term }, m: 'OR', token: Spree.api_key }; }, results: function (data, page) { var products = data.products ? data.products : []; return { results: products }; } }, formatResult: function (product) { return product.name; }, formatSelection: function (product) { return product.name; } }); }; $(document).ready(function () { $('.product_picker').productAutocomplete(); });
Add missing api key in product picker.
Add missing api key in product picker. Fixes #6185
JavaScript
bsd-3-clause
jasonfb/spree,mindvolt/spree,alvinjean/spree,adaddeo/spree,jspizziri/spree,sfcgeorge/spree,gregoryrikson/spree-sample,beni55/spree,JDutil/spree,rajeevriitm/spree,radarseesradar/spree,jparr/spree,JuandGirald/spree,useiichi/spree,CJMrozek/spree,ayb/spree,priyank-gupta/spree,builtbybuffalo/spree,Engeltj/spree,tancnle/spree,pulkit21/spree,groundctrl/spree,jaspreet21anand/spree,grzlus/spree,madetech/spree,welitonfreitas/spree,shekibobo/spree,pervino/spree,vulk/spree,archSeer/spree,brchristian/spree,alejandromangione/spree,jimblesm/spree,dafontaine/spree,gregoryrikson/spree-sample,sfcgeorge/spree,yiqing95/spree,TrialGuides/spree,rakibulislam/spree,useiichi/spree,APohio/spree,tomash/spree,imella/spree,alvinjean/spree,quentinuys/spree,JuandGirald/spree,alejandromangione/spree,thogg4/spree,Ropeney/spree,calvinl/spree,hifly/spree,piousbox/spree,hoanghiep90/spree,JDutil/spree,berkes/spree,patdec/spree,vinayvinsol/spree,KMikhaylovCTG/spree,orenf/spree,gregoryrikson/spree-sample,jaspreet21anand/spree,Lostmyname/spree,vcavallo/spree,SadTreeFriends/spree,nooysters/spree,jspizziri/spree,raow/spree,Hawaiideveloper/shoppingcart,fahidnasir/spree,edgward/spree,jaspreet21anand/spree,hoanghiep90/spree,abhishekjain16/spree,zaeznet/spree,mleglise/spree,DarkoP/spree,siddharth28/spree,gautamsawhney/spree,priyank-gupta/spree,abhishekjain16/spree,odk211/spree,camelmasa/spree,CiscoCloud/spree,Boomkat/spree,lyzxsc/spree,piousbox/spree,sunny2601/spree,FadliKun/spree,joanblake/spree,builtbybuffalo/spree,patdec/spree,SadTreeFriends/spree,ramkumar-kr/spree,azranel/spree,alejandromangione/spree,omarsar/spree,zamiang/spree,Kagetsuki/spree,Lostmyname/spree,AgilTec/spree,SadTreeFriends/spree,ramkumar-kr/spree,volpejoaquin/spree,shaywood2/spree,azranel/spree,agient/agientstorefront,FadliKun/spree,karlitxo/spree,zamiang/spree,zaeznet/spree,omarsar/spree,Engeltj/spree,zamiang/spree,jeffboulet/spree,camelmasa/spree,abhishekjain16/spree,vinayvinsol/spree,maybii/spree,shekibobo/spree,cutefrank/spree,beni55/spree,tesserakt/clean_spree,caiqinghua/spree,Lostmyname/spree,reidblomquist/spree,abhishekjain16/spree,orenf/spree,kewaunited/spree,jspizziri/spree,tesserakt/clean_spree,DynamoMTL/spree,zaeznet/spree,rajeevriitm/spree,thogg4/spree,DynamoMTL/spree,reidblomquist/spree,DarkoP/spree,NerdsvilleCEO/spree,agient/agientstorefront,jimblesm/spree,piousbox/spree,tancnle/spree,madetech/spree,vulk/spree,KMikhaylovCTG/spree,DynamoMTL/spree,TrialGuides/spree,yiqing95/spree,locomotivapro/spree,TrialGuides/spree,NerdsvilleCEO/spree,AgilTec/spree,priyank-gupta/spree,tomash/spree,gautamsawhney/spree,SadTreeFriends/spree,jparr/spree,archSeer/spree,dafontaine/spree,miyazawatomoka/spree,vulk/spree,odk211/spree,NerdsvilleCEO/spree,moneyspyder/spree,welitonfreitas/spree,edgward/spree,calvinl/spree,vmatekole/spree,CiscoCloud/spree,progsri/spree,FadliKun/spree,fahidnasir/spree,TimurTarasenko/spree,nooysters/spree,robodisco/spree,robodisco/spree,builtbybuffalo/spree,njerrywerry/spree,jasonfb/spree,jeffboulet/spree,tesserakt/clean_spree,CiscoCloud/spree,madetech/spree,archSeer/spree,azranel/spree,ramkumar-kr/spree,lsirivong/spree,quentinuys/spree,jparr/spree,hifly/spree,hifly/spree,volpejoaquin/spree,radarseesradar/spree,beni55/spree,sunny2601/spree,Ropeney/spree,siddharth28/spree,sfcgeorge/spree,KMikhaylovCTG/spree,karlitxo/spree,firman/spree,vinsol/spree,dafontaine/spree,adaddeo/spree,lsirivong/spree,carlesjove/spree,karlitxo/spree,vinsol/spree,adaddeo/spree,njerrywerry/spree,jspizziri/spree,berkes/spree,robodisco/spree,quentinuys/spree,calvinl/spree,edgward/spree,ayb/spree,siddharth28/spree,volpejoaquin/spree,patdec/spree,yiqing95/spree,trigrass2/spree,Ropeney/spree,TimurTarasenko/spree,hifly/spree,AgilTec/spree,wolfieorama/spree,vinsol/spree,lsirivong/spree,CJMrozek/spree,rakibulislam/spree,edgward/spree,Kagetsuki/spree,lyzxsc/spree,pervino/spree,sunny2601/spree,jparr/spree,fahidnasir/spree,Kagetsuki/spree,Lostmyname/spree,alejandromangione/spree,yushine/spree,tancnle/spree,rajeevriitm/spree,sliaquat/spree,madetech/spree,zamiang/spree,joanblake/spree,lyzxsc/spree,useiichi/spree,pulkit21/spree,KMikhaylovCTG/spree,mleglise/spree,ahmetabdi/spree,vinayvinsol/spree,reidblomquist/spree,miyazawatomoka/spree,softr8/spree,mindvolt/spree,DynamoMTL/spree,Ropeney/spree,nooysters/spree,CJMrozek/spree,carlesjove/spree,brchristian/spree,omarsar/spree,azranel/spree,grzlus/spree,FadliKun/spree,locomotivapro/spree,CJMrozek/spree,jasonfb/spree,DarkoP/spree,vulk/spree,pulkit21/spree,hoanghiep90/spree,Boomkat/spree,JuandGirald/spree,vcavallo/spree,tomash/spree,yiqing95/spree,vinsol/spree,wolfieorama/spree,thogg4/spree,piousbox/spree,yushine/spree,caiqinghua/spree,shekibobo/spree,orenf/spree,berkes/spree,ahmetabdi/spree,robodisco/spree,ramkumar-kr/spree,raow/spree,agient/agientstorefront,ayb/spree,TrialGuides/spree,dafontaine/spree,rajeevriitm/spree,vmatekole/spree,kewaunited/spree,Hawaiideveloper/shoppingcart,gregoryrikson/spree-sample,jeffboulet/spree,berkes/spree,NerdsvilleCEO/spree,maybii/spree,caiqinghua/spree,moneyspyder/spree,firman/spree,yushine/spree,raow/spree,cutefrank/spree,softr8/spree,vmatekole/spree,progsri/spree,cutefrank/spree,cutefrank/spree,groundctrl/spree,thogg4/spree,imella/spree,imella/spree,calvinl/spree,groundctrl/spree,omarsar/spree,njerrywerry/spree,sfcgeorge/spree,mindvolt/spree,softr8/spree,shaywood2/spree,gautamsawhney/spree,firman/spree,trigrass2/spree,agient/agientstorefront,zaeznet/spree,tancnle/spree,tomash/spree,mleglise/spree,priyank-gupta/spree,carlesjove/spree,adaddeo/spree,beni55/spree,pervino/spree,APohio/spree,moneyspyder/spree,groundctrl/spree,brchristian/spree,TimurTarasenko/spree,gautamsawhney/spree,sunny2601/spree,APohio/spree,TimurTarasenko/spree,maybii/spree,jimblesm/spree,moneyspyder/spree,kewaunited/spree,Engeltj/spree,pulkit21/spree,builtbybuffalo/spree,mleglise/spree,maybii/spree,tesserakt/clean_spree,patdec/spree,sliaquat/spree,brchristian/spree,kewaunited/spree,jaspreet21anand/spree,welitonfreitas/spree,camelmasa/spree,radarseesradar/spree,raow/spree,alvinjean/spree,mindvolt/spree,CiscoCloud/spree,volpejoaquin/spree,vcavallo/spree,progsri/spree,Boomkat/spree,JDutil/spree,fahidnasir/spree,rakibulislam/spree,jimblesm/spree,progsri/spree,odk211/spree,quentinuys/spree,rakibulislam/spree,odk211/spree,jasonfb/spree,pervino/spree,Engeltj/spree,shaywood2/spree,vinayvinsol/spree,joanblake/spree,grzlus/spree,shaywood2/spree,sliaquat/spree,radarseesradar/spree,siddharth28/spree,softr8/spree,shekibobo/spree,orenf/spree,APohio/spree,DarkoP/spree,miyazawatomoka/spree,miyazawatomoka/spree,trigrass2/spree,ayb/spree,locomotivapro/spree,Hawaiideveloper/shoppingcart,Boomkat/spree,archSeer/spree,lyzxsc/spree,grzlus/spree,useiichi/spree,AgilTec/spree,sliaquat/spree,vcavallo/spree,wolfieorama/spree,welitonfreitas/spree,karlitxo/spree,lsirivong/spree,yushine/spree,JDutil/spree,camelmasa/spree,vmatekole/spree,ahmetabdi/spree,reidblomquist/spree,Kagetsuki/spree,carlesjove/spree,trigrass2/spree,caiqinghua/spree,firman/spree,nooysters/spree,hoanghiep90/spree,njerrywerry/spree,locomotivapro/spree,jeffboulet/spree,joanblake/spree,Hawaiideveloper/shoppingcart,ahmetabdi/spree,wolfieorama/spree,JuandGirald/spree,alvinjean/spree
cc5aa2d5902750420cb9dfde1acec0893e22df40
test/spec/react-loader-test.js
test/spec/react-loader-test.js
/** @jsx React.DOM */ var React = require('react'); var Loader = require('../../lib/react-loader'); var expect = require('chai').expect; var loader; describe('Loader', function () { describe('before loaded', function () { beforeEach(function () { loader = <Loader loaded={false}>Welcome</Loader>; React.renderComponent(loader, document.body); }); it('renders the loader', function () { expect(document.body.innerHTML).to.match(/<div class="loader"/); }); it('does not render the content', function () { expect(document.body.innerHTML).to.not.match(/Welcome/); }); }); describe('after loaded', function () { beforeEach(function () { loader = <Loader loaded={true}>Welcome</Loader>; React.renderComponent(loader, document.body); }); it('does not render the loader', function () { expect(document.body.innerHTML).to.not.match(/<div class="loader"/); }); it('renders the content', function () { expect(document.body.innerHTML).to.match(/Welcome/); }); }); });
/** @jsx React.DOM */ var React = require('react'); var Loader = require('../../lib/react-loader'); var expect = require('chai').expect; describe('Loader', function () { var testCases = [{ description: 'loading is in progress', options: { loaded: false }, expectedOutput: /<div class="loader".*<div class="spinner"/ }, { description: 'loading is in progress with spinner options', options: { loaded: false, radius: 17, width: 900 }, expectedOutput: /<div class="loader"[^>]*?><div class="spinner"[^>]*?>.*translate\(17px, 0px\).*style="[^"]*?height: 900px;/ }, { describe: 'loading is complete', options: { loaded: true }, expectedOutput: /<div[^>]*>Welcome<\/div>/ }]; testCases.forEach(function (testCase) { describe(testCase.description, function () { beforeEach(function () { var loader = new Loader(testCase.options, 'Welcome'); React.renderComponent(loader, document.body); }); it('renders the correct output', function () { expect(document.body.innerHTML).to.match(testCase.expectedOutput); }) }); }); });
Update test suite to ensure spinner and spinner options are rendered as expected
Update test suite to ensure spinner and spinner options are rendered as expected
JavaScript
mit
CarLingo/react-loader,gokulkrishh/react-loader,alengel/react-loader,aparticka/react-loader,CarLingo/react-loader,quickleft/react-loader,CognizantStudio/react-loader,CognizantStudio/react-loader,aparticka/react-loader,quickleft/react-loader,gokulkrishh/react-loader,dallonf/react-loader,insekkei/react-loader,dallonf/react-loader,alengel/react-loader,insekkei/react-loader
64038fb9752955742180bc734fb8686dede22662
app/index.js
app/index.js
import React from 'react' import ReactDOM from 'react-dom' import getRoutes from './config/routes' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import users from 'redux/modules/users' import thunk from 'redux-thunk' import { checkIfAuthed } from 'helpers/auth' const store = createStore(users, applyMiddleware(thunk)) function checkAuth (nextState, replace) { const isAuthed = checkIfAuthed(store) const nextPathName = nextState.location.pathname if (nextPathName === '/' || nextPathName === '/auth') { if (isAuthed === true) { replace('/feed') } } else { if (isAuthed !== true) { replace('/auth') } } } ReactDOM.render( <Provider store={store}> {getRoutes(checkAuth)} </Provider>, document.getElementById('app') )
import React from 'react' import ReactDOM from 'react-dom' import getRoutes from './config/routes' import { createStore, applyMiddleware, compose } from 'redux' import { Provider } from 'react-redux' import users from 'redux/modules/users' import thunk from 'redux-thunk' import { checkIfAuthed } from 'helpers/auth' const store = createStore(users, compose( applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : (f) => f )) function checkAuth (nextState, replace) { const isAuthed = checkIfAuthed(store) const nextPathName = nextState.location.pathname if (nextPathName === '/' || nextPathName === '/auth') { if (isAuthed === true) { replace('/feed') } } else { if (isAuthed !== true) { replace('/auth') } } } ReactDOM.render( <Provider store={store}> {getRoutes(checkAuth)} </Provider>, document.getElementById('app') )
Include redux devtools through compose
Include redux devtools through compose
JavaScript
mit
StuartPearlman/duckr,StuartPearlman/duckr
bf669b035df93e5e27b5683ad59c3b68e0ac5fdb
client/partials/mybilltable.js
client/partials/mybilltable.js
Template.mybilltable.created = function(){ Session.set('message', ''); }; Template.mybilltable.helpers({ onReady: function(){ //Meteor.subscribe("mybills"); }, bill: function(){ return bills.find({ registeredby: Meteor.userId() }); }, nobills: function(){ var thebills = bills.find({ registeredby: Meteor.userId() }).fetch(); if (thebills.length === 0){ Session.set('message','<div class="no-data alert alert-danger">You haven\'t registered any bills! <a href="{{ pathFor "newbill" }}">Register your first bill!</a></div>'); return Session.get('message'); } } });
Template.mybilltable.created = function(){ Session.set('message', ''); }; Template.mybilltable.helpers({ onReady: function(){ //Meteor.subscribe("mybills"); }, bill: function(){ return bills.find({ registeredby: Meteor.userId() }); }, nobills: function(){ var thebills = bills.find({ registeredby: Meteor.userId() }).fetch(); if (thebills.length === 0){ Session.set('message','<div class="no-data alert alert-danger">You haven\'t registered any bills! <a href="/new-bill">Register your first bill!</a></div>'); return Session.get('message'); } } });
Fix link in Profile error message.
Fix link in Profile error message.
JavaScript
mit
celsom3/undocumoney,celsom3/undocumoney
09e3525e15e891760bcb737c9948d774aa12f061
frontend/src/sub-components/translate.js
frontend/src/sub-components/translate.js
import privateInfo from "../../../../../credentials/token.json"; /** * Fetches translated text using the Google Translate API */ export function getTranslation(term, fromLang, toLang) { const response = fetch("/translation", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ rawText: `${term}`, toLang: `${toLang}`, fromLang: `${fromLang}`, }), }) .then((res) => res.json()) .then((result) => { console.log(result); return result.translation; }) .catch((error) => { return "Could not Translate"; }); }
import privateInfo from "../../../../../credentials/token.json"; /** * Fetches translated text using the Google Translate API */ export function getTranslation(term, fromLang, toLang) { const response = fetch("/translation", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ rawText: `${term}`, toLang: `${toLang}`, fromLang: `${fromLang}`, }), }) .then((res) => res.json()) .then((result) => { return result.translation; }) .catch((error) => { return "Could not Translate"; }); }
Remove console.log from all files
Remove console.log from all files
JavaScript
apache-2.0
google/step197-2020,google/step197-2020,google/step197-2020,google/step197-2020
30f098e5baab15c95a111050d02ec4e9a16ffcbe
test/postgres-sql-loader.js
test/postgres-sql-loader.js
// Test that loading SQL files for PostgreSQL works. 'use strict'; var Code = require('code'); var Lab = require('lab'); var Querious = require('../index'); var path = require('path'); var lab = module.exports.lab = Lab.script(); lab.experiment('PostgreSQL sql file loading', function () { lab.test('it works with a basic query', function (done) { var instance = new Querious({ cache_sql: false, dialect: 'postgresql', sql_folder: path.resolve(__dirname, 'sql/postgresql') }); instance.loadSql('basic-query', function (err, sql) { Code.expect(err).to.not.exist(); Code.expect(sql).to.equal("SELECT 2+2;\n"); done(); }); }); lab.test('it works with a basic query in a .pgsql file', function (done) { var instance = new Querious({ dialect: 'postgresql', sql_folder: path.resolve(__dirname, 'sql/postgresql') }); instance.loadSql('pi-approximation', function (err, sql) { Code.expect(err).to.not.exist(); Code.expect(sql).to.equal("SELECT 22/7;\n"); done(); }); }); });
// Test that loading SQL files for PostgreSQL works. 'use strict'; var Code = require('code'); var Lab = require('lab'); var Querious = require('../index'); var path = require('path'); var lab = module.exports.lab = Lab.script(); lab.experiment('PostgreSQL sql file loading', function () { lab.test('it works with a basic query', function (done) { var instance = new Querious({ cache_sql: false, dialect: 'postgresql', sql_folder: path.resolve(__dirname, 'sql/postgresql') }); instance.loadSql('basic-query', function (err, sql) { Code.expect(err).to.not.exist(); Code.expect(sql).to.equal("SELECT 2+2;\n"); done(); }); }); lab.test('it works with a basic query in a .pgsql file', function (done) { var instance = new Querious({ dialect: 'postgresql', sql_folder: path.resolve(__dirname, 'sql/postgresql') }); instance.loadSql('pi-approximation', function (err, sql) { Code.expect(err).to.not.exist(); Code.expect(sql).to.equal("SELECT 22/7;\n"); done(); }); }); lab.test('it fails when loading a non-existing file', function (done) { var instance = new Querious({ dialect: 'postgresql', sql_folder: path.resolve(__dirname, 'sql/postgresql') }); instance.loadSql('does-not-exist', function (err, sql) { Code.expect(err.slice(0, 42)).to.equal("Querious: No file matching `does-not-exist"); Code.expect(sql).to.not.exist(); done(); }); }); });
Test for ambigous file loading.
Test for ambigous file loading.
JavaScript
isc
mikl/querious
42a38b012ae01477845ef926d4620b12f0a418f6
prime/index.test.js
prime/index.test.js
/* eslint-env node, jest */ const shogi = require('./index.js'); const Slack = require('../lib/slackMock.js'); jest.mock('../achievements/index.ts'); let slack = null; beforeEach(() => { slack = new Slack(); process.env.CHANNEL_SANDBOX = slack.fakeChannel; shogi(slack); }); describe('shogi', () => { it('responds to "素数大富豪"', async () => { const {username, text} = await slack.getResponseTo('素数大富豪'); expect(username).toBe('primebot'); expect(text).toContain('手札'); }); });
/* eslint-env node, jest */ jest.mock('../achievements/index.ts'); const shogi = require('./index.js'); const Slack = require('../lib/slackMock.js'); let slack = null; beforeEach(() => { slack = new Slack(); process.env.CHANNEL_SANDBOX = slack.fakeChannel; shogi(slack); }); describe('shogi', () => { it('responds to "素数大富豪"', async () => { const {username, text} = await slack.getResponseTo('素数大富豪'); expect(username).toBe('primebot'); expect(text).toContain('手札'); }); });
Fix order of invokation of achievement mocking
Fix order of invokation of achievement mocking
JavaScript
mit
tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot
c690ddf5bbcbc0fd9bedfe547d924f1621dcd76c
app/assets/javascripts/letter_opener_web/application.js
app/assets/javascripts/letter_opener_web/application.js
//= require jquery-1.8.3.min //= require_tree . jQuery(function($) { $('.letter-opener').on('click', 'tr', function() { var $this = $(this); $('iframe').attr('src', $this.find('a').attr('href')); $this.parent().find('.active').removeClass('active'); $this.addClass('active'); }); $('.refresh').click(function(e) { e.preventDefault(); var table = $('.letter-opener'); table.find('tbody').empty().append('<tr><td colspan="2">Loading...</td></tr>'); table.load(table.data('letters-path') + ' .letter-opener'); }); });
//= require jquery-1.8.3.min //= require_tree . jQuery(function($) { $('.letter-opener').on('click', 'tr', function() { var $this = $(this); $('iframe').attr('src', $this.find('a').attr('href')); $this.parent().find('.active').removeClass('active'); $this.addClass('active'); }); $('.refresh').click(function(e) { e.preventDefault(); var table = $('.letter-opener'); table.find('tbody').empty().append('<tr><td colspan="2">Loading...</td></tr>'); table.load(table.data('letters-path') + ' .letter-opener', function() { $('iframe').attr('src', $('.letter-opener tbody a:first-child()').attr('href')); }); }); });
Refresh letters content on <iframe> when reloading letters list
Refresh letters content on <iframe> when reloading letters list
JavaScript
mit
ProctorU/letter_opener_web,sergey-verevkin/letter_opener_web,fgrehm/letter_opener_web,sergey-verevkin/letter_opener_web,fgrehm/letter_opener_web,fgrehm/letter_opener_web,ProctorU/letter_opener_web,fgrehm/letter_opener_web,sergey-verevkin/letter_opener_web,ProctorU/letter_opener_web,ProctorU/letter_opener_web
920d357a257d13cec80f227d1637a437070d7557
app/scripts/components/experts/requests/create/expert-contract-form.js
app/scripts/components/experts/requests/create/expert-contract-form.js
import template from './expert-contract-form.html'; const expertContract = { template, bindings: { model: '=', form: '<', contractTemplate: '<', expert: '<', errors: '<', }, controller: class ExpertContractController { $onInit() { this.loading = true; let sortedOptions = {}; angular.forEach(this.expert.order, name => { sortedOptions[name] = this.expert.options[name]; }); this.expert.options = sortedOptions; this.tabs = [this.createTab(gettext('Details'), this.expert.options)]; angular.forEach(this.contractTemplate.order, tabName => { let tab = this.contractTemplate.options[tabName]; this.tabs.push(this.createTab(tab.label, tab.options)); angular.forEach(tab.options, (option, name) => { option.name = name; if (option.default) { this.model[name] = option.default; } }); }); this.loading = false; } createTab(name, options) { return { label: name, options: options, required: Object.keys(options).some(name => options[name].required), }; } } }; export default expertContract;
import template from './expert-contract-form.html'; const expertContract = { template, bindings: { model: '=', form: '<', contractTemplate: '<', expert: '<', errors: '<', }, controller: class ExpertContractController { $onInit() { this.loading = true; let sortedOptions = {}; angular.forEach(this.expert.order, name => { sortedOptions[name] = this.expert.options[name]; }); this.expert.options = sortedOptions; this.tabs = [this.createTab(gettext('Details'), this.expert.options)]; angular.forEach(this.contractTemplate.order, tabName => { let tab = this.contractTemplate.options[tabName]; this.tabs.push(this.createTab(tab.label, tab.options)); angular.forEach(tab.options, (option, name) => { option.name = name; if (this.expert.options_overrides[name] && this.expert.options_overrides[name].default_value !== undefined) { this.model[name] = this.expert.options_overrides[name].default_value; } else if (option.default) { this.model[name] = option.default; } }); }); this.loading = false; } createTab(name, options) { return { label: name, options: options, required: Object.keys(options).some(name => options[name].required), }; } } }; export default expertContract;
Allow to override specific contract template values
Allow to override specific contract template values - CS-208
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
62c0a2cde5383d927fa8d45a26b04f5237030818
push-clients/service-worker.js
push-clients/service-worker.js
self.addEventListener('push', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { var focused = false; for (var i = 0; i < clientList.length; i++) { if (clientList[i].focused) { focused = true; break; } } return self.registration.showNotification('ServiceWorker Cookbook', { body: focused ? 'You\'re still here, thanks!' : 'Click me, please!', }); })); }); self.addEventListener('notificationclick', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { if (clientList.length > 0) { return clientList[0].focus(); } else { return clients.openWindow('./push-clients/index.html'); } })); });
self.addEventListener('push', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { var focused = false; for (var i = 0; i < clientList.length; i++) { if (clientList[i].focused) { focused = true; break; } } var notificationMessage; if (focused) { notificationMessage = 'You\'re still here, thanks!'; } else if (clientList.length > 0) { notificationMessage = 'You haven\'t closed the page, click here to focus it!'; } else { notificationMessage = 'You have closed the page, click here to re-open it!'; } return self.registration.showNotification('ServiceWorker Cookbook', { body: notificationMessage, }); })); }); self.addEventListener('notificationclick', function(event) { event.waitUntil(clients.matchAll().then(function(clientList) { if (clientList.length > 0) { return clientList[0].focus(); } else { return clients.openWindow('./push-clients/index.html'); } })); });
Use different notification messages when the tab is focused, unfocused, closed
Use different notification messages when the tab is focused, unfocused, closed
JavaScript
mit
TimAbraldes/serviceworker-cookbook,mozilla/serviceworker-cookbook,mozilla/serviceworker-cookbook,TimAbraldes/serviceworker-cookbook
ea1907a5efc980997dde8b34bff7557a106ad9cd
src/index.js
src/index.js
// @flow /* Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { if (!self) { self = this; } return function() { var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
// @flow /* Transform a Promise-returning function into a function that can optionally * take a callback as the last parameter instead. * * @param {Function} fn a function that returns a Promise * @param {Object} self (optional) `this` to be used when applying fn * @return {Function} a function that can take callbacks as well. */ function optionalCallback(fn, self) { return function() { if (!self) { self = this; } var last = arguments[arguments.length - 1]; if (typeof last === 'function') { return fn.apply(self, arguments).then(function(){ last.apply(self, arguments); }).catch(function(err){ last(err); }); } else { return fn.apply(self, arguments); } }; } module.exports = optionalCallback;
Resolve the value of self later
Resolve the value of self later
JavaScript
mit
DimensionSoftware/optional-callback
9246a44a065a046293492edeccafc376a9aa628f
src/utils.js
src/utils.js
import fs from "fs"; import InputStream from "./InputStream"; export function isGreyspace(string) { if (string === "" || string === " " || string === "\n" || /^\s*$/.test(string)) { return true; } if (string === undefined || string === null) throw new Error("passed undefined or null to isGreyspace"); let stream = new InputStream(string); // Consume shebang stream.consume(/#!.*\n/); while (!stream.atEnd()) { let consumed = stream.consume(/\s+/) || stream.consume(/\/\/[^\n]*/) || stream.consume(/\/\*[\W\S]*?\*\//); if (!consumed) return false; } return stream.atEnd(); } export function log(...messages) { let data = messages.join(" ") + "\n"; try { fs.writeSync(3, data); } catch (error) { if (error.code === "EBADF") { return; } else { throw error; } } }
import fs from "fs"; import InputStream from "./InputStream"; const whitespaceRe = /\s+/; const shebangRe = /#!.*\n/; const lineCommentRe = /\/\/[^\n]*/; const blockCommentRe = /\/\*[\W\S]*?\*\//; export function isGreyspace(string) { if (string === "" || string === " " || string === "\n" || /^\s*$/.test(string)) { return true; } if (string === undefined || string === null) throw new Error("passed undefined or null to isGreyspace"); let stream = new InputStream(string); // Consume shebang stream.consume(shebangRe); while (!stream.atEnd()) { let consumed = stream.consume(whitespaceRe) || stream.consume(lineCommentRe) || stream.consume(blockCommentRe); if (!consumed) return false; } return stream.atEnd(); } export function parseGreyspace(string) { if (string === undefined || string === null) throw new Error("passed undefined or null to isGreyspace"); let parsedNodes = []; let stream = new InputStream(string); while (!stream.atEnd()) { if (stream.consume(whitespaceRe)) { parsedNodes.push({ type: "whitespace", value: stream.consumed }); } else if (stream.consume(lineCommentRe)) { parsedNodes.push({ type: "lineComment", value: stream.consumed }); } else if (stream.consume(blockCommentRe)) { parsedNodes.push({ type: "blockComment", value: stream.consumed }); } else if (stream.consume(shebangRe)) { parsedNodes.push({ type: "shebang", value: stream.consumed }); } else { // Takes care of assertion that string is greyspace throw new Error("string is not greyspace"); } } return parsedNodes; } export function log(...messages) { let data = messages.join(" ") + "\n"; try { fs.writeSync(3, data); } catch (error) { if (error.code === "EBADF") { return; } else { throw error; } } }
Create greyspace parser function to allow for splitting greyspace by type.
Create greyspace parser function to allow for splitting greyspace by type.
JavaScript
mit
Mark-Simulacrum/pretty-generator,Mark-Simulacrum/attractifier
62081fa8127cce340675fb462a83ee9c457e13a3
src/utils.js
src/utils.js
// @flow // Recursively remove undefined, null, empty objects and empty arrays export const compact = (obj: any): any => { if (obj === null) { return undefined; } if (Array.isArray(obj)) { const compacted = obj.map(v => compact(v)).filter( v => typeof v !== 'undefined' ); return compacted.length === 0 ? undefined : compacted; } if (typeof obj === 'object') { const compacted = Object.keys(obj).reduce((acc, key) => { const nested = compact(obj[key]); if (typeof nested === 'undefined') { return acc; } else { return { ...acc, [key]: nested }; } }, {}); return Object.keys(compacted).length === 0 ? undefined : compacted; } return obj; };
// @flow // Recursively remove undefined, null, empty objects and empty arrays export const compact = (value: any): any => { if (value === null) { return undefined; } if (Array.isArray(value)) { const compacted = value.map(v => compact(v)).filter( v => typeof v !== 'undefined' ); return compacted.length === 0 ? undefined : compacted; } if (typeof value === 'object') { const compacted = Object.keys(value).reduce((acc, key) => { const nested = compact(value[key]); if (typeof nested === 'undefined') { return acc; } else { return { ...acc, [key]: nested }; } }, {}); return Object.keys(compacted).length === 0 ? undefined : compacted; } return value; };
Rename 'obj' to 'value' for clarity
Rename 'obj' to 'value' for clarity
JavaScript
apache-2.0
contactlab/contacthub-sdk-nodejs
00f48eb9ab3f99883fea421afab2ddd875f32cf3
node_modules/c9/manifest.js
node_modules/c9/manifest.js
var git = require("./git"); var hostname = require("./hostname"); exports.load = function(root) { var manifest = require(root + "/package.json"); manifest.revision = manifest.revision || git.getHeadRevisionSync(root); manifest.hostname = hostname.get(); return manifest; };
var git = require("./git"); var hostname = require("./hostname"); var os = require("os"); exports.load = function(root) { var manifest = require(root + "/package.json"); manifest.revision = manifest.revision || git.getHeadRevisionSync(root); manifest.hostname = hostname.get(); manifest.internalIP = os.networkInterfaces().eth0 && os.networkInterfaces().eth0[0].address; return manifest; };
Store internal IP in docker host
Store internal IP in docker host
JavaScript
bsd-3-clause
humberto-garza/VideoJuegos,humberto-garza/VideoJuegos
15c69f68a85e0bffca04e8c67b81b7260198f1c8
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require tether //= require toastr //= require_tree . $(function () { $(".sticky").sticky({ topSpacing: 90 , zIndex: -0 , stopper: "#you_shall_not_pass" }); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require tether //= require toastr //= require_tree . document.addEventListener("turbolinks:load", function() { $(function () { $(".sticky").sticky({ topSpacing: 90 , zIndex: -0 , stopper: "#you_shall_not_pass" }); }); })
Update js for sticky content
Update js for sticky content
JavaScript
mit
bdisney/eShop,bdisney/eShop,bdisney/eShop
de7309b150f877e59c8303748f84fd9a9e96c472
app/assets/javascripts/application.js
app/assets/javascripts/application.js
//= require libs/jquery/jquery-ui-1.8.16.custom.min //= require libs/jquery/plugins/jquery.base64 //= require libs/jquery/plugins/jquery.mustache.js //= require core //= require devolution //= require popup //= require geo-locator //= require welcome //= require browse //= require search //= require jquery.history //= require jquery.tabs //= require mobile //= require js-stick-at-top-when-scrolling //= require stop-related-scrolling
//= require libs/jquery/jquery-ui-1.8.16.custom.min //= require libs/jquery/plugins/jquery.base64 //= require libs/jquery/plugins/jquery.mustache.js //= require core //= require devolution //= require popup //= require geo-locator //= require welcome //= require browse //= require search //= require jquery.history //= require jquery.tabs //= require mobile //= require govuk_toolkit
Remove unused javascript requirements and add frontend toolkit
Remove unused javascript requirements and add frontend toolkit
JavaScript
mit
alphagov/static,tadast/static,tadast/static,kalleth/static,robinwhittleton/static,kalleth/static,tadast/static,robinwhittleton/static,alphagov/static,tadast/static,alphagov/static,robinwhittleton/static,kalleth/static,robinwhittleton/static,kalleth/static
b1e3644c1eb0f68ec02325fca257198a276c4133
generators/template-engine/modules/nunjucks/nunjucks-express.js
generators/template-engine/modules/nunjucks/nunjucks-express.js
// view engine setup nunjucks.configure('views', { autoescape: true, express: app });
// view engine setup nunjucks.configure('views', { autoescape: true, express: app }); app.set('view engine', 'html');
Set default extension (html) for nunjucks
Set default extension (html) for nunjucks
JavaScript
mit
sahat/boilerplate,sahat/megaboilerplate,sahat/megaboilerplate,sahat/megaboilerplate,sahat/boilerplate
ea82d61def4d3e9be56cc4a3c8f2b01c5ff4c3e1
server/app.js
server/app.js
export default {}; var Twitter = require('twit-stream'); var keys =require('./authentication.js'); var stream = new Twitter(keys).stream('statuses/sample'); /// connection configuration for stream object to connect to API stream.on('connected', function(msg) { console.log('Connection successful.'); }); stream.on('reconnect', function(req, res, interval) { console.log('Reconnecting in ' + (interval / 1e3) + ' seconds.'); }); stream.on('disconnect', function(msg) { console.log('Twitter disconnection message'); console.log(msg); });
export default {}; var Twitter = require('twit-stream'); var keys =require('./authentication.js'); var stream = new Twitter(keys).stream('statuses/sample'); /// connection configuration for stream object to connect to API stream.on('connected', function(msg) { console.log('Connection successful.'); }); stream.on('reconnect', function(req, res, interval) { console.log('Reconnecting in ' + (interval / 1e3) + ' seconds.'); }); stream.on('disconnect', function(msg) { console.log('Twitter disconnection message'); console.log(msg); }); // connection returns if twitter cuts off connection and why stream.on('warning', function(message) { console.warning('Yikes! a Warning message:'); console.warning(message); }); stream.on('limit', function(message) { console.log('WOAH! issued a limit message:'); console.log(message) }) stream.on('disconnect', function(message) { console.log('NOPE! disconnection message'); console.log(message); });
Add event return listeners for Twitter warning,limit and discnct
Add event return listeners for Twitter warning,limit and discnct considering the amount of information you will be processing it is more imperative for you to take into account and work on being able to keep track of what twitters feedback is going to be. Thus created a series of event listeners for message feedback from twitter in the case.
JavaScript
isc
edwardpark/d3withtwitterstream,edwardpark/d3withtwitterstream
589e86a2a94e05f30cd8b39bbdb8c2c109a56427
js/console-save.js
js/console-save.js
//Source: //https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM //http://bgrins.github.io/devtools-snippets/#console-save (function(console){ console.save = function(data, filename){ if(!data) { console.error('Console.save: No data'); return; } if(!filename) filename = 'console.json'; if(typeof data === "object"){ data = JSON.stringify(data, undefined, 4); } var blob = new Blob([data], {type: 'text/json'}), e = document.createEvent('MouseEvents'), a = document.createElement('a'); a.download = filename; a.href = window.URL.createObjectURL(blob); a.dataset.downloadurl = ['text/json', a.download, a.href].join(':'); e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); a.dispatchEvent(e); }; })(console);
//Source: //https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM //http://bgrins.github.io/devtools-snippets/#console-save //A simple way to save objects as .json files from the console (function(console){ console.save = function(data, filename){ if(!data) { console.error('Console.save: No data'); return; } if(!filename) filename = 'console.json'; if(typeof data === "object"){ data = JSON.stringify(data, undefined, 4); } var blob = new Blob([data], {type: 'text/json'}), e = document.createEvent('MouseEvents'), a = document.createElement('a'); a.download = filename; a.href = window.URL.createObjectURL(blob); a.dataset.downloadurl = ['text/json', a.download, a.href].join(':'); e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); a.dispatchEvent(e); }; })(console);
Add import and export buttons
Add import and export buttons
JavaScript
mit
sjbuysse/sessions-map,sjbuysse/sessions-map
6a1098ef55e3723447d336384d0273f7f0a8dc00
misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js
misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @include https://deployer.london.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== const readyStateCheckInterval = setInterval(() => { if (document.readyState === 'complete') { clearInterval(readyStateCheckInterval); console.log('Monitor mode is go'); const $legend = document.querySelector('.legend'); $legend.style.display = 'none'; const $infoBox = document.querySelector('.lower-right-info'); $infoBox.style.display = 'none'; const $topBar = document.querySelector('#top-bar-app'); $topBar.style.display = 'none'; const $groupsBar = document.querySelector('.groups-bar'); $groupsBar.style.display = 'none'; const $bottom = document.querySelector('.bottom'); // Remove the padding because the top bar isn't there any more. $bottom.style.paddingTop = '0'; const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', ''); document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`); } }, 2000);
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @include https://deployer.london.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== const readyStateCheckInterval = setInterval(() => { if (document.readyState === 'complete') { clearInterval(readyStateCheckInterval); console.log('Monitor mode is go'); const $legend = document.querySelector('#legend'); $legend.style.display = 'none'; const $infoBox = document.querySelector('.lower-right-info'); $infoBox.style.display = 'none'; const $topBar = document.querySelector('#top-bar-app'); $topBar.style.display = 'none'; const $groupsBar = document.querySelector('#groups-bar'); $groupsBar.style.display = 'none'; const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', ''); document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`); } }, 2000);
Update chrome clean pipelines plugin to work with concourse 5
Update chrome clean pipelines plugin to work with concourse 5 This commit updates the divs that we wish to remove from the pipeline view.
JavaScript
mit
alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf
7d792bb25af6236a0fa53c561c7aa416129561b7
client/widgets/sharing/sharing.js
client/widgets/sharing/sharing.js
import Shariff from '/imports/ui/lib/shariff/shariff'; Template.sharing.onRendered(function() { this.autorun(() => { this.shariff = new Shariff(this.find('.shariff'), { lang: Session.get('locale'), services: [ 'twitter', 'facebook', 'whatsapp', 'googleplus', 'diaspora', 'mail', 'info', ] }); // Remove href and target from mail button. Instead install a click // event handler which opens a mail form. const mailAction = this.find('.shariff-button.mail a'); if (mailAction) { mailAction.removeAttribute('target'); mailAction.removeAttribute('href'); } }); }); Template.sharing.events({ 'click .shariff-button.mail a'(event) { event.stopPropagation(); console.log('e-mail button clicked! FIXME: open modal or something.') } });
import Shariff from '/imports/ui/lib/shariff/shariff'; Template.sharing.onRendered(function() { this.autorun(() => { this.shariff = new Shariff(this.find('.shariff'), { lang: Session.get('locale'), mailtoUrl: 'mailto:', services: [ 'twitter', 'facebook', 'whatsapp', 'googleplus', 'diaspora', 'mail', 'info', ] }); }); });
Use mailto: for the moment
Use mailto: for the moment
JavaScript
agpl-3.0
schuel/hmmm,schuel/hmmm,Openki/Openki,schuel/hmmm,Openki/Openki,Openki/Openki
f569688bc7ce880a1339697d3b775d67528d1eb8
static/scripts/helpers/form_bug_text.js
static/scripts/helpers/form_bug_text.js
/* eslint-disable max-len */ export default `Ich als [Nutzerrolle] habe auf der Seite [???] die Funktion [???] aufgrund des Fehlers/der Fehlermeldung "[???]" nicht benutzen können. Tritt der Fehler auch bei anderen/ ähnlichen Bereichen (z.B. andere Kurse oder Nutzer) auf? Wie genau äußert sich das Problem? Wenn mehrere Schritte notwendig sind, um das Problem nachzuvollziehen, diese hier bitte so kurz und klar wie möglich beschreiben. `;
/* eslint-disable max-len */ export default `Ich als [Nutzerrolle] habe auf der Seite [???] die Funktion [???] aufgrund des Fehlers/der Fehlermeldung "[???]" nicht benutzen können. Tritt der Fehler auch bei anderen/ ähnlichen Bereichen (z.B. andere Kurse oder Nutzer) auf? Wie genau äußert sich das Problem? Wann trat der Fehler genau auf (Datum, Uhrzeit), damit wir gezielt in den Logs schauen können? Wenn mehrere Schritte notwendig sind, um das Problem nachzuvollziehen, diese hier bitte so kurz und klar wie möglich beschreiben. `;
Add a new question regarding datetime
Add a new question regarding datetime
JavaScript
agpl-3.0
schul-cloud/schulcloud-client,schul-cloud/schulcloud-client,schul-cloud/schulcloud-client
25b2d06fe260f734ef6944062f410a74c3100bb5
sound-wave.js
sound-wave.js
const fs = require('fs'); const sampleRate = 44100, resolution = 16; const maxLevel = Math.pow(2, resolution - 1) - 1, BinaryArray = { 8: Int8Array, 16: Int16Array, 32: Int32Array }[resolution]; function sineWave(frequency, duration) { var samplesCount = duration * sampleRate, array = new BinaryArray(samplesCount); for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) { var currentTime = sampleNumber / sampleRate, signal = Math.sin(2 * Math.PI * frequency * currentTime), level = Math.floor(signal * maxLevel); array[sampleNumber] = level; } return array; } function writePCM(filename, frequency, duration) { var array = sineWave(frequency, duration), buffer = new Buffer(array); fs.writeFile(filename, buffer, 'binary'); } writePCM('440hz.pcm', 440, 10);
const fs = require('fs'); const sampleRate = 44100, resolution = 16; const maxLevel = Math.pow(2, resolution - 1) - 1, BinaryArray = { 8: Int8Array, 16: Int16Array, 32: Int32Array }[resolution]; function sineWave(frequency, duration) { var samplesCount = Math.floor(duration * sampleRate), array = new BinaryArray(samplesCount); for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) { var currentTime = sampleNumber / sampleRate, signal = Math.sin(2 * Math.PI * frequency * currentTime), level = Math.floor(signal * maxLevel); array[sampleNumber] = level; } return array; } function writePCM(filename, frequency, duration) { var array = sineWave(frequency, duration), buffer = new Buffer(array.buffer); fs.writeFile(filename, buffer, 'binary'); } writePCM('440hz.pcm', 440, 10);
Use array.buffer so that TypedArray and Buffer share the same memory
Use array.buffer so that TypedArray and Buffer share the same memory
JavaScript
mit
aqrln/sound-wave
4080e7daa4b5a9e7e37273036ac9e489bea226b9
spec/support/fixtures/stripejs-mock.js
spec/support/fixtures/stripejs-mock.js
class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.classList.add('StripeElement'); el.innerHTML = ` <input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text"> <input name="exp-date" placeholder="MM / YY" size="6" type="text"> <input name="cvc" placeholder="CVC" size="3" type="text"> `; } addEventListener(event) { return true; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { createPaymentMethod: () => { return new Promise(resolve => { resolve({ paymentMethod: { id: "pm_123", card: { brand: 'visa', last4: fetchLastFour(), exp_month: "10", exp_year: "2050" } } }); }); }, elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
// StripeJS fixture for using Stripe in feature specs. Mimics credit card form and Element objects. // Based on: https://github.com/thoughtbot/fake_stripe/blob/v0.3.0/lib/fake_stripe/assets/v3.js // The original has been adapted to work with OFN (see commit history for details). class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.classList.add('StripeElement'); el.innerHTML = ` <input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text"> <input name="exp-date" placeholder="MM / YY" size="6" type="text"> <input name="cvc" placeholder="CVC" size="3" type="text"> `; } addEventListener(event) { return true; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { createPaymentMethod: () => { return new Promise(resolve => { resolve({ paymentMethod: { id: "pm_123", card: { brand: 'visa', last4: fetchLastFour(), exp_month: "10", exp_year: "2050" } } }); }); }, elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
Add comments in StripeJS mock
Add comments in StripeJS mock
JavaScript
agpl-3.0
lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,lin-d-hop/openfoodnetwork,Matt-Yorkley/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork
6f83ef247f86a8581c9b66841cdea826a6fd90ed
server/config/db.js
server/config/db.js
var connection = { client: 'mysql', connection: { host: process.env.HOST, database: process.env.APP_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD, charset: 'utf8' } }; var knex = require('knex')(connection); connection.database = process.env.APP_NAME; var db = require('bookshelf')(knex); module.exports = db;
var connection = { client: 'mysql', connection: { host: 'localhost', database: process.env.APP_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD, charset: 'utf8' } }; var knex = require('knex')(connection); connection.database = process.env.APP_NAME; var db = require('bookshelf')(knex); module.exports = db;
Adjust database host to always be localhost
Adjust database host to always be localhost
JavaScript
mit
chkakaja/sentimize,formidable-coffee/masterfully,formidable-coffee/masterfully,chkakaja/sentimize
7f6e9e09e064c6d8b51960a579375684d660ecc9
src/client.js
src/client.js
import React from 'react' import ReactDOM from 'react-dom' /* Create a simple component without JSX <div> React Tutorial </div> */ const App = function() { return React.createElement('div', null, 'React Tutorial'); } ReactDOM.render(<App />, document.getElementById('app'))
import React from 'react' import ReactDOM from 'react-dom' /* Create a simple component without JSX <div> React Tutorial </div> */ const App = function() { // return React.createElement('div', null, 'React Tutorial'); return <div>React Tutorial</div>; } ReactDOM.render(<App />, document.getElementById('app'))
Create a simple component with JSX
Create a simple component with JSX
JavaScript
mit
suranartnc/react-tutorial