commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
217b9501b2b3e371e8c4c7fdbd534f9c1f6ca440
build/build.js
build/build.js
var extend = require('extend'); var path = require('path'); var cleanDist = require('./tasks/clean_dist'); var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); var polyfillJS = require('./tasks/polyfillJS'); module.exports = function(options) { /** * Default options for the build * * `components` is configuration for which components should be included in the * build. This defaults to only Govuk core stuff. The local build scripts also include * the "Build" category which contains styles for example pages */ var config = extend({ mode: 'development', cache: true, components: true, destination: 'dist' }, options); return new Promise(function(resolve, reject) { cleanDist(config) .then(function() { return copy.govUkTemplateAssets(config); }) .then(function() { return copy.govUkToolkitAssets(config); }) .then(function() { return copy.landregistryComponentAssets(config); }) .then(function() { return sass(config); }) .then(function() { return javascript.compile(config); }) .then(function() { resolve(path.join(config.destination, 'assets')); }) .catch(function(e) { reject(e); }); }); }
var extend = require('extend'); var path = require('path'); var cleanDist = require('./tasks/clean_dist'); var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); module.exports = function(options) { /** * Default options for the build * * `components` is configuration for which components should be included in the * build. This defaults to only Govuk core stuff. The local build scripts also include * the "Build" category which contains styles for example pages */ var config = extend({ mode: 'development', cache: true, components: true, destination: 'dist' }, options); return new Promise(function(resolve, reject) { cleanDist(config) .then(function() { return copy.govUkTemplateAssets(config); }) .then(function() { return copy.govUkToolkitAssets(config); }) .then(function() { return copy.landregistryComponentAssets(config); }) .then(function() { return sass(config); }) .then(function() { return javascript.compile(config); }) .then(function() { resolve(path.join(config.destination, 'assets')); }) .catch(function(e) { reject(e); }); }); }
Fix JS bug caused by previous commit
Fix JS bug caused by previous commit
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
9393b0303d6b991ef27758ebadaed670a290d7fc
generators/app/templates/_app/_app.js
generators/app/templates/_app/_app.js
var express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'); var routes = require('./routes'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { // log a message to console! }); module.exports = app;
var express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'); var routes = require('./routes'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { // log a message to console! }); module.exports = app;
Fix 'body-parser deprecated urlencoded' warning
Fix 'body-parser deprecated urlencoded' warning
JavaScript
mit
christiannwamba/generator-wean,christiannwamba/generator-wean
72aa328e3dcd2118c03a45781d9674976fc447dc
src/utils/convertJsToSass.js
src/utils/convertJsToSass.js
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function withQuotesIfNecessary(value) { const hasQuotes = /^['"](\n|.)*['"]$/gm.test(value) const requiresQuotes = /^[0 ]/.test(value) return hasQuotes || !requiresQuotes ? value : `"${value}"` } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return withQuotesIfNecessary(value) } return JSON.stringify(value) } module.exports = convertJsToSass
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return value } return JSON.stringify(value) } module.exports = convertJsToSass
Remove quotes from string because they break e.g. box shadows
Remove quotes from string because they break e.g. box shadows
JavaScript
mit
epegzz/sass-vars-loader,epegzz/sass-vars-loader,epegzz/sass-vars-loader
6951e92d15472187976538ed98cb9d572ce426bc
build/start.js
build/start.js
const childProcess = require("child_process"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; const watching = compiler.watch({}, (err, stats) => { if (err != null) { console.log(err); } else if (!electronStarted) { electronStarted = true; childProcess .spawn(electron, ["."], { stdio: "inherit" }) .on("close", () => { watching.close(); }); } console.log(stats.toString({ colors: true })); });
const childProcess = require("child_process"); const readline = require("readline"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; const clearTerminal = () => { if (process.stdout.isTTY) { const blankLines = "\n".repeat(process.stdout.rows); console.log(blankLines); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } }; const watching = compiler.watch({}, (err, stats) => { if (err != null) { console.log(err); } else if (!electronStarted) { electronStarted = true; childProcess .spawn(electron, ["."], { stdio: "inherit" }) .on("close", () => { watching.close(); }); } if (stats != null) { clearTerminal(); console.log(stats.toString({ colors: true })); } });
Clear terminal with each webpack rebuild
Clear terminal with each webpack rebuild
JavaScript
mit
szwacz/electron-boilerplate,szwacz/electron-boilerplate
c2e2b863bb2f18f3825a1c1ae19983c345a8db30
frontend/src/components/App.js
frontend/src/components/App.js
import React, { PropTypes } from 'react'; import { Link, IndexLink } from 'react-router'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. class App extends React.Component { render() { return ( <div> <div id="header-bar"> <span>{"2016 Presidental Debates "}</span> <IndexLink to="/">About</IndexLink> {' | '} <Link to="/play">Play</Link> {' | '} <Link to="/stats">Stats</Link> </div> <div className="pure-g"> <div className="pure-u-1-24 pure-u-sm-1-5"></div> <div className="pure-u-22-24 pure-u-sm-3-5"> {this.props.children} </div> <div className="pure-u-1-24 pure-u-sm-1-5"></div> </div> </div> ); } } App.propTypes = { children: PropTypes.element }; export default App;
import React, { PropTypes } from 'react'; import { Link, IndexLink } from 'react-router'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. class App extends React.Component { render() { return ( <div> <div id="header-bar"> <span>{"2016 Presidental Debates "}</span> <IndexLink to="/">About</IndexLink> {' | '} <Link to="/play">Play</Link> {' | '} <Link to="/stats">Stats</Link> </div> <div className="pure-g"> <div className="pure-u-1-24 pure-u-lg-1-5"></div> <div className="pure-u-22-24 pure-u-lg-3-5"> {this.props.children} </div> <div className="pure-u-1-24 pure-u-lg-1-5"></div> </div> </div> ); } } App.propTypes = { children: PropTypes.element }; export default App;
Break gutters only on large devices
Break gutters only on large devices
JavaScript
mit
user01/PresidentialDebates,user01/PresidentialDebates,user01/PresidentialDebates
a57628e33816f3740ccb39dd295310f34583b85d
guides/place-my-order/steps/add-data/list.js
guides/place-my-order/steps/add-data/list.js
import { Component } from 'can'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; const RestaurantList = Component.extend({ tag: 'pmo-restaurant-list', view, ViewModel: { // EXTERNAL STATEFUL PROPERTIES // These properties are passed from another component. Example: // value: {type: "number"} // INTERNAL STATEFUL PROPERTIES // These properties are owned by this component. restaurants: { default() { return Restaurant.getList({}); } }, // DERIVED PROPERTIES // These properties combine other property values. Example: // get valueAndMessage(){ return this.value + this.message; } // METHODS // Functions that can be called by the view. Example: // incrementValue() { this.value++; } // SIDE EFFECTS // The following is a good place to perform changes to the DOM // or do things that don't fit in to one of the areas above. connectedCallback(element){ } } }); export default RestaurantList; export const ViewModel = RestaurantList.ViewModel; import Component from 'can-component'; import DefineMap from 'can-define/map/'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; export const ViewModel = DefineMap.extend({ restaurants: { value() { return Restaurant.getList({}); } } }); export default Component.extend({ tag: 'pmo-restaurant-list', ViewModel, view });
import { Component } from 'can'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; const RestaurantList = Component.extend({ tag: 'pmo-restaurant-list', view, ViewModel: { // EXTERNAL STATEFUL PROPERTIES // These properties are passed from another component. Example: // value: {type: "number"} // INTERNAL STATEFUL PROPERTIES // These properties are owned by this component. restaurants: { default() { return Restaurant.getList({}); } }, // DERIVED PROPERTIES // These properties combine other property values. Example: // get valueAndMessage(){ return this.value + this.message; } // METHODS // Functions that can be called by the view. Example: // incrementValue() { this.value++; } // SIDE EFFECTS // The following is a good place to perform changes to the DOM // or do things that don't fit in to one of the areas above. connectedCallback(element){ } } }); export default RestaurantList; export const ViewModel = RestaurantList.ViewModel;
Remove redundant source from PMO
Remove redundant source from PMO This removes the redundant source that was left over from the DoneJS 2 guide. Fixes #1156
JavaScript
mit
donejs/donejs,donejs/donejs
ffbd3bf025e9f8f72f8b4cb42e9be653ecdb08b3
js/FeaturedExperiences.ios.js
js/FeaturedExperiences.ios.js
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule FeaturedExperiences */ 'use strict'; function setReferrer(newReferrer) { // NOOP. Shouldn't get here. } function getFeatured() { return [ { url: 'exp://exp.host/@exponent/floatyplane', manifest: { name: 'Floaty Plane', desc: 'Touch the plane until you die!', iconUrl: 'https://s3-us-west-2.amazonaws.com/examples-exp/floaty_icon.png', }, }, { url: 'exp://exp.host/@exponent/react-native-for-curious-people', manifest: { name: 'React Native for Curious People', desc: 'Learn about React Native.', iconUrl: 'https://s3.amazonaws.com/rnfcp/icon.png', }, }, { url: 'exp://exp.host/@exponent/pomodoro', manifest: { name: 'Pomodoro', desc: 'Be careful or the tomatoes might explode!', iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, ]; } module.exports = { setReferrer, getFeatured, };
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule FeaturedExperiences */ 'use strict'; function setReferrer(newReferrer) { // NOOP. Shouldn't get here. } function getFeatured() { return [ { url: 'exp://exp.host/@exponent/floatyplane', manifest: { name: 'Floaty Plane', desc: 'Touch the plane until you die!', iconUrl: 'https://s3-us-west-2.amazonaws.com/examples-exp/floaty_icon.png', }, }, { url: 'exp://exp.host/@exponent/react-native-for-curious-people', manifest: { name: 'React Native for Curious People', desc: 'Learn about React Native.', iconUrl: 'https://s3.amazonaws.com/rnfcp/icon.png', }, }, { url: 'exp://exp.host/@exponent/pomodoro', manifest: { name: 'Pomodoro', desc: 'Be careful or the tomatoes might explode!', iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, { url: 'exp://exp.host/@notbrent/native-component-list', manifest: { name: 'Native Component List', desc: 'Demonstration of some native components.', iconUrl: 'https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png', }, }, ]; } module.exports = { setReferrer, getFeatured, };
Add native component list to featured experiences
Add native component list to featured experiences fbshipit-source-id: 7a6210a
JavaScript
bsd-3-clause
jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponentjs/exponent,jolicloud/exponent,exponentjs/exponent,jolicloud/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponent/exponent,jolicloud/exponent,exponentjs/exponent,jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponent/exponent
ae0031e09a40434d24bfa344bf099aa4c8cbaad5
src/components/Board.js
src/components/Board.js
import React, {Component, PropTypes} from 'react' import BoardContainer from './BoardContainer' import {Provider} from 'react-redux' import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' let store = createStore(boardReducer, window && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component { render () { return <Provider store={store}> <BoardContainer {...this.props} /> </Provider> } } Board.propTypes = { data: PropTypes.object.isRequired, onLaneScroll: PropTypes.func, onCardClick: PropTypes.func, eventBusHandle: PropTypes.func, laneSortFunction: PropTypes.func, draggable: PropTypes.bool, handleDragStart: PropTypes.func, handleDragEnd: PropTypes.func, onDataChange: PropTypes.func }
import React, {Component, PropTypes} from 'react' import BoardContainer from './BoardContainer' import {Provider} from 'react-redux' import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' let store = createStore(boardReducer, typeof(window) !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component { render () { return <Provider store={store}> <BoardContainer {...this.props} /> </Provider> } } Board.propTypes = { data: PropTypes.object.isRequired, onLaneScroll: PropTypes.func, onCardClick: PropTypes.func, eventBusHandle: PropTypes.func, laneSortFunction: PropTypes.func, draggable: PropTypes.bool, handleDragStart: PropTypes.func, handleDragEnd: PropTypes.func, onDataChange: PropTypes.func }
Use typeof(window) to check if being used in non browser environments
fix(): Use typeof(window) to check if being used in non browser environments https://github.com/rcdexta/react-trello/issues/15
JavaScript
mit
rcdexta/react-trello,rcdexta/react-trello
01c5311c3027c893ddd76cfbec42d88baece1564
lib/daab-run.js
lib/daab-run.js
#!/usr/bin/env node // daab run var fs = require('fs'); var spawn = require('child_process').spawn; var program = require('commander'); var auth = require('./auth'); program .allowUnknownOption() .parse(process.argv); if (! auth.hasToken()) { console.log('At first, try "daab login"'); process.exit(); } var hubot = spawn('bin/hubot', ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
#!/usr/bin/env node // daab run var fs = require('fs'); var spawn = require('child_process').spawn; var program = require('commander'); var auth = require('./auth'); program .allowUnknownOption() .parse(process.argv); if (! auth.hasToken()) { console.log('At first, try "daab login"'); process.exit(); } var cmd = process.platform === 'win32' ? 'bin\\hubot.cmd' : 'bin/hubot'; var hubot = spawn(cmd, ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
Fix launch command on windows platform.
Fix launch command on windows platform.
JavaScript
mit
lisb/daab,lisb/daab,lisb/daab
cb7ab80f26922a025297d20fe791e8c0b0a01ca7
settings.js
settings.js
//app-specific sentence module.exports = { serverPort : 8080, pingInteralInMilliseconds : 1000*5, // server main loop interval. 6 hours postBeforeTheMatch : true, postAfterTheMatch : true, preMatchWindowInMinutes: "in 5 minutes", // moment.js humanize expression postMatchWindowInHours: "2 hours ago" // moment.js humanize expression };
//app-specific sentence module.exports = { serverPort : 8080, pingInteralInMilliseconds : 1000*60, // server main loop interval. 6 hours postBeforeTheMatch : true, postAfterTheMatch : true, preMatchWindowInMinutes: "in 5 minutes", // moment.js humanize expression postMatchWindowInHours: "2 hours ago" // moment.js humanize expression };
Set default loop interval to 1 minute
Set default loop interval to 1 minute
JavaScript
mit
matijaabicic/Moubot,d48/Moubot,matijaabicic/Moubot,matijaabicic/Moubot,dougmolineux/Moubot
b569d9e348d345f6c6b1135c5fbb49a189e21f42
src/components/Menu.js
src/components/Menu.js
import * as React from 'react' import { Link } from 'gatsby' import { Container } from './Container' import { CloseIcon } from './icons/Close' export const Menu = ({ showMenu, onClick }) => { return ( <div className={`${ showMenu ? 'fixed' : 'hidden' } inset-0 z-40 h-screen bg-black w-full bg-opacity-25`} > <div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0"> <Container className="flex flex-col space-y-4"> <Link to="/articles" className="font-bold text-gray-500 text-normal hover:underline" > Articles </Link> <Link to="/projects" className="font-bold text-gray-500 text-normal hover:underline" > Projects </Link> </Container> </div> <div className="absolute bottom-0 right-0 p-4 m-6 text-white bg-black rounded-full"> <CloseIcon className="w-6 h-6" onClick={() => onClick((prevState) => !prevState)} /> </div> </div> ) }
import * as React from 'react' import { Link } from 'gatsby' import { Container } from './Container' import { CloseIcon } from './icons/Close' export const Menu = ({ showMenu, onClick }) => { return ( <div className={`${ showMenu ? 'fixed' : 'hidden' } inset-0 z-40 h-full bg-black w-full bg-opacity-25`} > <div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0"> <Container className="flex flex-col space-y-4"> <Link to="/articles" className="font-bold text-gray-500 text-normal hover:underline" > Articles </Link> <Link to="/projects" className="font-bold text-gray-500 text-normal hover:underline" > Projects </Link> </Container> </div> <div className="absolute bottom-0 right-0 p-4 m-6 text-white bg-black rounded-full"> <CloseIcon className="w-6 h-6" onClick={() => onClick((prevState) => !prevState)} /> </div> </div> ) }
Fix menu close btn position
Fix menu close btn position
JavaScript
mit
dtjv/dtjv.github.io
210c0478bd061571f62bb0a841400bd24e325acb
lib/check.js
lib/check.js
var check = { isNaN : function(value) { "use strict"; return isNaN(value); }, isZero : function(value) { "use strict"; return value === 0; }, isPositiveZero : function(value) { "use strict"; return value === 0 && 1 / value === Infinity; }, isNegativeZero : function(value) { "use strict"; return value === 0 && 1 / value === -Infinity; }, isFinite : function(value) { "use strict" return !isNaN(value) && value !== Infinity && value !== -Infinity; }, isInfinity : function(value) { "use strict"; return value === Infinity || value === -Infinity; }, isPositiveInfinity : function(value) { "use strict"; return value === Infinity; }, isNegativeInfinity : function(value) { "use strict"; return value === -Infinity; } }; module.exports = check;
var check = { isNaN : isNaN, isZero : function(value) { "use strict"; return value === 0; }, isPositiveZero : function(value) { "use strict"; return value === 0 && 1 / value === Infinity; }, isNegativeZero : function(value) { "use strict"; return value === 0 && 1 / value === -Infinity; }, isFinite : isFinite, isInfinity : function(value) { "use strict"; return value === Infinity || value === -Infinity; }, isPositiveInfinity : function(value) { "use strict"; return value === Infinity; }, isNegativeInfinity : function(value) { "use strict"; return value === -Infinity; } }; module.exports = check;
Make isFinite() and isNaN() direct ref copy of the builtin functions
Make isFinite() and isNaN() direct ref copy of the builtin functions
JavaScript
mit
kchapelier/node-mathp
b4b33ec346e1f6e6fb7f5eea1c9674d33a6d2831
client/hide.js
client/hide.js
/* Hide posts you don't like */ let main = require('./main'); // Remember hidden posts for 7 days only, to perevent the cookie from // eclipsing the Sun let hidden = new main.Memory('hide', 7, true); main.reply('hide', function(model) { // Hiding your own posts would open up the gates for a ton of bugs. Fuck // that. if (model.get('mine')) return; const count = hidden.write(model.get('num')); model.remove(); // Forward number to options menu main.request('hide:render', count); }); main.reply('hide:clear', hidden.purgeAll); // Initial render main.defer(() => main.request('hide:render', hidden.size()));
/* Hide posts you don't like */ let main = require('./main'); // Remember hidden posts for 7 days only, to perevent the cookie from // eclipsing the Sun let hidden = new main.Memory('hide', 7, true); main.reply('hide', function(model) { // Hiding your own posts would open up the gates for a ton of bugs. Fuck // that. if (model.get('mine')) return; const count = hidden.write(model.get('num')); model.remove(); // Forward number to options menu main.request('hide:render', count); }); main.reply('hide:clear', () => hidden.purgeAll()); // Initial render main.defer(() => main.request('hide:render', hidden.size()));
Fix purging hidden post list
Fix purging hidden post list
JavaScript
mit
theGaggle/sleepingpizza,KoinoAoi/meguca,KoinoAoi/meguca,theGaggle/sleepingpizza,reiclone/doushio,reiclone/doushio,reiclone/doushio,theGaggle/sleepingpizza,reiclone/doushio,theGaggle/sleepingpizza,KoinoAoi/meguca,KoinoAoi/meguca,KoinoAoi/meguca,theGaggle/sleepingpizza,theGaggle/sleepingpizza,reiclone/doushio
38733fd891f6d3022a5c0bd7aef98c4ee7ad5b55
packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js
packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js
'use strict'; /** * Deduplicate one addon's children addons recursively from hostAddons. * * @private * @param {Object} hostAddons * @param {EmberAddon} dedupedAddon * @param {String} treeName */ module.exports = function deeplyNonDuplicatedAddon(hostAddons, dedupedAddon, treeName) { if (dedupedAddon.addons.length === 0) { return; } dedupedAddon._orginalAddons = dedupedAddon.addons; dedupedAddon.addons = dedupedAddon.addons.filter(addon => { // nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here if (addon.lazyLoading && addon.lazyLoading.enabled) { return true; } if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName); } let hostAddon = hostAddons[addon.name]; if (hostAddon && hostAddon.cacheKeyForTree) { let innerCacheKey = addon.cacheKeyForTree(treeName); let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName); if ( innerCacheKey != null && innerCacheKey === hostAddonCacheKey ) { // the addon specifies cache key and it is the same as host instance of the addon, skip the tree return false; } } return true; }); }
'use strict'; // Array of addon names that should not be deduped. const ADDONS_TO_EXCLUDE_FROM_DEDUPE = [ 'ember-cli-babel', ]; /** * Deduplicate one addon's children addons recursively from hostAddons. * * @private * @param {Object} hostAddons * @param {EmberAddon} dedupedAddon * @param {String} treeName */ module.exports = function deeplyNonDuplicatedAddon(hostAddons, dedupedAddon, treeName) { if (dedupedAddon.addons.length === 0) { return; } dedupedAddon._orginalAddons = dedupedAddon.addons; dedupedAddon.addons = dedupedAddon.addons.filter(addon => { // nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here if (addon.lazyLoading && addon.lazyLoading.enabled) { return true; } if (ADDONS_TO_EXCLUDE_FROM_DEDUPE.includes(addon.name)) { return true; } if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName); } let hostAddon = hostAddons[addon.name]; if (hostAddon && hostAddon.cacheKeyForTree) { let innerCacheKey = addon.cacheKeyForTree(treeName); let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName); if ( innerCacheKey != null && innerCacheKey === hostAddonCacheKey ) { // the addon specifies cache key and it is the same as host instance of the addon, skip the tree return false; } } return true; }); }
Add exclude list to addon dedupe logic
Add exclude list to addon dedupe logic
JavaScript
mit
ember-engines/ember-engines,ember-engines/ember-engines
5ecc6a9de257eb6872946a01f5929a2bfa94bf79
lib/macgyver.js
lib/macgyver.js
var pristineEnv = require('./pristine-env'); function macgyver(thing) { if (Object.prototype.toString.call(thing) === '[object Array]') { return (new pristineEnv().Array(0)).concat(thing); } else { return thing; } } module.exports = macgyver;
var pristineEnv = require('./pristine-env'); var pristineObject = pristineEnv().Object; var pristineArray = pristineEnv().Array; function macgyver(thing) { if (pristineObject.prototype.toString.call(thing) === '[object Array]') { return (new pristineArray()).concat(thing); } else { return thing; } } module.exports = macgyver;
Use pristine Object to work out if a thing is an array
Use pristine Object to work out if a thing is an array
JavaScript
mit
customcommander/macgyver
8d62ce5afa50ccbe21b516f3cc39d0c7ca20b922
lib/index.js
lib/index.js
require('./db/connection'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const logger = require('koa-logger'); const json = require('koa-json'); const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); const auth = require('./helpers/auth'); (() => { const app = new Koa(); onerror(app); app.use(bodyParser({})) .use(json()) .use(logger()) .use(cors()) router.map(el => app.use(el.routes())); app.listen(3003); })();
require('./db/connection'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const logger = require('koa-logger'); const json = require('koa-json'); const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); (() => { const app = new Koa(); onerror(app); app.use(bodyParser({})) .use(json()) .use(logger()) .use(cors()); router.map(el => app.use(el.routes())); app.listen(process.env.PORT || 3003); })();
ADD - PORT env var
ADD - PORT env var
JavaScript
apache-2.0
fkanout/NotifyDrive-API
30b859c827ed450fbf7a52a18aa92af79c11e5e4
lib/index.js
lib/index.js
'use strict'; var bunyan = require('bunyan'); var config = require('coyno-config'); function createLogger() { var log; if (!!config.log.pretty) { var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); log = bunyan.createLogger({ name: 'queue', streams: [{ level: config.log.level, type: 'raw', stream: prettyStdOut }] }); } else { log = bunyan.createLogger({name: 'queue'}); } return log; } module.exports = createLogger();
'use strict'; var bunyan = require('bunyan'); var config = require('coyno-config'); function createLogger() { var log; if (!!config.log.pretty) { var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); log = bunyan.createLogger({ name: 'queue', streams: [{ level: config.log.level, type: 'raw', stream: prettyStdOut }] }); } else { log = bunyan.createLogger({name: 'queue', level: config.log.level}); } return log; } module.exports = createLogger();
Handle log level correctly for raw logs
Handle log level correctly for raw logs
JavaScript
apache-2.0
blooks/log
fe4d6b89e779c357d6bdc00c46c6c28bc549ecc5
Source/Scene/Pass.js
Source/Scene/Pass.js
/*global define*/ define([ '../Core/freezeObject' ], function( freezeObject) { "use strict"; /** * The render pass for a command. * * @private */ var Pass = { GLOBE : 0, OPAQUE : 1, TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4 }; return freezeObject(Pass); });
/*global define*/ define([ '../Core/freezeObject' ], function( freezeObject) { "use strict"; /** * The render pass for a command. * * @private */ var Pass = { GLOBE : 0, OPAQUE : 1, // Commands are executed in order by pass up to the translucent pass. // Translucent geometry needs special handling (sorting/OIT). Overlays // are also special (they're executed last, they're not sorted by frustum). TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4 }; return freezeObject(Pass); });
Add comment about the order of passes.
Add comment about the order of passes.
JavaScript
apache-2.0
CesiumGS/cesium,AnimatedRNG/cesium,likangning93/cesium,denverpierce/cesium,jason-crow/cesium,ggetz/cesium,kiselev-dv/cesium,esraerik/cesium,esraerik/cesium,emackey/cesium,omh1280/cesium,soceur/cesium,jason-crow/cesium,emackey/cesium,YonatanKra/cesium,YonatanKra/cesium,omh1280/cesium,AnimatedRNG/cesium,kiselev-dv/cesium,hodbauer/cesium,josh-bernstein/cesium,geoscan/cesium,denverpierce/cesium,kiselev-dv/cesium,aelatgt/cesium,NaderCHASER/cesium,CesiumGS/cesium,omh1280/cesium,wallw-bits/cesium,emackey/cesium,ggetz/cesium,hodbauer/cesium,josh-bernstein/cesium,esraerik/cesium,progsung/cesium,kiselev-dv/cesium,denverpierce/cesium,wallw-bits/cesium,likangning93/cesium,AnalyticalGraphicsInc/cesium,soceur/cesium,AnalyticalGraphicsInc/cesium,oterral/cesium,likangning93/cesium,emackey/cesium,CesiumGS/cesium,likangning93/cesium,CesiumGS/cesium,hodbauer/cesium,oterral/cesium,wallw-bits/cesium,aelatgt/cesium,wallw-bits/cesium,CesiumGS/cesium,progsung/cesium,kaktus40/cesium,denverpierce/cesium,omh1280/cesium,ggetz/cesium,YonatanKra/cesium,YonatanKra/cesium,AnimatedRNG/cesium,esraerik/cesium,jasonbeverage/cesium,soceur/cesium,jason-crow/cesium,jasonbeverage/cesium,AnimatedRNG/cesium,kaktus40/cesium,jason-crow/cesium,geoscan/cesium,oterral/cesium,aelatgt/cesium,likangning93/cesium,ggetz/cesium,aelatgt/cesium,NaderCHASER/cesium,NaderCHASER/cesium
f315636aec6965e0fe1394775bc4e97a67ad11aa
CodeWars/js/death-by-coffee.js
CodeWars/js/death-by-coffee.js
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; }
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; } export { coffeeLimits };
Add export to use as module
Add export to use as module
JavaScript
mit
sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems
fcf4357086a308bf9a9164f496c167e02e01ba17
lib/template.js
lib/template.js
const Handlebars = require('handlebars'); Handlebars.registerHelper('removeBreak', (text) => { text = Handlebars.Utils.escapeExpression(text); text = text.replace(/(\r\n|\n|\r)/gm, ' '); return new Handlebars.SafeString(text); }); const Template = class { constructor(templateString, data) { this.template = Handlebars.compile(templateString || ''); this.data = data || {}; } setTemplate(templateString) { this.template = Handlebars.compile(templateString || ''); } parse(callback) { callback(this.template(this.data)); } }; module.exports = Template;
const Handlebars = require('handlebars'); Handlebars.registerHelper('removeBreak', (text) => { text = Handlebars.Utils.escapeExpression(text); text = text.replace(/(\r\n|\n|\r)/gm, ' '); return new Handlebars.SafeString(text); }); const Template = class { constructor(templateString, data) { this.template = Handlebars.compile(templateString || ''); this.data = data || {}; } parse(callback) { callback(this.template(this.data)); } }; module.exports = Template;
Remove class method of Template
Remove class method of Template
JavaScript
mit
t32k/stylestats
ffdfc42c910a9d09d4cddc9c5df46d44d1e10ca8
grunt/contrib-jshint.js
grunt/contrib-jshint.js
// Check JS assets for code quality module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', 'scripts/main.js'], }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
// Check JS assets for code quality module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', 'grunt/*.js', 'scripts/main.js'], }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
Include Grunt partials in jshint task.
Include Grunt partials in jshint task.
JavaScript
mit
yellowled/yl-bp,yellowled/yl-bp
db31f1d00912d3720c8b2af5257d8727347e4d94
lib/redis.js
lib/redis.js
const redis = require('redis') const config = require('config') const url = require('url') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = url.parse(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { console.log('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { console.log('Connected to Redis') const redisAuth = (config.redis.url && redisInfo) ? redisInfo.auth.split(':')[1] : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
const redis = require('redis') const config = require('config') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = new URL(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { logger.info('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { logger.info('Connected to Redis') // Use the password in the URL if provided; otherwise use the one provided by config const redisAuth = (config.redis.url && redisInfo) ? redisInfo.password : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
Replace deprecated url.parse() with WHATWG URL API
Replace deprecated url.parse() with WHATWG URL API
JavaScript
bsd-3-clause
codeforamerica/streetmix,codeforamerica/streetmix,codeforamerica/streetmix
030d0f7d611c4b99819564f984354a659b2fa35a
core/src/main/public/static/js/find/app/page/search/results/state-token-strategy.js
core/src/main/public/static/js/find/app/page/search/results/state-token-strategy.js
/* * Copyright 2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define(['underscore'], function(_) { return { waitForIndexes: _.constant(false), promotions: _.constant(true), requestParams: function(queryModel) { return { text: queryModel.get('queryText'), state_match_ids: queryModel.get('stateMatchIds'), state_dont_match_ids: queryModel.get('stateDontMatchIds'), summary: 'context' }; }, validateQuery: function(queryModel) { return !_.isEmpty(queryModel.get('stateMatchIds')); } }; });
/* * Copyright 2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define(['underscore'], function(_) { return { waitForIndexes: _.constant(false), promotions: _.constant(false), requestParams: function(queryModel) { return { text: queryModel.get('queryText'), state_match_ids: queryModel.get('stateMatchIds'), state_dont_match_ids: queryModel.get('stateDontMatchIds'), summary: 'context' }; }, validateQuery: function(queryModel) { return !_.isEmpty(queryModel.get('stateMatchIds')); } }; });
Stop saved snapshots querying for promotions [rev: jon.soul]
[FIND-57] Stop saved snapshots querying for promotions [rev: jon.soul]
JavaScript
mit
hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/java-powerpoint-report,hpautonomy/find,hpe-idol/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,hpe-idol/find,hpe-idol/java-powerpoint-report,LinkPowerHK/find,hpe-idol/find,LinkPowerHK/find,LinkPowerHK/find,hpautonomy/find
5c0a550bc9c68f0281bd1b61e93985cbaed962c0
src/lib/render-image.js
src/lib/render-image.js
// Utility for rendering html images to files 'use strict'; const webshot = require('webshot'); const Jimp = require('jimp'); const fs = require(`fs`); const webshotOptions = { windowSize: { width: 1024, height: 768 } , shotSize: { width: 1024, height: 'all' } , phantomPath: 'phantomjs' , siteType: 'html' , streamType: 'png' , renderDelay: 0 }; function renderImageFromHtml(html, outputPath) { return new Promise((resolve, reject) => { const tempFile = `${outputPath}.tmp.png`; webshot(html, tempFile, webshotOptions, (err) => { if (err) { console.error(`WEBSHOT ERROR: ${err}`); reject(err); return; } Jimp.read(tempFile) .then(image => image.autocrop().write(outputPath)) .then(() => { setTimeout(() => resolve(outputPath), 50); }) .then(() => fs.unlink(tempFile, (err) => { if (err) { console.error(err); reject(err); } })) .catch(err => { console.error('\n *** Failed to create trimmed png:'); console.error(err.stack); reject(err); }); }); }); } module.exports = { fromHtml: renderImageFromHtml };
// Utility for rendering html images to files 'use strict'; const webshot = require('webshot'); const Jimp = require('jimp'); const fs = require(`fs`); const webshotOptions = { windowSize: { width: 1024, height: 768 } , shotSize: { width: 1024, height: 'all' } , phantomPath: 'phantomjs' , siteType: 'html' , streamType: 'png' , renderDelay: 0 }; function renderImageFromHtml(html, outputPath) { return new Promise((resolve, reject) => { const tempFile = `${outputPath}.tmp.png`; webshot(html, tempFile, webshotOptions, (err) => { if (err) { console.error(`WEBSHOT ERROR: ${err}`); reject(err); return; } Jimp.read(tempFile) .then(image => image.autocrop().write(outputPath)) .then(() => { setTimeout(() => resolve(outputPath), 1000); }) .then(() => fs.unlink(tempFile, (err) => { if (err) { console.error(err); reject(err); } })) .catch(err => { console.error('\n *** Failed to create trimmed png:'); console.error(err.stack); reject(err); }); }); }); } module.exports = { fromHtml: renderImageFromHtml };
Increase delay before considering file written
Increase delay before considering file written
JavaScript
mit
GoodGamery/mtgnewsbot,GoodGamery/mtgnewsbot
8e279cc54dcc083bf49940a572b0574881bbeea8
www/lib/collections/photos.js
www/lib/collections/photos.js
Photo = function (doc) { _.extend(this, doc); }; _.extend(Photo.prototype, { getImgTag: function (dimension) { return { 'class': 'lazy', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), 'data-src-retina': _.str.sprintf( '%s/photos/%s@2x/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), alt: this.title, width: dimension, height: dimension }; } }); Photos = new Mongo.Collection('Photos', { transform: function (doc) { return new Photo(doc); } });
Photo = function (doc) { _.extend(this, doc); }; _.extend(Photo.prototype, { getImgTag: function (dimension) { return { 'class': 'lazy', src: 'data:image/gif;base64,' + 'R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), 'data-src-retina': _.str.sprintf( '%s/photos/%s@2x/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), alt: this.title, width: dimension, height: dimension }; } }); Photos = new Mongo.Collection('Photos', { transform: function (doc) { return new Photo(doc); } });
Use a placeholder png to hold the image size
Use a placeholder png to hold the image size
JavaScript
mit
nburka/black-white
54306bafd423daff49272d4605bf84ae7a7471c8
js/metronome.js
js/metronome.js
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); } }
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); counter.innerHTML = ""; } }
Clear counter when Metronome is stopped
Clear counter when Metronome is stopped
JavaScript
mit
dmilburn/beatrice,dmilburn/beatrice
dba8dc2f41ffdf023bbfb8dbf92826c6c799a0b0
js/nbpreview.js
js/nbpreview.js
(function () { var root = this; var $file_input = document.querySelector("input#file"); var $holder = document.querySelector("#notebook-holder"); var render_notebook = function (ipynb) { var notebook = root.notebook = nb.parse(ipynb); while ($holder.hasChildNodes()) { $holder.removeChild($holder.lastChild); } $holder.appendChild(notebook.render()); Prism.highlightAll(); }; $file_input.onchange = function (e) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; reader.readAsText(this.files[0]); }; }).call(this);
(function () { var root = this; var $file_input = document.querySelector("input#file"); var $holder = document.querySelector("#notebook-holder"); var render_notebook = function (ipynb) { var notebook = root.notebook = nb.parse(ipynb); while ($holder.hasChildNodes()) { $holder.removeChild($holder.lastChild); } $holder.appendChild(notebook.render()); Prism.highlightAll(); }; var load_file = function (file) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; reader.readAsText(file); }; $file_input.onchange = function (e) { load_file(this.files[0]); }; window.addEventListener('dragover', function (e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a root.document.body.style.opacity = 0.5; }, false); window.addEventListener('dragleave', function (e) { root.document.body.style.opacity = 1; }, false); window.addEventListener('drop', function (e) { e.stopPropagation(); e.preventDefault(); load_file(e.dataTransfer.files[0]); $file_input.style.display = "none"; root.document.body.style.opacity = 1; }, false); }).call(this);
Add support for dropping files into window.
Add support for dropping files into window.
JavaScript
mit
jsvine/nbpreview,jsvine/nbpreview
c3f9e5eff4b8b7e7de0e4a6f7da1faad077b23ee
templates/system/modules/ph7cms-donation/themes/base/js/donationbox.js
templates/system/modules/ph7cms-donation/themes/base/js/donationbox.js
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', maxWidth: '450px', maxHeight: '85%', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', width: '200px', height: '155px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
Change size of donation popup
Change size of donation popup
JavaScript
mit
pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS
7044032b4ace71eda06a99a5389edf0289179602
src/list.js
src/list.js
import { debuglog } from 'util'; import AbstractCache from './abstract'; export default class ListCache extends AbstractCache { constructor() { super(); this._log = debuglog('cache'); this._date = null; this.touch(); } touch() { this._date = Date.now(); return this; } get(key, callback) { this._log('ListCache get %s', key); this._client.get(key, (error, value) => { if (error) { callback(error); return; } if (!value) { callback(); return; } if (value.date < this._date) { this._client.del(key, () => callback()); return; } callback(null, value.data); }); } set(key, data, callback) { this._log('ListCache set %s', key); const value = { data, date: Date.now() }; this._client.set(key, value, (error) => { if (error) { callback(error); return; } callback(null, data); }); } del(key, callback) { this._log('ListCache del %s', key); this._client.del(key, callback); } }
import { debuglog } from 'util'; import AbstractCache from './abstract'; export default class ListCache extends AbstractCache { constructor() { super(); this._log = debuglog('cache'); this._date = Date.now(); } date(value = null) { if (value === null) { return this._date; } this._log('ListCache date %s', value); this._date = value; return this; } get(key, callback) { this._log('ListCache get %s', key); this._client.get(key, (error, value) => { if (error) { callback(error); return; } if (!value) { callback(); return; } if (value.date < this._date) { this._client.del(key, () => callback()); return; } callback(null, value.data); }); } set(key, data, callback) { this._log('ListCache set %s', key); const value = { data, date: Date.now() }; this._client.set(key, value, (error) => { if (error) { callback(error); return; } callback(null, data); }); } del(key, callback) { this._log('ListCache del %s', key); this._client.del(key, callback); } }
Replace touch with date get/setter
Replace touch with date get/setter
JavaScript
mit
scola84/node-api-cache
d4660759d672c90a23fe0944082cff0083d691a0
src/main.js
src/main.js
import Vue from 'vue'; import VueResource from 'vue-resource'; import VueRouter from 'vue-router'; import App from './App.vue'; import About from './components/About.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters' Vue.use(VueResource); Vue.use(VueRouter); components(Vue); filters(Vue); export const router = new VueRouter({ routes: routes, base: __dirname }); new Vue({ router, store, el: '#app', components: { App } });
import Vue from 'vue'; import VueResource from 'vue-resource'; import VueRouter from 'vue-router'; import App from './App.vue'; import About from './components/About.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters' Vue.use(VueResource); Vue.use(VueRouter); components(Vue); filters(Vue); export const router = new VueRouter({ mode: 'history', routes: routes, base: __dirname }); new Vue({ router, store, el: '#app', components: { App } });
Switch router to history mode
Switch router to history mode
JavaScript
mit
dmurtari/mbu-frontend,dmurtari/mbu-frontend
a1694721011727b4570e21d444e6b23835d42a1c
src/main.js
src/main.js
'use strict'; var resourcify = angular.module('resourcify', []); function resourcificator ($http, $q) { var $resourcifyError = angular.$$minErr('resourcify'), requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'], requestMethods = { 'query': 'GET', 'get': 'GET', '$get': 'GET', '$save': 'POST', '$update': 'PUT', '$delete': 'DELETE' }, validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; function validMethod (method) { if (!~validMethods.indexOf(method)) { throw $resourcifyError('requesttype', '"@{0}" is not a valid request method.', method); } return method; } function replaceParams (params, url) { } } resourcificator.$inject = ['$http', '$q']; resourcify.service('resourcify', resourcificator);
'use strict'; var resourcify = angular.module('resourcify', []); function resourcificator ($http, $q) { var $resourcifyError = angular.$$minErr('resourcify'), requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'], requestMethods = { 'query': 'GET', 'get': 'GET', '$get': 'GET', '$save': 'POST', '$update': 'PUT', '$delete': 'DELETE' }, bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; // Finds and replaces query params and path params function replaceParams (params, url) { var findParam = /[\/=](:\w*[a-zA-Z]\w*)/g, copiedPath = angular.copy(url); } } resourcificator.$inject = ['$http', '$q']; resourcify.service('resourcify', resourcificator);
Add regex for finding path params
Add regex for finding path params
JavaScript
mit
erikdonohoo/resourcify,erikdonohoo/resourcify
b3827c12d2092ec93813470ec0b9a81d4d554d08
lib/client/satisfactionratings.js
lib/client/satisfactionratings.js
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all };
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all }; // ====================================== Posting SatisfactionRatings SatisfactionRatings.prototype.create = function (ticketID, satisfactionRating, cb) { this.request('POST', ['tickets', ticketId, 'satisfaction_rating'], satisfactionRating, cb); };
Add support for creating Satisfaction Ratings
Add support for creating Satisfaction Ratings As documented at https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating
JavaScript
mit
blakmatrix/node-zendesk,blakmatrix/node-zendesk
30100c0d4d320abbe3004f795b7121d3dfebdaf5
logger.js
logger.js
const chalk = require('chalk'); LOG_TYPES = { NONE: 0, ERROR: 1, NORMAL: 2, DEBUG: 3 }; let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { if (!(type in Object.values(LOG_TYPES))) return; logType = type; }; const logTime = () => { let nowDate = new Date(); return nowDate.toLocaleDateString() + ' ' + nowDate.toLocaleTimeString([], { hour12: false }); }; const log = (...args) => { if (logType < LOG_TYPES.NORMAL) return; console.log(logTime(), chalk.bold.green('[INFO]'), ...args); }; const error = (...args) => { if (logType < LOG_TYPES.ERROR) return; console.log(logTime(), chalk.bold.red('[ERROR]'), ...args); }; const debug = (...args) => { if (logType < LOG_TYPES.DEBUG) return; console.log(logTime(), chalk.bold.blue('[DEBUG]'), ...args); }; module.exports = { LOG_TYPES, setLogType, log, error, debug }
const chalk = require('chalk'); LOG_TYPES = { NONE: 0, ERROR: 1, NORMAL: 2, DEBUG: 3 }; let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { if (typeof type !== 'number') return; logType = type; }; const logTime = () => { let nowDate = new Date(); return nowDate.toLocaleDateString() + ' ' + nowDate.toLocaleTimeString([], { hour12: false }); }; const log = (...args) => { if (logType < LOG_TYPES.NORMAL) return; console.log(logTime(), chalk.bold.green('[INFO]'), ...args); }; const error = (...args) => { if (logType < LOG_TYPES.ERROR) return; console.log(logTime(), chalk.bold.red('[ERROR]'), ...args); }; const debug = (...args) => { if (logType < LOG_TYPES.DEBUG) return; console.log(logTime(), chalk.bold.blue('[DEBUG]'), ...args); }; module.exports = { LOG_TYPES, setLogType, log, error, debug }
Fix nodejs v6 'TypeError: Object.values is not a function'
Fix nodejs v6 'TypeError: Object.values is not a function'
JavaScript
mit
illuspas/Node-Media-Server,illuspas/Node-Media-Server
789eb9cc78ecaf8e7e04dc8ca1dc8ac7b48f86de
src/node.js
src/node.js
import fs from 'fs'; import { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export const renderToStream = function(element) { return pdf(element).toBuffer(); }; export const renderToFile = function(element, filePath, callback) { const output = renderToStream(element); const stream = fs.createWriteStream(filePath); output.pipe(stream); return new Promise((resolve, reject) => { stream.on('finish', () => { if (callback) callback(output, filePath); resolve(output); }); stream.on('error', reject); }); }; export const render = renderToFile; export { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export default { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, renderToStream, renderToFile, render, };
import fs from 'fs'; import { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export const renderToStream = function(element) { return pdf(element).toBuffer(); }; export const renderToFile = function(element, filePath, callback) { const output = renderToStream(element); const stream = fs.createWriteStream(filePath); output.pipe(stream); return new Promise((resolve, reject) => { stream.on('finish', () => { if (callback) callback(output, filePath); resolve(output); }); stream.on('error', reject); }); }; const throwEnvironmentError = name => { throw new Error( `${name} is a web specific API. Or you're either using this component on Node, or your bundler is not loading react-pdf from the appropiate web build.`, ); }; export const PDFViewer = () => { throwEnvironmentError('PDFViewer'); }; export const PDFDownloadLink = () => { throwEnvironmentError('PDFDownloadLink'); }; export const BlobProvider = () => { throwEnvironmentError('BlobProvider'); }; export const render = renderToFile; export { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export default { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, renderToStream, renderToFile, render, };
Throw error when trying to use web specific APIs on Node
Throw error when trying to use web specific APIs on Node
JavaScript
mit
diegomura/react-pdf,diegomura/react-pdf
caf9ce480560406d0354cf20a93323e2e08ca7c1
src/app/rules/references.service.js
src/app/rules/references.service.js
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(query, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var bindings = []; angular.forEach(query.bindings, function(binding) { if ('id' in binding) { bindings.push(binding.id); } }); var info = { rule: query.rule, query: query.query, bindings: bindings, constraints: query.constraints }; var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(info, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
Reduce amount of information in reference links
Reduce amount of information in reference links
JavaScript
apache-2.0
Wikidata/SQID,Wikidata/WikidataClassBrowser,Wikidata/WikidataClassBrowser,Wikidata/SQID,Wikidata/SQID,Wikidata/WikidataClassBrowser,Wikidata/SQID,Wikidata/SQID,Wikidata/SQID,Wikidata/SQID
af9403793eefb5b3ee0217b077cb41a480251667
test/helpers.js
test/helpers.js
const Bluebird = require('bluebird'); const mongoose = require('mongoose'); const Alternative = require('../app/models/alternative'); const Election = require('../app/models/election'); const Vote = require('../app/models/vote'); const User = require('../app/models/user'); exports.dropDatabase = () => mongoose.connection.dropDatabase().then(() => mongoose.disconnect()); exports.clearCollections = () => Bluebird.map([Alternative, Election, Vote, User], collection => collection.remove() ); const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password' const testUser = (exports.testUser = { username: 'testuser', cardKey: '99TESTCARDKEY', hash }); const adminUser = (exports.adminUser = { username: 'admin', admin: true, cardKey: '55TESTCARDKEY', hash }); exports.createUsers = () => User.create([testUser, adminUser]);
const Bluebird = require('bluebird'); const mongoose = require('mongoose'); const Alternative = require('../app/models/alternative'); const Election = require('../app/models/election'); const Vote = require('../app/models/vote'); const User = require('../app/models/user'); exports.dropDatabase = () => mongoose.connection.dropDatabase().then(() => mongoose.disconnect()); exports.clearCollections = () => Bluebird.map([Alternative, Election, Vote, User], collection => collection.remove() ); const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password' const testUser = (exports.testUser = { username: 'testuser', cardKey: '99TESTCARDKEY', hash }); const adminUser = (exports.adminUser = { username: 'admin', admin: true, moderator: true, cardKey: '55TESTCARDKEY', hash }); exports.createUsers = () => User.create([testUser, adminUser]);
Make new code pass all new tests
Make new code pass all new tests This was done by setting the moderator flag in the helper function that creates admin users.
JavaScript
mit
webkom/vote,webkom/vote,webkom/vote,webkom/vote
35ba2674051ab6201382af6dda76e1531e8ef612
test/es5.js
test/es5.js
import test from 'tape-catch'; var Symbol = require('es6-symbol'); var { curry, _ } = require('../module/index')({ Symbol }); test('The API is in good shape.', (is) => { is.equal( typeof curry, 'function', '`curry_` is a function' ); is.end(); }); test('basic usage', (is) => { const sum = (a, b, c) => a + b + c; is.equal( sum::curry()(1, 2, 3), 6, 'curries a function' ); is.equal( sum::curry(1)(2, 3), 6, 'curries a function' ); is.equal( sum::curry(1, 2)(3), 6, 'curries a function' ); is.equal( sum::curry(1)(2)(3), 6, 'curries a function' ); is.end(); }); test('placeholders', (is) => { const strJoin = (a, b, c) => '' + a + b + c; is.equal( strJoin::curry()(1, 2, 3), '123', 'curries a function' ); is.equal( strJoin::curry(1, _, 3)(2), '123', 'curries a function' ); is.equal( strJoin::curry(_, _, 3)(1)(2), '123', 'curries a function' ); is.equal( strJoin::curry(_, 2)(1)(3), '123', 'curries a function' ); is.end(); });
Add ES5 test by @stoeffel
Add ES5 test by @stoeffel
JavaScript
mit
thisables/curry,togusafish/stoeffel-_-curry-this,stoeffel/curry-this
9fd8b1cd47f6c9f03879427abf471f3d9be49738
tools/tests/cordova-platforms.js
tools/tests/cordova-platforms.js
var selftest = require('../selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../files.js'); // Add plugins to an app. Change the contents of the plugins and their // dependencies, make sure that the app still refreshes. selftest.define("add cordova platforms", function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); s.set("METEOR_TEST_TMP", files.mkdtemp()); run = s.run("run", "android"); run.matchErr("platform is not added"); run.matchErr("meteor add-platform android"); run.expectExit(1); run = s.run("add-platform", "android"); run.match("Do you agree"); run.write("Y\n"); run.extraTime = 90; // Huge download run.match("added"); run = s.run("remove-platform", "foo"); run.match("foo is not"); run = s.run("remove-platform", "android"); run.match("removed"); run = s.run("run", "android"); run.matchErr("platform is not added"); run.matchErr("meteor add-platform android"); run.expectExit(1); });
var selftest = require('../selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../files.js'); // Add plugins to an app. Change the contents of the plugins and their // dependencies, make sure that the app still refreshes. selftest.define("add cordova platforms", function () { var s = new Sandbox(); var run; // Starting a run s.createApp("myapp", "package-tests"); s.cd("myapp"); s.set("METEOR_TEST_TMP", files.mkdtemp()); run = s.run("run", "android"); run.matchErr("Platform is not added"); run.match("meteor add-platform android"); run.expectExit(1); run = s.run("add-platform", "android"); run.match("Do you agree"); run.write("Y\n"); run.extraTime = 90; // Huge download run.match("added"); run = s.run("remove-platform", "foo"); run.match("foo is not"); run = s.run("remove-platform", "android"); run.match("removed"); run = s.run("run", "android"); run.matchErr("Platform is not added"); run.match("meteor add-platform android"); run.expectExit(1); });
Update 'add cordova platforms' to match latest command output
Update 'add cordova platforms' to match latest command output
JavaScript
mit
benstoltz/meteor,dandv/meteor,allanalexandre/meteor,brdtrpp/meteor,neotim/meteor,tdamsma/meteor,newswim/meteor,PatrickMcGuinness/meteor,4commerce-technologies-AG/meteor,DCKT/meteor,fashionsun/meteor,DAB0mB/meteor,emmerge/meteor,dfischer/meteor,ljack/meteor,servel333/meteor,lpinto93/meteor,deanius/meteor,benjamn/meteor,brettle/meteor,eluck/meteor,dboyliao/meteor,whip112/meteor,framewr/meteor,pandeysoni/meteor,planet-training/meteor,stevenliuit/meteor,lassombra/meteor,mauricionr/meteor,alphanso/meteor,jenalgit/meteor,jdivy/meteor,AnthonyAstige/meteor,shadedprofit/meteor,msavin/meteor,henrypan/meteor,kidaa/meteor,mubassirhayat/meteor,lpinto93/meteor,benjamn/meteor,shadedprofit/meteor,HugoRLopes/meteor,rozzzly/meteor,alexbeletsky/meteor,ljack/meteor,kencheung/meteor,vjau/meteor,planet-training/meteor,kencheung/meteor,PatrickMcGuinness/meteor,TechplexEngineer/meteor,sitexa/meteor,devgrok/meteor,whip112/meteor,johnthepink/meteor,IveWong/meteor,colinligertwood/meteor,calvintychan/meteor,chasertech/meteor,DAB0mB/meteor,akintoey/meteor,AnjirHossain/meteor,johnthepink/meteor,qscripter/meteor,Hansoft/meteor,sdeveloper/meteor,jeblister/meteor,brettle/meteor,katopz/meteor,shmiko/meteor,pandeysoni/meteor,zdd910/meteor,dfischer/meteor,emmerge/meteor,EduShareOntario/meteor,yinhe007/meteor,qscripter/meteor,jirengu/meteor,udhayam/meteor,whip112/meteor,GrimDerp/meteor,aldeed/meteor,youprofit/meteor,yinhe007/meteor,lorensr/meteor,tdamsma/meteor,yinhe007/meteor,cbonami/meteor,meteor-velocity/meteor,nuvipannu/meteor,katopz/meteor,codingang/meteor,williambr/meteor,hristaki/meteor,ndarilek/meteor,arunoda/meteor,saisai/meteor,Hansoft/meteor,elkingtonmcb/meteor,HugoRLopes/meteor,whip112/meteor,kengchau/meteor,mjmasn/meteor,DAB0mB/meteor,IveWong/meteor,ndarilek/meteor,daslicht/meteor,AnthonyAstige/meteor,jeblister/meteor,zdd910/meteor,michielvanoeffelen/meteor,dev-bobsong/meteor,dev-bobsong/meteor,wmkcc/meteor,chengxiaole/meteor,lawrenceAIO/meteor,yyx990803/meteor,jirengu/meteor,jdivy/meteor,henrypan/meteor,papimomi/meteor,ndarilek/meteor,Hansoft/meteor,LWHTarena/meteor,h200863057/meteor,jenalgit/meteor,meteor-velocity/meteor,yonas/meteor-freebsd,chasertech/meteor,Puena/meteor,neotim/meteor,mauricionr/meteor,yalexx/meteor,deanius/meteor,williambr/meteor,4commerce-technologies-AG/meteor,chmac/meteor,saisai/meteor,lieuwex/meteor,lpinto93/meteor,yonglehou/meteor,ashwathgovind/meteor,juansgaitan/meteor,servel333/meteor,HugoRLopes/meteor,DCKT/meteor,skarekrow/meteor,queso/meteor,yyx990803/meteor,D1no/meteor,jirengu/meteor,chasertech/meteor,D1no/meteor,modulexcite/meteor,lassombra/meteor,AlexR1712/meteor,dboyliao/meteor,TribeMedia/meteor,shrop/meteor,JesseQin/meteor,jdivy/meteor,mauricionr/meteor,juansgaitan/meteor,devgrok/meteor,meteor-velocity/meteor,aldeed/meteor,EduShareOntario/meteor,Urigo/meteor,kidaa/meteor,dandv/meteor,cherbst/meteor,yinhe007/meteor,yonglehou/meteor,papimomi/meteor,kencheung/meteor,cbonami/meteor,codingang/meteor,meteor-velocity/meteor,sclausen/meteor,saisai/meteor,daslicht/meteor,yonglehou/meteor,mjmasn/meteor,meonkeys/meteor,yiliaofan/meteor,skarekrow/meteor,yinhe007/meteor,devgrok/meteor,aramk/meteor,skarekrow/meteor,jeblister/meteor,EduShareOntario/meteor,alexbeletsky/meteor,dfischer/meteor,yiliaofan/meteor,Prithvi-A/meteor,aldeed/meteor,colinligertwood/meteor,luohuazju/meteor,sdeveloper/meteor,sitexa/meteor,chengxiaole/meteor,lpinto93/meteor,dboyliao/meteor,oceanzou123/meteor,jenalgit/meteor,Theviajerock/meteor,alexbeletsky/meteor,Prithvi-A/meteor,udhayam/meteor,wmkcc/meteor,somallg/meteor,aldeed/meteor,youprofit/meteor,imanmafi/meteor,pandeysoni/meteor,saisai/meteor,chinasb/meteor,JesseQin/meteor,Jonekee/meteor,michielvanoeffelen/meteor,tdamsma/meteor,allanalexandre/meteor,planet-training/meteor,yanisIk/meteor,benstoltz/meteor,kengchau/meteor,iman-mafi/meteor,cherbst/meteor,TribeMedia/meteor,Hansoft/meteor,kidaa/meteor,jagi/meteor,HugoRLopes/meteor,yalexx/meteor,dfischer/meteor,newswim/meteor,somallg/meteor,chiefninew/meteor,GrimDerp/meteor,dandv/meteor,sdeveloper/meteor,chinasb/meteor,Profab/meteor,wmkcc/meteor,Quicksteve/meteor,iman-mafi/meteor,SeanOceanHu/meteor,namho102/meteor,chmac/meteor,pjump/meteor,yalexx/meteor,Eynaliyev/meteor,servel333/meteor,framewr/meteor,namho102/meteor,guazipi/meteor,benjamn/meteor,fashionsun/meteor,deanius/meteor,lassombra/meteor,dev-bobsong/meteor,calvintychan/meteor,wmkcc/meteor,Jonekee/meteor,daltonrenaldo/meteor,whip112/meteor,daltonrenaldo/meteor,HugoRLopes/meteor,daslicht/meteor,brdtrpp/meteor,Jonekee/meteor,cog-64/meteor,jeblister/meteor,henrypan/meteor,zdd910/meteor,steedos/meteor,brdtrpp/meteor,namho102/meteor,cog-64/meteor,cog-64/meteor,juansgaitan/meteor,hristaki/meteor,mjmasn/meteor,yonglehou/meteor,jg3526/meteor,SeanOceanHu/meteor,sitexa/meteor,Profab/meteor,Prithvi-A/meteor,chengxiaole/meteor,Eynaliyev/meteor,framewr/meteor,deanius/meteor,aramk/meteor,rabbyalone/meteor,rozzzly/meteor,sdeveloper/meteor,sunny-g/meteor,colinligertwood/meteor,GrimDerp/meteor,evilemon/meteor,daltonrenaldo/meteor,modulexcite/meteor,ndarilek/meteor,Eynaliyev/meteor,joannekoong/meteor,ashwathgovind/meteor,Urigo/meteor,AnjirHossain/meteor,aleclarson/meteor,EduShareOntario/meteor,akintoey/meteor,juansgaitan/meteor,dev-bobsong/meteor,chiefninew/meteor,meonkeys/meteor,lawrenceAIO/meteor,vacjaliu/meteor,vjau/meteor,vacjaliu/meteor,dev-bobsong/meteor,elkingtonmcb/meteor,lieuwex/meteor,JesseQin/meteor,lieuwex/meteor,PatrickMcGuinness/meteor,planet-training/meteor,jrudio/meteor,ericterpstra/meteor,sitexa/meteor,daslicht/meteor,ashwathgovind/meteor,AnthonyAstige/meteor,Hansoft/meteor,h200863057/meteor,AlexR1712/meteor,aramk/meteor,mjmasn/meteor,evilemon/meteor,planet-training/meteor,jrudio/meteor,cherbst/meteor,jg3526/meteor,chengxiaole/meteor,codedogfish/meteor,judsonbsilva/meteor,esteedqueen/meteor,vjau/meteor,sclausen/meteor,Theviajerock/meteor,kengchau/meteor,newswim/meteor,mubassirhayat/meteor,Prithvi-A/meteor,elkingtonmcb/meteor,sdeveloper/meteor,SeanOceanHu/meteor,cherbst/meteor,williambr/meteor,DCKT/meteor,nuvipannu/meteor,TribeMedia/meteor,Paulyoufu/meteor-1,kidaa/meteor,DCKT/meteor,LWHTarena/meteor,cbonami/meteor,jenalgit/meteor,ericterpstra/meteor,steedos/meteor,zdd910/meteor,Paulyoufu/meteor-1,Jeremy017/meteor,dfischer/meteor,servel333/meteor,bhargav175/meteor,brettle/meteor,deanius/meteor,steedos/meteor,Eynaliyev/meteor,tdamsma/meteor,baysao/meteor,deanius/meteor,framewr/meteor,Urigo/meteor,namho102/meteor,lassombra/meteor,l0rd0fwar/meteor,mirstan/meteor,paul-barry-kenzan/meteor,ashwathgovind/meteor,HugoRLopes/meteor,benjamn/meteor,Urigo/meteor,Jonekee/meteor,chasertech/meteor,yyx990803/meteor,JesseQin/meteor,paul-barry-kenzan/meteor,dandv/meteor,pjump/meteor,Hansoft/meteor,brettle/meteor,codedogfish/meteor,TribeMedia/meteor,kidaa/meteor,pandeysoni/meteor,aleclarson/meteor,TechplexEngineer/meteor,chmac/meteor,HugoRLopes/meteor,yiliaofan/meteor,udhayam/meteor,modulexcite/meteor,baiyunping333/meteor,Jeremy017/meteor,Ken-Liu/meteor,luohuazju/meteor,jg3526/meteor,jdivy/meteor,codedogfish/meteor,dev-bobsong/meteor,arunoda/meteor,namho102/meteor,lorensr/meteor,kencheung/meteor,ljack/meteor,AlexR1712/meteor,yyx990803/meteor,alphanso/meteor,neotim/meteor,skarekrow/meteor,baysao/meteor,oceanzou123/meteor,fashionsun/meteor,msavin/meteor,chinasb/meteor,baysao/meteor,yiliaofan/meteor,DCKT/meteor,neotim/meteor,lieuwex/meteor,jdivy/meteor,hristaki/meteor,daslicht/meteor,aldeed/meteor,vacjaliu/meteor,chiefninew/meteor,brdtrpp/meteor,IveWong/meteor,yonas/meteor-freebsd,mubassirhayat/meteor,Puena/meteor,lorensr/meteor,lieuwex/meteor,alphanso/meteor,alexbeletsky/meteor,Jeremy017/meteor,papimomi/meteor,jeblister/meteor,daltonrenaldo/meteor,mubassirhayat/meteor,aramk/meteor,shadedprofit/meteor,PatrickMcGuinness/meteor,jeblister/meteor,Quicksteve/meteor,ndarilek/meteor,elkingtonmcb/meteor,emmerge/meteor,youprofit/meteor,evilemon/meteor,sitexa/meteor,kengchau/meteor,SeanOceanHu/meteor,daltonrenaldo/meteor,chinasb/meteor,yanisIk/meteor,neotim/meteor,shrop/meteor,chinasb/meteor,codedogfish/meteor,mauricionr/meteor,iman-mafi/meteor,colinligertwood/meteor,skarekrow/meteor,jdivy/meteor,l0rd0fwar/meteor,h200863057/meteor,mubassirhayat/meteor,bhargav175/meteor,framewr/meteor,planet-training/meteor,yonglehou/meteor,servel333/meteor,Urigo/meteor,justintung/meteor,zdd910/meteor,chinasb/meteor,henrypan/meteor,queso/meteor,oceanzou123/meteor,yanisIk/meteor,lawrenceAIO/meteor,hristaki/meteor,mubassirhayat/meteor,allanalexandre/meteor,pjump/meteor,calvintychan/meteor,aldeed/meteor,dboyliao/meteor,mubassirhayat/meteor,kengchau/meteor,esteedqueen/meteor,joannekoong/meteor,D1no/meteor,Quicksteve/meteor,yanisIk/meteor,queso/meteor,lawrenceAIO/meteor,iman-mafi/meteor,Eynaliyev/meteor,mauricionr/meteor,jagi/meteor,jirengu/meteor,mirstan/meteor,TechplexEngineer/meteor,elkingtonmcb/meteor,TechplexEngineer/meteor,cog-64/meteor,arunoda/meteor,shmiko/meteor,codingang/meteor,JesseQin/meteor,calvintychan/meteor,allanalexandre/meteor,baiyunping333/meteor,skarekrow/meteor,namho102/meteor,ndarilek/meteor,zdd910/meteor,AnthonyAstige/meteor,yiliaofan/meteor,rabbyalone/meteor,yalexx/meteor,tdamsma/meteor,dandv/meteor,meonkeys/meteor,bhargav175/meteor,cog-64/meteor,arunoda/meteor,shmiko/meteor,Profab/meteor,karlito40/meteor,jenalgit/meteor,codingang/meteor,judsonbsilva/meteor,joannekoong/meteor,AnthonyAstige/meteor,Theviajerock/meteor,saisai/meteor,calvintychan/meteor,AnjirHossain/meteor,alphanso/meteor,dandv/meteor,Paulyoufu/meteor-1,lawrenceAIO/meteor,arunoda/meteor,williambr/meteor,henrypan/meteor,modulexcite/meteor,msavin/meteor,rabbyalone/meteor,benjamn/meteor,Prithvi-A/meteor,guazipi/meteor,GrimDerp/meteor,cherbst/meteor,chiefninew/meteor,vjau/meteor,guazipi/meteor,TechplexEngineer/meteor,ericterpstra/meteor,lorensr/meteor,wmkcc/meteor,chengxiaole/meteor,lassombra/meteor,sitexa/meteor,chinasb/meteor,shmiko/meteor,guazipi/meteor,meonkeys/meteor,h200863057/meteor,chasertech/meteor,pjump/meteor,dboyliao/meteor,jg3526/meteor,meteor-velocity/meteor,katopz/meteor,Jonekee/meteor,IveWong/meteor,bhargav175/meteor,iman-mafi/meteor,pandeysoni/meteor,benstoltz/meteor,Profab/meteor,AnjirHossain/meteor,fashionsun/meteor,karlito40/meteor,HugoRLopes/meteor,aramk/meteor,devgrok/meteor,SeanOceanHu/meteor,tdamsma/meteor,ljack/meteor,johnthepink/meteor,katopz/meteor,williambr/meteor,Urigo/meteor,bhargav175/meteor,Eynaliyev/meteor,papimomi/meteor,shrop/meteor,alphanso/meteor,h200863057/meteor,allanalexandre/meteor,udhayam/meteor,Jeremy017/meteor,oceanzou123/meteor,joannekoong/meteor,tdamsma/meteor,jrudio/meteor,evilemon/meteor,sclausen/meteor,Paulyoufu/meteor-1,eluck/meteor,stevenliuit/meteor,esteedqueen/meteor,msavin/meteor,justintung/meteor,D1no/meteor,arunoda/meteor,LWHTarena/meteor,justintung/meteor,codingang/meteor,justintung/meteor,imanmafi/meteor,devgrok/meteor,IveWong/meteor,alexbeletsky/meteor,meteor-velocity/meteor,somallg/meteor,4commerce-technologies-AG/meteor,sunny-g/meteor,paul-barry-kenzan/meteor,D1no/meteor,somallg/meteor,yonas/meteor-freebsd,queso/meteor,elkingtonmcb/meteor,lorensr/meteor,henrypan/meteor,michielvanoeffelen/meteor,williambr/meteor,daslicht/meteor,Quicksteve/meteor,esteedqueen/meteor,SeanOceanHu/meteor,benjamn/meteor,bhargav175/meteor,shadedprofit/meteor,karlito40/meteor,jagi/meteor,yanisIk/meteor,Profab/meteor,GrimDerp/meteor,baiyunping333/meteor,chasertech/meteor,youprofit/meteor,Ken-Liu/meteor,chiefninew/meteor,iman-mafi/meteor,Profab/meteor,ljack/meteor,yonas/meteor-freebsd,ljack/meteor,guazipi/meteor,IveWong/meteor,hristaki/meteor,baysao/meteor,yonas/meteor-freebsd,AlexR1712/meteor,elkingtonmcb/meteor,daltonrenaldo/meteor,queso/meteor,chengxiaole/meteor,stevenliuit/meteor,Theviajerock/meteor,paul-barry-kenzan/meteor,vacjaliu/meteor,yyx990803/meteor,planet-training/meteor,judsonbsilva/meteor,eluck/meteor,sitexa/meteor,yonglehou/meteor,emmerge/meteor,l0rd0fwar/meteor,jg3526/meteor,JesseQin/meteor,benstoltz/meteor,nuvipannu/meteor,guazipi/meteor,baiyunping333/meteor,papimomi/meteor,qscripter/meteor,rabbyalone/meteor,oceanzou123/meteor,lawrenceAIO/meteor,Paulyoufu/meteor-1,eluck/meteor,udhayam/meteor,akintoey/meteor,cbonami/meteor,codedogfish/meteor,paul-barry-kenzan/meteor,newswim/meteor,judsonbsilva/meteor,brdtrpp/meteor,AnjirHossain/meteor,somallg/meteor,codedogfish/meteor,IveWong/meteor,saisai/meteor,eluck/meteor,jenalgit/meteor,Quicksteve/meteor,benstoltz/meteor,newswim/meteor,neotim/meteor,4commerce-technologies-AG/meteor,justintung/meteor,benstoltz/meteor,Quicksteve/meteor,eluck/meteor,Ken-Liu/meteor,benstoltz/meteor,steedos/meteor,yyx990803/meteor,Paulyoufu/meteor-1,colinligertwood/meteor,arunoda/meteor,framewr/meteor,AlexR1712/meteor,zdd910/meteor,judsonbsilva/meteor,ericterpstra/meteor,lawrenceAIO/meteor,l0rd0fwar/meteor,sunny-g/meteor,cbonami/meteor,codedogfish/meteor,hristaki/meteor,steedos/meteor,meonkeys/meteor,modulexcite/meteor,dandv/meteor,vjau/meteor,karlito40/meteor,imanmafi/meteor,ashwathgovind/meteor,AnthonyAstige/meteor,lpinto93/meteor,sunny-g/meteor,judsonbsilva/meteor,Quicksteve/meteor,esteedqueen/meteor,benjamn/meteor,sclausen/meteor,steedos/meteor,devgrok/meteor,sunny-g/meteor,fashionsun/meteor,chmac/meteor,Eynaliyev/meteor,kengchau/meteor,yanisIk/meteor,Profab/meteor,sunny-g/meteor,TribeMedia/meteor,cog-64/meteor,jenalgit/meteor,sclausen/meteor,imanmafi/meteor,skarekrow/meteor,baysao/meteor,dboyliao/meteor,Puena/meteor,katopz/meteor,aleclarson/meteor,juansgaitan/meteor,TechplexEngineer/meteor,michielvanoeffelen/meteor,sclausen/meteor,DCKT/meteor,shrop/meteor,allanalexandre/meteor,alexbeletsky/meteor,4commerce-technologies-AG/meteor,PatrickMcGuinness/meteor,somallg/meteor,D1no/meteor,alexbeletsky/meteor,Puena/meteor,LWHTarena/meteor,msavin/meteor,Jeremy017/meteor,GrimDerp/meteor,queso/meteor,oceanzou123/meteor,vacjaliu/meteor,justintung/meteor,karlito40/meteor,Jeremy017/meteor,youprofit/meteor,tdamsma/meteor,brdtrpp/meteor,D1no/meteor,cbonami/meteor,papimomi/meteor,rozzzly/meteor,JesseQin/meteor,baysao/meteor,chiefninew/meteor,lieuwex/meteor,yonglehou/meteor,emmerge/meteor,namho102/meteor,brdtrpp/meteor,jagi/meteor,michielvanoeffelen/meteor,aramk/meteor,Jonekee/meteor,Puena/meteor,DAB0mB/meteor,papimomi/meteor,chmac/meteor,chiefninew/meteor,EduShareOntario/meteor,emmerge/meteor,Ken-Liu/meteor,baiyunping333/meteor,mirstan/meteor,jagi/meteor,michielvanoeffelen/meteor,guazipi/meteor,baysao/meteor,jirengu/meteor,Ken-Liu/meteor,DAB0mB/meteor,lorensr/meteor,stevenliuit/meteor,luohuazju/meteor,vjau/meteor,ndarilek/meteor,mirstan/meteor,justintung/meteor,mirstan/meteor,qscripter/meteor,jagi/meteor,rozzzly/meteor,Jeremy017/meteor,pandeysoni/meteor,codingang/meteor,whip112/meteor,evilemon/meteor,mauricionr/meteor,williambr/meteor,shrop/meteor,fashionsun/meteor,brettle/meteor,karlito40/meteor,emmerge/meteor,kencheung/meteor,colinligertwood/meteor,shrop/meteor,pjump/meteor,daslicht/meteor,mubassirhayat/meteor,msavin/meteor,eluck/meteor,EduShareOntario/meteor,pjump/meteor,Prithvi-A/meteor,framewr/meteor,dboyliao/meteor,Hansoft/meteor,allanalexandre/meteor,joannekoong/meteor,juansgaitan/meteor,luohuazju/meteor,aldeed/meteor,udhayam/meteor,katopz/meteor,sclausen/meteor,calvintychan/meteor,nuvipannu/meteor,vacjaliu/meteor,chasertech/meteor,chmac/meteor,4commerce-technologies-AG/meteor,shadedprofit/meteor,eluck/meteor,neotim/meteor,johnthepink/meteor,sunny-g/meteor,cbonami/meteor,akintoey/meteor,luohuazju/meteor,yonas/meteor-freebsd,dfischer/meteor,l0rd0fwar/meteor,Prithvi-A/meteor,kencheung/meteor,cherbst/meteor,iman-mafi/meteor,AnjirHossain/meteor,Urigo/meteor,shmiko/meteor,vjau/meteor,TribeMedia/meteor,ljack/meteor,dev-bobsong/meteor,modulexcite/meteor,Puena/meteor,karlito40/meteor,johnthepink/meteor,stevenliuit/meteor,saisai/meteor,meteor-velocity/meteor,steedos/meteor,mirstan/meteor,aramk/meteor,vacjaliu/meteor,EduShareOntario/meteor,brdtrpp/meteor,esteedqueen/meteor,youprofit/meteor,AnthonyAstige/meteor,paul-barry-kenzan/meteor,calvintychan/meteor,wmkcc/meteor,imanmafi/meteor,jg3526/meteor,evilemon/meteor,chengxiaole/meteor,ashwathgovind/meteor,yalexx/meteor,mjmasn/meteor,somallg/meteor,chmac/meteor,LWHTarena/meteor,bhargav175/meteor,LWHTarena/meteor,lassombra/meteor,ericterpstra/meteor,kidaa/meteor,rabbyalone/meteor,evilemon/meteor,AlexR1712/meteor,planet-training/meteor,lorensr/meteor,qscripter/meteor,johnthepink/meteor,luohuazju/meteor,cog-64/meteor,servel333/meteor,DAB0mB/meteor,shrop/meteor,msavin/meteor,devgrok/meteor,Theviajerock/meteor,DAB0mB/meteor,dfischer/meteor,sunny-g/meteor,qscripter/meteor,akintoey/meteor,h200863057/meteor,luohuazju/meteor,imanmafi/meteor,michielvanoeffelen/meteor,judsonbsilva/meteor,shmiko/meteor,Puena/meteor,ericterpstra/meteor,AnjirHossain/meteor,ashwathgovind/meteor,yanisIk/meteor,nuvipannu/meteor,mjmasn/meteor,rozzzly/meteor,lieuwex/meteor,meonkeys/meteor,yalexx/meteor,whip112/meteor,chiefninew/meteor,shadedprofit/meteor,ndarilek/meteor,oceanzou123/meteor,jirengu/meteor,deanius/meteor,l0rd0fwar/meteor,akintoey/meteor,fashionsun/meteor,Theviajerock/meteor,johnthepink/meteor,joannekoong/meteor,AnthonyAstige/meteor,daltonrenaldo/meteor,yiliaofan/meteor,newswim/meteor,esteedqueen/meteor,baiyunping333/meteor,lassombra/meteor,yiliaofan/meteor,brettle/meteor,jirengu/meteor,DCKT/meteor,henrypan/meteor,ericterpstra/meteor,lpinto93/meteor,rabbyalone/meteor,alexbeletsky/meteor,jrudio/meteor,wmkcc/meteor,cherbst/meteor,queso/meteor,karlito40/meteor,mirstan/meteor,meonkeys/meteor,jdivy/meteor,LWHTarena/meteor,qscripter/meteor,jg3526/meteor,codingang/meteor,paul-barry-kenzan/meteor,rozzzly/meteor,rabbyalone/meteor,imanmafi/meteor,katopz/meteor,nuvipannu/meteor,kengchau/meteor,udhayam/meteor,dboyliao/meteor,TribeMedia/meteor,SeanOceanHu/meteor,brettle/meteor,newswim/meteor,GrimDerp/meteor,kencheung/meteor,PatrickMcGuinness/meteor,Ken-Liu/meteor,D1no/meteor,nuvipannu/meteor,stevenliuit/meteor,allanalexandre/meteor,joannekoong/meteor,jrudio/meteor,jrudio/meteor,servel333/meteor,daltonrenaldo/meteor,kidaa/meteor,shmiko/meteor,Ken-Liu/meteor,modulexcite/meteor,AlexR1712/meteor,stevenliuit/meteor,yalexx/meteor,lpinto93/meteor,youprofit/meteor,yinhe007/meteor,shadedprofit/meteor,alphanso/meteor,hristaki/meteor,akintoey/meteor,yanisIk/meteor,somallg/meteor,yonas/meteor-freebsd,l0rd0fwar/meteor,Jonekee/meteor,TechplexEngineer/meteor,pandeysoni/meteor,baiyunping333/meteor,yyx990803/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,sdeveloper/meteor,SeanOceanHu/meteor,pjump/meteor,rozzzly/meteor,yinhe007/meteor,Paulyoufu/meteor-1,jeblister/meteor,juansgaitan/meteor,h200863057/meteor,Theviajerock/meteor,mauricionr/meteor,jagi/meteor,ljack/meteor,colinligertwood/meteor,Eynaliyev/meteor,servel333/meteor,PatrickMcGuinness/meteor,alphanso/meteor,sdeveloper/meteor
1657a56ec025e6670d72c20f1cf87f80ab9c7de6
lib/throttle.js
lib/throttle.js
'use strict'; module.exports = (api) => { api.metasync.throttle = ( // Function throttling timeout, // time interval fn, // function to be executed once per timeout args // arguments array for fn (optional) ) => { let timer = null; let wait = false; return function throttled() { if (!timer) { timer = setTimeout(() => { timer = null; if (wait) throttled(); }, timeout); if (args) fn(...args); else fn(); wait = false; } else { wait = true; } }; }; api.metasync.debounce = ( timeout, fn, args = [] ) => { let timer; return () => { clearTimeout(timer); timer = setTimeout(() => fn(...args), timeout); }; }; api.metasync.timeout = ( // Set timeout for function execution timeout, // time interval asyncFunction, // async function to be executed // done - callback function done // callback function on done ) => { let finished = false; done = api.metasync.cb(done); const timer = setTimeout(() => { if (!finished) { finished = true; done(); } }, timeout); asyncFunction(() => { if (!finished) { clearTimeout(timer); finished = true; done(); } }); }; };
'use strict'; module.exports = (api) => { api.metasync.throttle = ( // Function throttling timeout, // time interval fn, // function to be executed once per timeout args // arguments array for fn (optional) ) => { let timer = null; let wait = false; return function throttled() { if (!timer) { timer = setTimeout(() => { timer = null; if (wait) throttled(); }, timeout); if (args) fn(...args); else fn(); wait = false; } else { wait = true; } }; }; api.metasync.debounce = ( timeout, fn, args = [] ) => { let timer; return () => { clearTimeout(timer); timer = setTimeout(() => fn(...args), timeout); }; }; api.metasync.timeout = ( // Set timeout for function execution timeout, // time interval asyncFunction, // async function to be executed // done - callback function done // callback function on done ) => { let finished = false; done = api.metasync.cb(done); const timer = setTimeout(() => { if (!finished) { finished = true; done(null); } }, timeout); asyncFunction((err, data) => { if (!finished) { clearTimeout(timer); finished = true; done(err, data); } }); }; };
Add null as error argument for callback
Add null as error argument for callback Refs: #13 PR-URL: https://github.com/metarhia/metasync/pull/152 Reviewed-By: Timur Shemsedinov <6dc7cb6a9fcface2186172df883b5c9ab417ae33@gmail.com>
JavaScript
mit
metarhia/MetaSync,DzyubSpirit/MetaSync,DzyubSpirit/MetaSync
204918caff2feeff82f10300364edd43b8e1f4ea
lib/versions.js
lib/versions.js
var semver = require('semver'); var versions = module.exports; /** Returns a number representation of the version number that can be compared with other such representations e.g. compareable('0.6.12') > compareable('0.6.10') */ versions.compareable = function compareable(ver) { var parts = ver.split('.'); return parseInt(parts.map(function(d){ while(d.length < 3) d = '0'+d; return d; }).join(''), 10); } /* Returns the matching version number in a list of sorted version numbers */ versions.find = function(version_spec, list, cb) { var v, i = list.length-1; if(version_spec.match(/^stable$/i)) { if(i >= 0) do { v = list[i--] }while(v && parseInt(v.split('.')[1]) % 2 != 0 && i >= 0);// search for an even number: e.g. 0.2.0 }else if(version_spec.match(/^latest$/i)) { v = list[list.length-1]; }else{ if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0); if(!semver.satisfies(v, version_spec)) v = null; } if(!v) return cb(new Error('Version spec didn\'t match any available version')); cb(null, v); };
var semver = require('semver'); var versions = module.exports; /** Returns a number representation of the version number that can be compared with other such representations e.g. compareable('0.6.12') > compareable('0.6.10') */ versions.compareable = function compareable(ver) { var parts = ver.split('.'); return parseInt(parts.map(function(d){ while(d.length < 3) d = '0'+d; return d; }).join(''), 10); } /* Returns the matching version number in a list of sorted version numbers */ versions.find = function(version_spec, list, cb) { var v, i = list.length-1; if(version_spec.match(/^stable$/i)) { if(i >= 0) do { v = list[i--] }while(v && parseInt(v.split('.')[1]) % 2 != 0 && i >= 0);// search for an even number: e.g. 0.2.0 }else if(version_spec.match(/^latest$/i)) { v = list[list.length-1]; }else{ if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0); if(!semver.satisfies(v, version_spec)) v = null; } if(!v) return cb(new Error('Version spec, "' + version_spec + '", didn\'t match any available version')); cb(null, v); };
Write out version spec that's being used, to make version errors more intuitive.
Write out version spec that's being used, to make version errors more intuitive.
JavaScript
mit
marcelklehr/nodist,marcelklehr/nodist,marcelklehr/nodist,nullivex/nodist,nullivex/nodist,nullivex/nodist
b933f6e2ba5915d248a954c4c322b91d452d5182
lib/errors/mfarequirederror.js
lib/errors/mfarequirederror.js
/** * Module dependencies. */ var TokenError = require('./tokenerror'); /** * `TokenError` error. * * @api public */ function MFARequiredError(message, uri, user) { TokenError.call(this, message, 'mfa_required', uri); Error.captureStackTrace(this, arguments.callee); this.name = 'MFARequiredError'; this.user = user; } /** * Inherit from `TokenError`. */ MFARequiredError.prototype.__proto__ = TokenError.prototype; /** * Expose `MFARequiredError`. */ module.exports = MFARequiredError;
/** * Module dependencies. */ var TokenError = require('./tokenerror'); /** * `TokenError` error. * * @api public */ function MFARequiredError(message, uri, user, areq) { TokenError.call(this, message, 'mfa_required', uri); Error.captureStackTrace(this, arguments.callee); this.name = 'MFARequiredError'; this.user = user; this.req = areq; } /** * Inherit from `TokenError`. */ MFARequiredError.prototype.__proto__ = TokenError.prototype; /** * Expose `MFARequiredError`. */ module.exports = MFARequiredError;
Add request to MFA error for keeping session context.
Add request to MFA error for keeping session context.
JavaScript
mit
jaredhanson/oauth2orize-2fa
adaa54ca513706ad15f858d318dd02895b3a6445
src/register-element.js
src/register-element.js
import * as privateMethods from './elements/private-methods.js'; const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback']; export default function registerElement(tagName, Constructor) { // The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created // would be the same as the one registered with the system. So delete it and replace it with the one generated by // `document.registerElement`. delete window[Constructor.name]; const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor); // Delete any custom element callbacks since native elements don't have them and we don't want that kind of // observable difference. Their presence only matters at registration time anyway. for (const callback of callbacks) { delete GeneratedConstructor[callback]; } // Register the appropriate private methods under the generated constructor name, since when they are looked up at // runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6 // lands. const privateMethodsForConstructor = privateMethods.getAll(Constructor.name); if (privateMethodsForConstructor) { const registerElementGeneratedName = GeneratedConstructor.name; privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor); } }
import * as privateMethods from './elements/private-methods.js'; const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback']; export default function registerElement(tagName, Constructor) { // The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created // would be the same as the one registered with the system. So delete it and replace it with the one generated by // `document.registerElement`. delete window[Constructor.name]; const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor); // Delete any custom element callbacks since native elements don't have them and we don't want that kind of // observable difference. Their presence only matters at registration time anyway. for (const callback of callbacks) { delete GeneratedConstructor.prototype[callback]; } // Register the appropriate private methods under the generated constructor name, since when they are looked up at // runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6 // lands. const privateMethodsForConstructor = privateMethods.getAll(Constructor.name); if (privateMethodsForConstructor) { const registerElementGeneratedName = GeneratedConstructor.name; privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor); } }
Fix logic for removing the custom element callbacks
Fix logic for removing the custom element callbacks
JavaScript
apache-2.0
domenic/html-as-custom-elements,domenic/html-as-custom-elements,zenorocha/html-as-custom-elements,valmzetvn/html-as-custom-elements,valmzetvn/html-as-custom-elements,valmzetvn/html-as-custom-elements,domenic/html-as-custom-elements,zenorocha/html-as-custom-elements
6e08a454f936d58fc5fc1720e7a74d94b3bc9c9e
demo/simple.js
demo/simple.js
'use strict'; var sandboxFactory = require('..'), MemoryFS = require('memory-fs'), memoryFS = new MemoryFS(), sandbox = sandboxFactory.create(memoryFS); memoryFS.mkdirpSync('/my/dir'); memoryFS.writeFileSync( '/my/dir/file1.js', 'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");' ); memoryFS.writeFileSync( '/my/dir/index.js', 'console.log("Index");' ); memoryFS.writeFileSync( '/my/dir/file2.js', 'console.log("File2");' ); sandbox.execute('require("/my/dir/file1");');
'use strict'; var sandboxFactory = require('..'), mockFS = require('mock-fs').fs(), sandbox = sandboxFactory.create(mockFS); mockFS.mkdirSync('/my'); mockFS.mkdirSync('/my/dir'); mockFS.writeFileSync( '/my/dir/file1.js', 'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");' ); mockFS.writeFileSync( '/my/dir/index.js', 'console.log("Index");' ); mockFS.writeFileSync( '/my/dir/file2.js', 'console.log("File2");' ); sandbox.execute('require("/my/dir/file1");');
Switch demo to use mock-fs rather than memory-fs
Switch demo to use mock-fs rather than memory-fs
JavaScript
mit
asmblah/playpit
f9069b0f601cfa508da172be105f1d0be35acd4c
js/views/ViewManager.js
js/views/ViewManager.js
import HomeView from './HomeView'; import JoinView from './JoinView'; export default class ViewManager { constructor(target) { this.target = target; this.home = new HomeView(); this.join = new JoinView(); this.load('home'); } load(viewName) { this[viewName].init().then(view => { // First remove all Childs while(this.target.firstChild) { this.target.removeChild(this.target.firstChild); } // Then load the view into it view.show(this.target); }); } }
import HomeView from './HomeView'; import JoinView from './JoinView'; export default class ViewManager { constructor(target) { this.target = target; // Register all known views this.home = new HomeView(); this.join = new JoinView(); // Define default view this.DEFAULT_VIEW = 'home'; // Init URL bar and history this.init(); } init() { if(location.hash == '') location.hash = '/'; // Load the view given in the URL this.load(location.hash.substr(2), true); // Check history back and forward to load the correct view window.addEventListener('popstate', event => { this.load(location.hash.substr(2), true); }); } load(viewName = '', nohistory = false) { // Check if view exists if(!this[viewName || this.DEFAULT_VIEW]) viewName = 'notfound'; // Init the new view (load template etc.) this[viewName || this.DEFAULT_VIEW].init().then(view => { // Push the new view to the URL and the history if(!nohistory) history.pushState(null, viewName || this.DEFAULT_VIEW, `#/${viewName}`); // Remove the old view while(this.target.firstChild) { this.target.removeChild(this.target.firstChild); } // Load the view view.show(this.target); }); } }
Add URL support with history.pushState
Add URL support with history.pushState
JavaScript
mit
richterdennis/CastleCrush,richterdennis/CastleCrush
e0fcee4687d0d97fefcef72bc828fcfb0a197da1
src/validations/html.js
src/validations/html.js
var Promise = require('es6-promise').Promise; var lodash = require('lodash'); var validateWithHtmllint = require('./html/htmllint.js'); var validateWithSlowparse = require('./html/slowparse.js'); function filterErrors(errors) { var indexedErrors = lodash(errors).indexBy('reason'); var suppressedTypes = indexedErrors. values(). map('suppresses'). flatten(). value(); return indexedErrors.omit(suppressedTypes).values().value(); } module.exports = function(source) { return Promise.all([ validateWithSlowparse(source), validateWithHtmllint(source), ]).then(function(results) { var filteredErrors = filterErrors(lodash.flatten(results)); return lodash.sortBy(filteredErrors, 'row'); }); };
var Promise = require('es6-promise').Promise; var lodash = require('lodash'); var validateWithHtmllint = require('./html/htmllint.js'); var validateWithSlowparse = require('./html/slowparse.js'); function filterErrors(errors) { var groupedErrors = lodash(errors).groupBy('reason'); var suppressedTypes = groupedErrors. values(). flatten(). map('suppresses'). flatten(). value(); return groupedErrors.omit(suppressedTypes).values().flatten().value(); } module.exports = function(source) { return Promise.all([ validateWithSlowparse(source), validateWithHtmllint(source), ]).then(function(results) { var filteredErrors = filterErrors(lodash.flatten(results)); return lodash.sortBy(filteredErrors, 'row'); }); };
Allow the same error on different lines
Allow the same error on different lines
JavaScript
mit
jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,popcodeorg/popcode,outoftime/learnpad,outoftime/learnpad,popcodeorg/popcode,popcodeorg/popcode,popcodeorg/popcode
87f7091e84b9cad0589160584f85d979b21df4e8
lib/rules_inline/backticks.js
lib/rules_inline/backticks.js
// Parse backticks 'use strict'; module.exports = function backtick(state, silent) { var start, max, marker, matchStart, matchEnd, token, pos = state.pos, ch = state.src.charCodeAt(pos); if (ch !== 0x60/* ` */) { return false; } start = pos; pos++; max = state.posMax; while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; } marker = state.src.slice(start, pos); matchStart = matchEnd = pos; while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { matchEnd = matchStart + 1; while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; } if (matchEnd - matchStart === marker.length) { if (!silent) { token = state.push('code_inline', 'code', 0); token.markup = marker; token.content = state.src.slice(pos, matchStart) .replace(/\n/g, ' ') .replace(/^ (.+) $/, '$1'); } state.pos = matchEnd; return true; } } if (!silent) { state.pending += marker; } state.pos += marker.length; return true; };
// Parse backticks 'use strict'; module.exports = function backtick(state, silent) { var start, max, marker, matchStart, matchEnd, token, pos = state.pos, ch = state.src.charCodeAt(pos); if (ch !== 0x60/* ` */) { return false; } start = pos; pos++; max = state.posMax; while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; } marker = state.src.slice(start, pos); matchStart = matchEnd = pos; while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { matchEnd = matchStart + 1; while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; } if (matchEnd - matchStart === marker.length) { if (!silent) { token = state.push('code_inline', 'code', 0); token.markup = marker; token.content = state.src.slice(pos, matchStart) .replace(/\n/g, ' ') .replace(/^ (.+) $/, '$1'); token.position = start; token.size = (matchStart + 1) - token.position; } state.pos = matchEnd; return true; } } if (!silent) { state.pending += marker; } state.pos += marker.length; return true; };
Add position and size to code_inline
Add position and size to code_inline
JavaScript
mit
GerHobbelt/markdown-it,GerHobbelt/markdown-it
9b6c06ddb62f358a73e3d243c9533c068a5b0bda
app/assets/javascripts/directives/validation/reset_validation_status.js
app/assets/javascripts/directives/validation/reset_validation_status.js
ManageIQ.angular.app.directive('resetValidationStatus', ['$rootScope', function($rootScope) { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { scope.$watch(attrs.ngModel, function() { adjustValidationStatus(ctrl.$modelValue, scope, ctrl, attrs, $rootScope); }); ctrl.$parsers.push(function(value) { adjustValidationStatus(value, scope, ctrl, attrs, $rootScope); return value; }); } } }]); var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) { if(scope.checkAuthentication === true && angular.isDefined(scope.postValidationModel)) { var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]); delete modelPostValidationObject[ctrl.$name]; var modelObject = angular.copy(scope[scope.model]); if(angular.isDefined(modelObject[ctrl.$name])) { delete modelObject[ctrl.$name]; } if (value == scope.postValidationModel[attrs.prefix][ctrl.$name] && _.isMatch(modelObject, modelPostValidationObject)) { scope[scope.model][attrs.resetValidationStatus] = true; rootScope.$broadcast('clearErrorOnTab', {tab: attrs.prefix}); } else { scope[scope.model][attrs.resetValidationStatus] = false; rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix}); } } };
ManageIQ.angular.app.directive('resetValidationStatus', ['$rootScope', function($rootScope) { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { scope.$watch(attrs.ngModel, function() { adjustValidationStatus(ctrl.$modelValue, scope, ctrl, attrs, $rootScope); }); ctrl.$parsers.push(function(value) { adjustValidationStatus(value, scope, ctrl, attrs, $rootScope); return value; }); } } }]); var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) { if(scope.checkAuthentication === true && angular.isDefined(scope.postValidationModel) && angular.isDefined(scope.postValidationModel[attrs.prefix])) { var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]); delete modelPostValidationObject[ctrl.$name]; var modelObject = angular.copy(scope[scope.model]); if(angular.isDefined(modelObject[ctrl.$name])) { delete modelObject[ctrl.$name]; } if (value == scope.postValidationModel[attrs.prefix][ctrl.$name] && _.isMatch(modelObject, modelPostValidationObject)) { scope[scope.model][attrs.resetValidationStatus] = true; rootScope.$broadcast('clearErrorOnTab', {tab: attrs.prefix}); } else { scope[scope.model][attrs.resetValidationStatus] = false; rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix}); } } };
Check if postValidationModel is defined for the tab in question
Check if postValidationModel is defined for the tab in question
JavaScript
apache-2.0
fbladilo/manageiq,agrare/manageiq,durandom/manageiq,mkanoor/manageiq,borod108/manageiq,matobet/manageiq,NickLaMuro/manageiq,josejulio/manageiq,aufi/manageiq,maas-ufcg/manageiq,maas-ufcg/manageiq,d-m-u/manageiq,tinaafitz/manageiq,matobet/manageiq,mzazrivec/manageiq,kbrock/manageiq,ilackarms/manageiq,jvlcek/manageiq,romaintb/manageiq,ManageIQ/manageiq,romaintb/manageiq,billfitzgerald0120/manageiq,mkanoor/manageiq,gmcculloug/manageiq,romanblanco/manageiq,jameswnl/manageiq,djberg96/manageiq,NickLaMuro/manageiq,pkomanek/manageiq,jntullo/manageiq,d-m-u/manageiq,israel-hdez/manageiq,fbladilo/manageiq,josejulio/manageiq,tinaafitz/manageiq,israel-hdez/manageiq,skateman/manageiq,lpichler/manageiq,mresti/manageiq,gmcculloug/manageiq,mzazrivec/manageiq,chessbyte/manageiq,KevinLoiseau/manageiq,juliancheal/manageiq,mzazrivec/manageiq,KevinLoiseau/manageiq,kbrock/manageiq,skateman/manageiq,jvlcek/manageiq,romanblanco/manageiq,fbladilo/manageiq,maas-ufcg/manageiq,gerikis/manageiq,durandom/manageiq,matobet/manageiq,jntullo/manageiq,pkomanek/manageiq,romaintb/manageiq,branic/manageiq,branic/manageiq,d-m-u/manageiq,jrafanie/manageiq,branic/manageiq,ailisp/manageiq,romaintb/manageiq,ManageIQ/manageiq,jameswnl/manageiq,mfeifer/manageiq,juliancheal/manageiq,djberg96/manageiq,ailisp/manageiq,jameswnl/manageiq,gerikis/manageiq,syncrou/manageiq,lpichler/manageiq,jrafanie/manageiq,hstastna/manageiq,KevinLoiseau/manageiq,matobet/manageiq,tinaafitz/manageiq,romanblanco/manageiq,kbrock/manageiq,romaintb/manageiq,syncrou/manageiq,mresti/manageiq,mfeifer/manageiq,gmcculloug/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,mfeifer/manageiq,NaNi-Z/manageiq,syncrou/manageiq,gmcculloug/manageiq,mzazrivec/manageiq,KevinLoiseau/manageiq,josejulio/manageiq,kbrock/manageiq,juliancheal/manageiq,agrare/manageiq,ailisp/manageiq,mresti/manageiq,mfeifer/manageiq,josejulio/manageiq,skateman/manageiq,tzumainn/manageiq,djberg96/manageiq,andyvesel/manageiq,mresti/manageiq,ManageIQ/manageiq,andyvesel/manageiq,mkanoor/manageiq,d-m-u/manageiq,maas-ufcg/manageiq,yaacov/manageiq,tinaafitz/manageiq,lpichler/manageiq,romanblanco/manageiq,aufi/manageiq,jrafanie/manageiq,gerikis/manageiq,gerikis/manageiq,jntullo/manageiq,pkomanek/manageiq,maas-ufcg/manageiq,skateman/manageiq,ilackarms/manageiq,maas-ufcg/manageiq,djberg96/manageiq,hstastna/manageiq,mkanoor/manageiq,borod108/manageiq,NaNi-Z/manageiq,NaNi-Z/manageiq,borod108/manageiq,billfitzgerald0120/manageiq,tzumainn/manageiq,tzumainn/manageiq,chessbyte/manageiq,hstastna/manageiq,romaintb/manageiq,borod108/manageiq,branic/manageiq,ilackarms/manageiq,jameswnl/manageiq,NickLaMuro/manageiq,syncrou/manageiq,andyvesel/manageiq,NaNi-Z/manageiq,hstastna/manageiq,juliancheal/manageiq,KevinLoiseau/manageiq,durandom/manageiq,fbladilo/manageiq,NickLaMuro/manageiq,aufi/manageiq,agrare/manageiq,ailisp/manageiq,tzumainn/manageiq,durandom/manageiq,jvlcek/manageiq,aufi/manageiq,israel-hdez/manageiq,ilackarms/manageiq,yaacov/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,agrare/manageiq,jntullo/manageiq,andyvesel/manageiq,chessbyte/manageiq,jvlcek/manageiq,ManageIQ/manageiq,pkomanek/manageiq,israel-hdez/manageiq,lpichler/manageiq,KevinLoiseau/manageiq,chessbyte/manageiq,jrafanie/manageiq
93f2591b913d31cf6521812f1fed6969efe0401e
app/routes/course-materials.js
app/routes/course-materials.js
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; const { Route, RSVP } = Ember; const { Promise, all, map } = RSVP; export default Route.extend(AuthenticatedRouteMixin, { afterModel(course){ return all([ this.loadCourseLearhingMaterials(course), this.loadSessionLearhingMaterials(course), ]) }, loadCourseLearhingMaterials(course){ return new Promise(resolve => { course.get('learningMaterials').then(courseLearningMaterials => { all(courseLearningMaterials.getEach('learningMaterial')).then(()=> { resolve(); }) }); }); }, loadSessionLearhingMaterials(course){ return new Promise(resolve => { course.get('sessions').then(sessions => { map(sessions.toArray(), session => { return all([ session.get('learningMaterials'), session.get('firstOfferingDate') ]); }).then(()=>{ resolve(); }) }); }); } });
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; const { Route, RSVP } = Ember; const { Promise, all, map } = RSVP; export default Route.extend(AuthenticatedRouteMixin, { afterModel(course){ return all([ this.loadCourseLearningMaterials(course), this.loadSessionLearningMaterials(course), ]) }, loadCourseLearningMaterials(course){ return new Promise(resolve => { course.get('learningMaterials').then(courseLearningMaterials => { all(courseLearningMaterials.getEach('learningMaterial')).then(()=> { resolve(); }) }); }); }, loadSessionLearningMaterials(course){ return new Promise(resolve => { course.get('sessions').then(sessions => { map(sessions.toArray(), session => { return all([ session.get('learningMaterials'), session.get('firstOfferingDate') ]); }).then(()=>{ resolve(); }) }); }); } });
Fix typo/miss spell in method names
Fix typo/miss spell in method names
JavaScript
mit
gboushey/frontend,ilios/frontend,jrjohnson/frontend,stopfstedt/frontend,dartajax/frontend,jrjohnson/frontend,dartajax/frontend,stopfstedt/frontend,ilios/frontend,djvoa12/frontend,gabycampagna/frontend,thecoolestguy/frontend,thecoolestguy/frontend,gboushey/frontend,djvoa12/frontend,gabycampagna/frontend
9a5eede1ae59e712eb17aec182af1468fd409a15
render.js
render.js
gRenderer = { frame: 0, render: function() { this.context.fillStyle = '#000'; this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height); switch (gScene.scene) { case 'title': gScene.renderTitle(); break; case 'hangar': case 'game': gScene.renderBack(); if (gPlayer.life > 0) gPlayer.render(); gScene.renderFore(); gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this)); if (gScene.inTransition) gScene.renderTransition(); break; case 'levelTitle': gScene.renderLevelTitle(); break; } if (!gScene.inTransition) gInput.render(); // Debug display // this.context.font = '16px monospace'; // this.context.textAlign = 'left'; // this.context.fillStyle = '#FFF'; // this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12); // this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36); this.frame = (this.frame + 1) % 60; } }
gRenderer = { frame: 0, render: function() { this.context.fillStyle = '#000'; this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height); switch (gScene.scene) { case 'title': gScene.renderTitle(); break; case 'hangar': case 'game': gScene.renderBack(); if (gPlayer.life > 0) gPlayer.render(); gScene.renderFore(); gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this)); if (gScene.inTransition) gScene.renderTransition(); break; case 'levelTitle': gScene.renderLevelTitle(); break; } if (!gScene.inTransition) gInput.render(); // Debug display // this.context.font = '16px monospace'; // this.context.textAlign = 'left'; // this.context.fillStyle = '#FFF'; // this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12); // this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36); this.frame = (this.frame + 1) % 240; } }
Increase gRenderer frame max to 240
Increase gRenderer frame max to 240
JavaScript
mit
peternatewood/shmup,peternatewood/shmup,peternatewood/shmup
cdf0bab5f02a914e51be806680e5c7252b873d76
plugins/meta.js
plugins/meta.js
const LifeforcePlugin = require("../utils/LifeforcePlugin.js"); const serverhostname = "http://localhost:16001"; //const serverhostname = "https://api.repkam09.com"; class MetaEndpoints extends LifeforcePlugin { constructor(restifyserver, logger, name) { super(restifyserver, logger, name); this.apiMap = [ { path: "/api/about", type: "get", handler: handleAboutApi }, { path: "/", type: "get", handler: handleAboutApi } ]; } } function handleAboutApi(req, res, next) { var apis = []; var keys = Object.keys(this.restifyserver.router.mounts); keys.forEach((key) => { var current = this.restifyserver.router.mounts[key]; apis.push({ path: serverhostname + current.spec.path, method: current.method }); }); res.send(200, apis); } module.exports = MetaEndpoints;
const LifeforcePlugin = require("../utils/LifeforcePlugin.js"); //const serverhostname = "http://localhost:16001"; const serverhostname = "https://api.repkam09.com"; class MetaEndpoints extends LifeforcePlugin { constructor(restifyserver, logger, name) { super(restifyserver, logger, name); this.apiMap = [ { path: "/api/about", type: "get", handler: handleAboutApi }, { path: "/", type: "get", handler: handleAboutApi } ]; } } function handleAboutApi(req, res, next) { var apis = []; var keys = Object.keys(this.restifyserver.router.mounts); keys.forEach((key) => { var current = this.restifyserver.router.mounts[key]; apis.push({ path: serverhostname + current.spec.path, method: current.method }); }); res.send(200, apis); } module.exports = MetaEndpoints;
Fix url to real production url
Fix url to real production url
JavaScript
mit
repkam09/repka-lifeforce,repkam09/repka-lifeforce,repkam09/repka-lifeforce
d9ff1a08d3c89cc88b7436ca97ffda589d322f82
test/retrieve.js
test/retrieve.js
'use strict'; var should = require('should'); var config = require('../config/configuration.js'); var retrieve = require('../lib/provider-google-drive/helpers/retrieve.js'); describe("Retrieve files", function () { it("should list files when no id passed and return the id of the last document", function(done) { retrieve(config.test_refresh_token, null, config, function(err, files, lastId) { if(err) { throw err; } files.should.have.lengthOf(4); should.exist(files[0]); lastId.should.equal("49"); files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE'); files[0].should.have.property('title', 'Test'); files[0].should.have.property('mimeType', 'application/vnd.google-apps.document'); done(); }); }); it("should list files from a given id", function(done) { retrieve(config.test_refresh_token, "44", config, function(err, files, lastId) { if(err) { throw err; } files.length.should.equal(3); done(); }); }); });
'use strict'; var should = require('should'); var config = require('../config/configuration.js'); var retrieve = require('../lib/provider-google-drive/helpers/retrieve.js'); describe("Retrieve files", function () { it("should list files when no id passed and return the id of the last document", function(done) { retrieve(config.test_refresh_token, null, config, function(err, files, lastId) { if(err) { throw err; } files.should.have.lengthOf(4); should.exist(files[0]); lastId.should.equal("82"); files[0].should.have.property('id', '1wnEFyXM4bSaSqMORS0NycszCse9dJvhYoiZnITRMeCE'); files[0].should.have.property('title', 'Test'); files[0].should.have.property('mimeType', 'application/vnd.google-apps.document'); done(); }); }); it("should list files from a given id", function(done) { retrieve(config.test_refresh_token, "44", config, function(err, files, lastId) { if(err) { throw err; } files.length.should.equal(4); done(); }); }); });
Update to the new drive state
Update to the new drive state
JavaScript
mit
AnyFetch/gdrive-provider.anyfetch.com
9dd0b0983b9ae8cf45d9505494e0e0afad9094f7
oui.js
oui.js
#!/usr/bin/env node "use strict"; process.title = "oui"; var arg = process.argv[2], oui = require("./"), spin = require("char-spinner"); if (arg === "--update") { var interval = spin(); oui.update(true, function (err) { clearInterval(interval); if (err) process.stdout.write(err + "\n"); process.exit(err ? 1 : 0); }); } else if (!arg || arg === "--help") { process.stdout.write([ "", " Usage: oui mac [options]", "", " Options:", "", " --help display this help", " --update update the database", "", "" ].join("\n")); process.exit(1); } else { var result; try { result = oui(arg); } catch (err) { process.stdout.write(err.message + "\n"); process.exit(1); } if (result) { process.stdout.write(result + "\n"); } else { process.stdout.write(arg + " not found in database\n"); } process.exit(0); }
#!/usr/bin/env node "use strict"; process.title = "oui"; var arg = process.argv[2], oui = require("./"), spin = require("char-spinner"); if (arg === "--update") { var interval = spin(); oui.update(true, function (err) { clearInterval(interval); if (err) process.stdout.write(err + "\n"); process.exit(err ? 1 : 0); }); } else if (!arg || arg === "--help") { process.stdout.write([ "", " Usage: oui mac [options]", "", " Options:", "", " --help display this help", " --update update the database", "", "" ].join("\n")); process.exit(0); } else { var result; try { result = oui(arg); } catch (err) { process.stdout.write(err.message + "\n"); process.exit(1); } if (result) process.stdout.write(result + "\n"); else process.stdout.write(arg + " not found in database\n"); process.exit(0); }
Correct exit code on help
Correct exit code on help
JavaScript
bsd-2-clause
silverwind/oui
dd2ac1fb52cb9c154d0b9bf354fd22d250413d94
date.polyfill.js
date.polyfill.js
/** * Date.prototype.toISOString() * version 0.0.0 * Feature Chrome Firefox Internet Explorer Opera Safari Edge * Basic support 3 1 9 10.5 5 12 * ------------------------------------------------------------------------------- */ if (!Date.prototype.toISOString) { Date.prototype.toISOString = function () { function pad(number) { if (number < 10) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; }
/** * Date.prototype.toISOString() * version 0.0.0 * Feature Chrome Firefox Internet Explorer Opera Safari Edge * Basic support 3 1 9 10.5 5 12 * ------------------------------------------------------------------------------- */ if (!Date.prototype.toISOString) { Object.defineProperty(Array.prototype, 'toISOString', { configurable : true, writable : true, value : function () { function pad(number) { if (number < 10) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; } }); }
Define all Date toISOString properties with Object.defineProperty, using the descriptors configurable, writable and non-enumerable.
Define all Date toISOString properties with Object.defineProperty, using the descriptors configurable, writable and non-enumerable.
JavaScript
mit
uxitten/polyfill
df3f7f36a5dce3e85660106e79953facfd0c7555
assets/javascripts/p_slides.js
assets/javascripts/p_slides.js
$(".presentation").each(function() { var md = new Remarkable('full', { html: true }); var markup = md.render($(this).html()); var slides = markup.split('<hr>'); var new_document = []; for (var j = 0; j < slides.length; j++) new_document.push('<div class=slide>' + slides[j] + '</div>'); document.write(new_document.join("")); }); $(".presentation").remove(); // If you want to syntax highlight all your code in the same way then // you can uncomment and customize the next line // //$("pre>code").parent().addClass("syntax cpp"); w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click); $.syntax(); // Automatic detection for theme javascript. It will run after slides // have been generated for(i in document.styleSheets) { stylesheet = document.styleSheets[i].href; if (stylesheet && stylesheet.indexOf("theme") != -1) { theme = stylesheet.slice(stylesheet.lastIndexOf("/")+1, stylesheet.length); eval(theme.replace(".css", "()")); } }
$(".presentation").each(function() { var md = new Remarkable('full', { html: true//, // Here goes a real syntax highlighter //highlight: function (str, lang) { // return str; //} }); var markup = md.render($(this).html()); var slides = markup.split('<hr>'); var new_document = []; for (var j = 0; j < slides.length; j++) new_document.push('<div class=slide>' + slides[j] + '</div>'); document.write(new_document.join("")); }); $(".presentation").remove(); // If you want to syntax highlight all your code in the same way then // you can uncomment and customize the next line // //$("pre>code").parent().addClass("syntax cpp"); w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click); // XXX: Work Around // RemarkableJS above translates content of <pre> Tags into HTML. // Therefore empty lines will create new paragraphs. Remove those // paragraphs, so that the newlines stay intact for code highlighting. // Note: Indentation is lost and cannot be retrieved here // Note: The better solution is to ditch jquery-syntax and go with // something that can be used together with RemarkableJS. $("pre.syntax").map(function(element) { $(this).html($(this). html(). replace(/<p>/g, "\n"). replace(/<\/p>/g, "")); }); $.syntax(); // Automatic detection for theme javascript. It will run after slides // have been generated for(i in document.styleSheets) { stylesheet = document.styleSheets[i].href; if (stylesheet && stylesheet.indexOf("theme") != -1) { theme = stylesheet.slice(stylesheet.lastIndexOf("/")+1, stylesheet.length); eval(theme.replace(".css", "()")); } }
Add workaround to introduce slightly better syntax highlighting.
Add workaround to introduce slightly better syntax highlighting.
JavaScript
agpl-3.0
munen/p_slides,munen/p_slides
7556ac4105736e6414933cc6bc928c696a625083
readFile.js
readFile.js
/** * Created by Kanthanarasimhaiah on 14/11/13. */ fs = require('fs'); var num_of_tasks; var total_time; var fileName = process.argv[2]; fs.readFile(fileName, 'utf8', function (err,data) { if (err) { return console.log(err); } //console.log(data); var input=data.split('\n'); var line1 = input[0].split(' '); num_of_tasks=parseInt(line1[0], 10); total_time=parseInt(line1[1], 10); console.log("Numer of Tasks:", num_of_tasks); console.log("Total Time:", total_time); // read in the tasks var queue= []; for(var j=1;j<num_of_tasks;j++) { var task_data=input[j].split(' '); var task = {id : task_data[0], start_time : parseInt(task_data[1], 10), duration : parseInt(task_data[2], 10)}; queue.push(task); } function sort_function (a, b) { return a.start_time - b.start_time; } queue.sort(sort_function); console.log("Tasks:"); console.log(queue); });
/** * Created by Kanthanarasimhaiah on 14/11/13. */ fs = require('fs'); function readTasks (file) { var data = fs.readFileSync(file, 'utf8'); var input=data.split('\n'); var line1 = input[0].split(' '); var num_of_tasks=parseInt(line1[0], 10); var total_time=parseInt(line1[1], 10); // read in the tasks var queue= []; for(var j=1;j<num_of_tasks;j++) { var task_data=input[j].split(' '); var task = {id : task_data[0], start_time : parseInt(task_data[1], 10), duration : parseInt(task_data[2], 10)}; queue.push(task); } function sort_function (a, b) { return a.start_time - b.start_time; } queue.sort(sort_function); return {num_of_tasks: num_of_tasks, total_time: total_time, task_queue: queue}; } var fileName = process.argv[2]; var tasks = readTasks(fileName); console.log("Numer of Tasks:", tasks.num_of_tasks); console.log("Total Time:", tasks.total_time); console.log("Task Queue:"); console.log(tasks.task_queue);
Move task reading into a standalone function.
Move task reading into a standalone function. - Also, use readFileSync (synchronous).
JavaScript
mpl-2.0
kanaka/rbt_cfs
b6bc9e62d615242ef0eaa438d961d08a3ea9c72a
server/controllers/usersController.js
server/controllers/usersController.js
let UserRecipes = require(`${__dirname}/../schemas.js`).UserRecipes; module.exports = { signup: (req, res) => { }, login: (req, res) => { }, logout: (req, res) => { }, //Gets all the recipes that belong to that user getProfile: (req, res) => { UserRecipes.findOne({ username: req.params.username }).then(result => { res.status(200).send(result); }).catch(error => { res.status(404).send(error); }); } };
let UserRecipe = require(`${__dirname}/../schemas.js`).UserRecipe; module.exports = { signup: (req, res) => { }, login: (req, res) => { }, logout: (req, res) => { }, //Gets all the recipes that belong to that user getProfile: (req, res) => { UserRecipe.findOne({ username: req.params.username }).then(result => { res.status(200).send(result); }).catch(error => { res.status(404).send(error); }); } };
Remove 's' from UserRecipe(s) in user controller
Remove 's' from UserRecipe(s) in user controller
JavaScript
mit
JAC-Labs/SkilletHub,JAC-Labs/SkilletHub
8abac9363de638edb93bfd3e9744ccb78930aace
Honeybee/EventHandler.js
Honeybee/EventHandler.js
'use strict'; //Import events const events = require('events'); //Create EventHandler function class EventHandler extends events.EventEmitter { constructor() { super() } registered() { this.emit('registered') } request(callback) { this.emit('request', callback) } submit(data, callback) { this.emit('submit', data, callback) } } module.exports = EventHandler;
'use strict'; //Import events const events = require('events'); //Create EventHandler function class EventHandler extends events.EventEmitter { constructor() { super(); } registered() { this.emit('registered'); } request(callback) { this.emit('request', callback); } submit(data, callback) { this.emit('submit', data, callback); } } module.exports = EventHandler;
Fix conventional errors from previos commit
Fix conventional errors from previos commit
JavaScript
isc
Kurimizumi/Honeybee-Hive
76a4a74053b07d7fe6a1d98ee0271173dbc58cf8
App/data/CaretakerRolesGateway/index.js
App/data/CaretakerRolesGateway/index.js
/* Makes API calls to fetch caretaker roles. However, until there is an API to call, it returns canned data. */ export default class CaretakerRolesGateway { static allRoles = null; static getAll() { if(this.allRoles === null) { //api call to get roles this.allRoles = [ {id: 1, name: 'Driver', description: 'Gives rides to things'}, {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'}, {id: 3, name: 'Groceries', description: 'Picks up groceries'}, {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'}, {id: 5, name: 'Chef', description: 'Cooks food cause yum'} ] } return this.allRoles; } }
/* Makes API calls to fetch caretaker roles. However, until there is an API to call, it returns canned data. */ const createCaretakerRolesGateway = () => { let allRoles = null; return { getAll: () => { if(allRoles === null) { //api call to get roles allRoles = [ {id: 1, name: 'Driver', description: 'Gives rides to things'}, {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'}, {id: 3, name: 'Groceries', description: 'Picks up groceries'}, {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'}, {id: 5, name: 'Chef', description: 'Cooks food cause yum'} ] } return allRoles; } } } export default createCaretakerRolesGateway();
Refactor CaretakerRolesGateway to use factory pattern
Refactor CaretakerRolesGateway to use factory pattern
JavaScript
mit
araneforseti/caretaker-app,araneforseti/caretaker-app,araneforseti/caretaker-app,araneforseti/caretaker-app
5fccae541140aa7d96be0566c97165cc84a6fd5f
to-title-case.js
to-title-case.js
ο»Ώ/* * To Title Case 2.0 – http://individed.com/code/to-title-case/ * Copyright Β© 2008–2012 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function() { var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i; return this.replace(/([^\W_]+[^\s-]*) */g, function(match, p1, index, title) { if (index > 0 && index + p1.length !== title.length && p1.search(smallWords) > -1 && title[index - 2] !== ":" && title[index - 1].search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (p1.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); };
ο»Ώ/* * To Title Case 2.0 – http://individed.com/code/to-title-case/ * Copyright Β© 2008–2012 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function () { var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i; return this.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) { if (index > 0 && index + p1.length !== title.length && p1.search(smallWords) > -1 && title[index - 2] !== ":" && title[index - 1].search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (p1.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); };
Add space between anon function and parens.
Add space between anon function and parens.
JavaScript
mit
rvagg/titlecase,fiatjaf/titulo,gouch/to-title-case,rvagg/titlecase,SaintPeter/titlecase,SaintPeter/titlecase,gouch/to-title-case
d8867d259040ce0eb240ede3edf9fc15415b299e
.eslintrc.js
.eslintrc.js
module.exports = { "extends": "airbnb", "parser": "babel-eslint", "plugins": [ "react" ], "rules": { "react/prop-types": 0, "space-before-function-paren": [2, { "anonymous": "never", "named": "always" }] } };
module.exports = { "extends": "airbnb", "parser": "babel-eslint", "plugins": [ "react" ], "rules": { "react/prop-types": 0, "react/jsx-boolean-value": 0, "consistent-return": 0, "space-before-function-paren": [2, { "anonymous": "never", "named": "always" }] } };
Add react rules to eslint file
Add react rules to eslint file
JavaScript
mit
mersocarlin/react-webpack-template,mersocarlin/react-webpack-template
8f3ea6b47eb1f4d0265676527652c333c36a21ca
app/latexCommands.js
app/latexCommands.js
module.exports = [ { action: '\\sqrt', label: '\\sqrt{X}' }, { action: '^', label: 'x^{X}' }, { action: '\\frac', label: '\\frac{X}{X}' }, { action: '\\int', label: '\\int_{X}^{X}' }, { action: '\\lim_', label: '\\lim_{X}' }, { action: '\\overrightarrow', label: '\\overrightarrow{X}' }, { action: '_', label: 'x_X' }, { action: '\\nthroot', label: '\\sqrt[X]{X}' }, { action: '\\sum', label: '\\sum_{X}^{X}' }, { action: '\\binom', label: '\\binom{X}{X}' }, { action: '\\sin' }, { action: '\\cos' }, { action: '\\tan' }, { action: '\\arcsin' }, { action: '\\arccos' }, { action: '\\arctan' }, { action: '\\not' }, { action: '\\vec', label: '\\vec{X}' }, { action: '\\bar', label: '\\bar{X}' }, { action: '\\underline', label: '\\underline{X}' }, { action: '\\overleftarrow', label: '\\overleftarrow{X}' }, { action: '|', label: '|X|'}, { action: '(', label: '(X)'} ]
module.exports = [ { action: '\\sqrt', label: '\\sqrt{X}' }, { action: '^', label: 'x^{X}' }, { action: '\\frac', label: '\\frac{X}{X}' }, { action: '\\int', label: '\\int_{X}^{X}' }, { action: '\\lim_', label: '\\lim_{X}' }, { action: '\\overrightarrow', label: '\\overrightarrow{X}' }, { action: '_', label: 'x_X' }, { action: '\\nthroot', label: '\\sqrt[X]{X}' }, { action: '\\sum', label: '\\sum_{X}^{X}' }, { action: '\\binom', label: '\\binom{X}{X}' }, { action: '\\sin' }, { action: '\\cos' }, { action: '\\tan' }, { action: '\\arcsin' }, { action: '\\arccos' }, { action: '\\arctan' }, { action: '\\vec', label: '\\vec{X}' }, { action: '\\bar', label: '\\bar{X}' }, { action: '\\underline', label: '\\underline{X}' }, { action: '\\overleftarrow', label: '\\overleftarrow{X}' }, { action: '|', label: '|X|'}, { action: '(', label: '(X)'} ]
Remove problematic not tool from the equation toolbar;
Remove problematic not tool from the equation toolbar; \not is used in conjunction with other commands such as \equiv or \infty. Mathquill however does not support this and changes \not to \neg.
JavaScript
mit
digabi/rich-text-editor,digabi/math-editor,digabi/math-editor,digabi/rich-text-editor,digabi/rich-text-editor
2030607c7012d78233deb3882f94bdac1fb6aff2
routes/index.js
routes/index.js
const UserController = require('../src/Http/Controllers/User'); const { define, wrap, post, get } = require('spirit-router'); const { json } = require('body-parser'); const express = require('spirit-express'); module.exports = define('/api', [ get('/users', UserController.index), get('/users/:user_id', ['user_id'], UserController.show), wrap(post('/users', ['body'], UserController.store), express(json())), ]);
const UserController = require('../src/Http/Controllers/User'); const { define, wrap, post, get, any, notFound } = require('spirit-router'); const { json } = require('body-parser'); const express = require('spirit-express'); const api = define('/api', [ get('/users', UserController.index), get('/users/:user_id', ['user_id'], UserController.show), wrap(post('/users', ['body'], UserController.store), express(json())), ]); module.exports = define([api, any('*', notFound())]);
Add default not found route
feat: Add default not found route
JavaScript
mit
diogoazevedos/corpus,diogoazevedos/corpus
b69ee85c892ef3ff7a0542e3ce4a799051a1ea8a
services/web/src/main/ember/app/components/draggable-dropzone.js
services/web/src/main/ember/app/components/draggable-dropzone.js
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['draggable-dropzone'], classNameBindings: ['dragClass'], dragClass: 'deactivated', dragLeave: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); }, dragOver: function(event) { event.preventDefault(); this.set('dragClass', 'activated'); }, drop: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); data = event.dataTransfer.getData('text/data'); // default drop action - change with {{draggable-dropzone dropped=xyz}} this.sendAction('dropped', data); } });
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['draggable-dropzone'], classNameBindings: ['dragClass'], dragClass: 'deactivated', dragLeave: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); }, dragOver: function(event) { event.preventDefault(); this.set('dragClass', 'activated'); }, drop: function(event) { event.preventDefault(); this.set('dragClass', 'deactivated'); var data = event.dataTransfer.getData('text/data'); // default drop action - change with {{draggable-dropzone dropped=xyz}} this.sendAction('dropped', data); } });
Fix small issue with ember dropzone
Fix small issue with ember dropzone
JavaScript
agpl-3.0
MarSik/shelves,MarSik/shelves,MarSik/shelves,MarSik/shelves
212b6c3a0ffb9eb7595b3987fa77040cadd92054
.eslintrc.js
.eslintrc.js
module.exports = { extends: ["matrix-org"], plugins: [ "babel", ], env: { browser: true, node: true, }, rules: { "no-var": ["warn"], "prefer-rest-params": ["warn"], "prefer-spread": ["warn"], "one-var": ["warn"], "padded-blocks": ["warn"], "no-extend-native": ["warn"], "camelcase": ["warn"], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "space-before-function-paren": ["error", { "anonymous": "never", "named": "never", "asyncArrow": "always", }], "arrow-parens": "off", "prefer-promise-reject-errors": "off", "quotes": "off", "indent": "off", "no-constant-condition": "off", "no-async-promise-executor": "off", // We use a `logger` intermediary module "no-console": "error", }, overrides: [{ "files": ["src/**/*.ts"], "extends": ["matrix-org/ts"], "rules": { // While we're converting to ts we make heavy use of this "@typescript-eslint/no-explicit-any": "off", "quotes": "off", }, }], };
module.exports = { extends: ["matrix-org"], plugins: [ "babel", ], env: { browser: true, node: true, }, rules: { "no-var": ["warn"], "prefer-rest-params": ["warn"], "prefer-spread": ["warn"], "one-var": ["warn"], "padded-blocks": ["warn"], "no-extend-native": ["warn"], "camelcase": ["warn"], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "space-before-function-paren": ["error", { "anonymous": "never", "named": "never", "asyncArrow": "always", }], "arrow-parens": "off", "prefer-promise-reject-errors": "off", "quotes": "off", "indent": "off", "no-constant-condition": "off", "no-async-promise-executor": "off", // We use a `logger` intermediary module "no-console": "error", }, overrides: [{ "files": ["src/**/*.ts"], "extends": ["matrix-org/ts"], "rules": { // We're okay being explicit at the moment "@typescript-eslint/no-empty-interface": "off", // While we're converting to ts we make heavy use of this "@typescript-eslint/no-explicit-any": "off", "quotes": "off", }, }], };
Resolve linting errors after upgrades
Resolve linting errors after upgrades
JavaScript
apache-2.0
matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk
8a22be70adca8bd7dd632f07451b878515dcfd58
.eslintrc.js
.eslintrc.js
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style extends: 'standard', plugins: [ 'html' // required to lint *.vue files ], // add your custom rules here 'rules': { // allow paren-less arrow functions 'arrow-parens': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 } }
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style extends: 'standard', plugins: [ 'html' // required to lint *.vue files ], // add your custom rules here 'rules': { // allow no-spaces between function name and argument parethesis list 'space-before-function-paren': 0, // allow paren-less arrow functions 'arrow-parens': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 } }
Update eslint rules to allow no-spaces between function name and argument parenthesis
Update eslint rules to allow no-spaces between function name and argument parenthesis
JavaScript
mit
cngu/vue-typer,cngu/vue-typer
f3ab92fb8626916d7824409c9b514854d28ab51e
www/js/Controllers/nearby.js
www/js/Controllers/nearby.js
angular.module('gitphaser') .controller('NearbyCtrl', NearbyCtrl); // @controller NearbyCtrl // @params: $scope, $reactive // @route: /tab/nearby // // Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter' // Subscription to 'connections' is handled in the route resolve. Also // exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user // clicks on list item to see profile) function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){ $reactive(this).attach($scope); var self = this; // Slide constants bound to the GeoLocate directive // and other DOM events, trigger updates based on // whether we are looking at List || Map view. self.listSlide = 0 self.mapSlide = 1; self.slide = 0; // Services self.geolocate = GeoLocate; self.notify = Notify; self.helpers({ connections: function () { if (Meteor.userId()){ return Connections.find( {transmitter: Meteor.userId() } ); } } }); };
angular.module('gitphaser').controller('NearbyCtrl', NearbyCtrl); /** * Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter' * Subscription to 'connections' is handled in the route resolve. Also * exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user * clicks on list item to see profile) * @controller NearbyCtrl * @route: /tab/nearby */ function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){ $reactive(this).attach($scope); var self = this; // Slide constants bound to the GeoLocate directive // and other DOM events, trigger updates based on // whether we are looking at List || Map view. self.listSlide = 0 self.mapSlide = 1; self.slide = 0; // Services self.geolocate = GeoLocate; self.notify = Notify; self.helpers({ connections: function () { if (Meteor.userId()){ return Connections.find( {transmitter: Meteor.userId() } ); } } }); };
Test push after changing local remote
Test push after changing local remote
JavaScript
mit
git-phaser/git-phaser,git-phaser/git-phaser,git-phaser/git-phaser,git-phaser/git-phaser
d6b8f2f017d2f28854d51ff3210c734352b8ca6a
VotingApplication/VotingApplication.Web/Scripts/Controllers/CreateBasicPageController.js
VotingApplication/VotingApplication.Web/Scripts/Controllers/CreateBasicPageController.js
ο»Ώ(function () { angular .module('GVA.Creation') .controller('CreateBasicPageController', ['$scope', 'AccountService', 'PollService', function ($scope, AccountService, PollService) { $scope.openLoginDialog = function () { AccountService.openLoginDialog($scope); }; $scope.openRegisterDialog = function () { AccountService.openRegisterDialog($scope); }; $scope.createPoll = function (question) { PollService.createPoll(question, function (data) { window.location.href = "/Manage/" + data.ManageId; }); }; }]); })();
ο»Ώ(function () { angular .module('GVA.Creation') .controller('CreateBasicPageController', ['$scope', 'AccountService', 'PollService', function ($scope, AccountService, PollService) { $scope.openLoginDialog = function () { AccountService.openLoginDialog($scope); }; $scope.openRegisterDialog = function () { AccountService.openRegisterDialog($scope); }; $scope.createPoll = function (question) { PollService.createPoll(question, function (data) { window.location.href = "/#/Manage/" + data.ManageId; }); }; }]); })();
Fix redirect after poll creation
Fix redirect after poll creation Redirect to /#/Manage/<ManageId> rather than /Manage/<ManageId>
JavaScript
apache-2.0
Generic-Voting-Application/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,Generic-Voting-Application/voting-application,tpkelly/voting-application,stevenhillcox/voting-application
1883460122f4690d84f673ef083d23b95f3abcd5
app/student.front.js
app/student.front.js
const $answer = $('.answer') const {makeRichText} = require('./math-editor') const save = ($elem, async = true) => $.post({ url: '/save', data: {text: $elem.html(), answerId: $elem.attr('id')}, async }) function saveScreenshot(questionId) { return ({data, type, id}) => { return $.post({ type: 'POST', url: `/saveImg?answerId=${questionId}&id=${id}`, data: data, processData: false, contentType: type }).then(res => { console.log('heh', res) return res.url }) } } const richTextOptions = id => ({ screenshot: { saver: data => saveScreenshot(id)(data) } }) $answer.each((i, answer) => { makeRichText(answer, richTextOptions(answer.id)) $.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html)) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() save($(e.target)) } })
const $answer = $('.answer') const {makeRichText} = require('./math-editor') const save = ($elem, async = true) => $.post({ url: '/save', data: {text: $elem.html(), answerId: $elem.attr('id')}, async }) function saveScreenshot(questionId) { return ({data, type, id}) => { return $.post({ type: 'POST', url: `/saveImg?answerId=${questionId}&id=${id}`, data: data, processData: false, contentType: type }).then(res => { console.log('heh', res) return res.url }) } } const richTextOptions = id => ({ screenshot: { saver: data => saveScreenshot(id)(data) } }) $answer.each((i, answer) => { makeRichText(answer, richTextOptions(answer.id)) $.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html)) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() save($(e.target)) } }) $('#answer1').focus()
Set focus automatically to first field
Set focus automatically to first field
JavaScript
mit
digabi/rich-text-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/math-editor,digabi/math-editor
7dfbb87add262139525d9981f6024a46bbc52190
src/jupyter_contrib_nbextensions/nbextensions/export_embedded/main.js
src/jupyter_contrib_nbextensions/nbextensions/export_embedded/main.js
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function initialize () { console.log("Embedded HTML Exporter loaded!"); } var load_ipython_extension = function() { var dwm = $("#download_menu") var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>') dwm.append(downloadEntry) downloadEntry.click(function () { Jupyter.menubar._nbconvert('html_embed', true); }); Jupyter.toolbar.add_buttons_group([{ id : 'export_embeddedhtml', label : 'Embedded HTML Export', icon : 'fa-save', callback : function() { Jupyter.menubar._nbconvert('html_embed', true); } }]); if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function initialize () { } var load_ipython_extension = function() { /* Add an entry in the download menu */ var dwm = $("#download_menu") var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>') dwm.append(downloadEntry) downloadEntry.click(function () { Jupyter.menubar._nbconvert('html_embed', true); }); /* Add also a Button, currently disabled */ /* Jupyter.toolbar.add_buttons_group([{ id : 'export_embeddedhtml', label : 'Embedded HTML Export', icon : 'fa-save', callback : function() { Jupyter.menubar._nbconvert('html_embed', true); } }]); */ if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
Remove Button, only in Download Menu
Remove Button, only in Download Menu
JavaScript
bsd-3-clause
ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,juhasch/IPython-notebook-extensions
86de60799199c39949c6f862997752c688572c91
src/apps/contacts/middleware/interactions.js
src/apps/contacts/middleware/interactions.js
const { getContact } = require('../../contacts/repos') function setInteractionsDetails (req, res, next) { res.locals.interactions = { returnLink: `/contacts/${req.params.contactId}/interactions/`, entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`, query: { contacts_id: req.params.contactId }, view: 'contacts/views/interactions', canAdd: true, } next() } async function setCompanyDetails (req, res, next) { try { const contact = await getContact(req.session.token, req.params.contactId) res.locals.company = contact.company next() } catch (error) { next(error) } } module.exports = { setInteractionsDetails, setCompanyDetails, }
const { getContact } = require('../../contacts/repos') function setInteractionsDetails (req, res, next) { res.locals.interactions = { returnLink: `/contacts/${req.params.contactId}/interactions/`, entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`, query: { contacts__id: req.params.contactId }, view: 'contacts/views/interactions', canAdd: true, } next() } async function setCompanyDetails (req, res, next) { try { const contact = await getContact(req.session.token, req.params.contactId) res.locals.company = contact.company next() } catch (error) { next(error) } } module.exports = { setInteractionsDetails, setCompanyDetails, }
Add missing underscore on query param to contacts
Add missing underscore on query param to contacts
JavaScript
mit
uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend
ca0425c4149e8a3dd736abef6a13967d8d656f20
src/audits/UnfocusableElementsWithOnClick.js
src/audits/UnfocusableElementsWithOnClick.js
// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. AuditRules.addRule({ name: 'unfocusableElementsWithOnClick', severity: Severity.Warning, opt_shouldRunInDevtools: true, relevantNodesSelector: function() { var potentialOnclickElements = document.querySelectorAll('span, div, img'); var unfocusableClickableElements = []; for (var i = 0; i < potentialOnclickElements.length; i++) { var element = potentialOnclickElements[i]; if (AccessibilityUtils.isElementOrAncestorHidden) continue; var eventListeners = getEventListeners(element); if ('click' in eventListeners) { unfocusableClickableElements.push(element); } } return unfocusableClickableElements; }, test: function(element) { return element.tabIndex == null; } });
// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. AuditRules.addRule({ name: 'unfocusableElementsWithOnClick', severity: Severity.Warning, opt_shouldRunInDevtools: true, relevantNodesSelector: function() { var potentialOnclickElements = document.querySelectorAll('*'); var unfocusableClickableElements = []; for (var i = 0; i < potentialOnclickElements.length; i++) { var element = potentialOnclickElements[i]; if (AccessibilityUtils.isElementOrAncestorHidden) continue; var eventListeners = getEventListeners(element); if ('click' in eventListeners) { unfocusableClickableElements.push(element); } } return unfocusableClickableElements; }, test: function(element) { return element.tabIndex == null; } });
Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick
Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick
JavaScript
apache-2.0
japacible/accessibility-developer-tools-extension,modulexcite/accessibility-developer-tools,alice/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,ckundo/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,kublaj/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,seksanman/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,googlearchive/accessibility-developer-tools-extension,japacible/accessibility-developer-tools,Khan/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,alice/accessibility-developer-tools,garcialo/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,japacible/accessibility-developer-tools,ckundo/accessibility-developer-tools,japacible/accessibility-developer-tools,alice/accessibility-developer-tools,seksanman/accessibility-developer-tools,t9nf/accessibility-developer-tools,hmrc/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,japacible/accessibility-developer-tools-extension,seksanman/accessibility-developer-tools,hmrc/accessibility-developer-tools,Khan/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,garcialo/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,Khan/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,kublaj/accessibility-developer-tools,ckundo/accessibility-developer-tools,minorninth/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,modulexcite/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,hmrc/accessibility-developer-tools,t9nf/accessibility-developer-tools,modulexcite/accessibility-developer-tools,garcialo/accessibility-developer-tools,googlearchive/accessibility-developer-tools-extension,GabrielDuque/accessibility-developer-tools,minorninth/accessibility-developer-tools,t9nf/accessibility-developer-tools,kublaj/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,kristapsmelderis/accessibility-developer-tools,ricksbrown/accessibility-developer-tools
8f5dda30829b7439f0fc49d8e1fe86623980dc3b
dev/grunt/postcss.js
dev/grunt/postcss.js
module.exports = { options: { map: true, // inline sourcemaps processors: [ require('pixrem')(), // add fallbacks for rem units require('autoprefixer-core')({ // add vendor prefixes browsers: [ 'last 3 version', 'ie 8', 'ff 3.6', 'opera 11.1', 'ios 4', 'android 2.3' ] }), require('cssnano')() // minify the result ] }, dist: { src: '<%= destCSSDir %>' + '/*.css' } };
module.exports = { options: { map: true, // inline sourcemaps processors: [ require('pixrem')(), // add fallbacks for rem units require('autoprefixer-core')({ // add vendor prefixes browsers: [ 'last 3 version', 'ie 8', 'ff 3.6', 'opera 11.1', 'ios 4', 'android 2.3' ] }), require('cssnano')({ convertValues: false }) // minify the result ] }, dist: { src: '<%= destCSSDir %>' + '/*.css' } };
Disable not-safe PostCSS value conversions
Disable not-safe PostCSS value conversions
JavaScript
mit
ideus-team/html-framework,ideus-team/html-framework
6cdb0bf0cb4872dae918175851b1fec4341bfb97
violet/violet.js
violet/violet.js
#!/usr/bin/env node var ncp = require('ncp').ncp; var path = require('path'); require('yargs') .usage('$0 <cmd> [args]') .option('directory', { alias: 'd', describe: 'Provide the directory to install Violet to' }) .command('install', 'Install violet', {}, function (argv) { var directory = 'violet'; if (argv.directory != null) { directory = argv.directory; } ncp(path.resolve(__dirname, './source'), directory, function (err) { if (err) { return console.error(err); } console.log('Installed Violet!'); }); }) .help('help') .argv;
#!/usr/bin/env node var ncp = require('ncp').ncp; var path = require('path'); var fs = require('fs'); require('yargs') .usage('$0 <cmd> [args]') .option('directory', { alias: 'd', describe: 'Provide the directory to install Violet to' }) .command('install', 'Install Violet', {}, function (argv) { var directory = 'violet'; if (argv.directory != null) { directory = argv.directory; } install(directory); }) .command('update', 'Update Violet', {}, function (argv) { var directory = 'violet'; if (argv.directory != null) { directory = argv.directory; } deleteFolderRecursive(directory); install(directory); }) .help('help') .argv; function install(directory) { ncp(path.resolve(__dirname, './source'), directory, function (err) { if (err) { return console.error(err); } console.log('Installed Violet!'); }); } // thanks to http://www.geedew.com/remove-a-directory-that-is-not-empty-in-nodejs/ function deleteFolderRecursive(path) { if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function (file, index) { var curPath = path + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse deleteFolderRecursive(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } };
Add update fucntion to CLI
Add update fucntion to CLI
JavaScript
mit
Lexteam/lexteam.github.io,Lexteam/lexteam.github.io,Lexteam/lexteam.github.io
482508f2927d05f2be0c58b20d7f9acd35606bc4
scripts/docs.js
scripts/docs.js
#!/usr/bin/env node var _ = require('lodash'); var docdown = require('docdown'); var fs = require('fs'); var path = require('path'); var srcPath = path.join(__dirname, '../src'); var outPath = path.join(__dirname, '../docs'); // Define which files to scan var sourceFiles = [ 'tree.js', 'treenode.js', 'treenodes.js' ]; // Create output directory if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } _.each(sourceFiles, function(sourceFile) { var markdown = docdown({ title: '', toc: 'categories', path: path.join(srcPath, sourceFile), url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile }); var docName = sourceFile.split('/').pop().replace('.js', '.md'); // Write file fs.writeFile(path.join(outPath, docName), markdown, function(err) { if (err) { console.log('Error writing to file:'); console.log(err); return; } console.log('Wrote output for ' + sourceFile); }); });
#!/usr/bin/env node var _ = require('lodash'); var docdown = require('docdown'); var fs = require('fs'); var path = require('path'); var srcPath = path.join(__dirname, '../src'); var outPath = path.join(__dirname, '../docs'); // Define which files to scan var sourceFiles = [ 'tree.js', 'treenode.js', 'treenodes.js' ]; // Create output directory if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } _.each(sourceFiles, function(sourceFile) { var markdown = docdown({ title: '', toc: 'categories', path: path.join(srcPath, sourceFile), style: 'github', url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile }); var docName = sourceFile.split('/').pop().replace('.js', '.md'); // Write file fs.writeFile(path.join(outPath, docName), markdown, function(err) { if (err) { console.log('Error writing to file:'); console.log(err); return; } console.log('Wrote output for ' + sourceFile); }); });
Set docdown style to github.
Set docdown style to github. [ci skip]
JavaScript
mit
helion3/inspire-tree,helion3/inspire-tree
70fab2cf5426def9114bdd40727f4a72593df9e4
src/core.js
src/core.js
(function(global) { 'use strict'; define([ ], function() { // $HEADER$ /** * This will be the <code>warmsea</code> namespace. * @namespace * @alias warmsea */ var w = _.extend({}, _); /** * The unmodified underlying underscore object. */ w._ = w.underscore = _; /** * The version of this WarmseaJS. * @type {string} */ w.VERSION = '$VERSION$'; /** * The global object of the executing environment. * @type {object} */ w.global = global; /** * Save the previous `warmsea`. */ var previousWarmsea = global.warmsea; /** * Return the current `warmsea` and restore the previous global one. * @return {warmsea} This warmsea object. */ w.noConflict = function() { global.warmsea = previousWarmsea; return this; }; /** * A function that throws an error with the message "Unimplemented". */ w.unimplemented = function() { w.error('Unimplemented'); }; /** * Throws an Error. * @method * @param {string} msg * @throws {Error} */ w.error = function(msg) { throw new Error(msg); }; // $FOOTER$ return w; }); })(this);
(function(global) { 'use strict'; define([ ], function() { // $HEADER$ /** * This will be the <code>warmsea</code> namespace. * @namespace * @alias warmsea */ var w = _.extend({}, _); /** * The unmodified underlying underscore object. */ w._ = w.underscore = _; /** * The version of this WarmseaJS. * @type {string} */ w.VERSION = '$VERSION$'; /** * The global object of the executing environment. * @type {object} */ w.global = global; /** * Save the previous `warmsea`. */ var previousWarmsea = global.warmsea; /** * Return the current `warmsea` and restore the previous global one. * @return {warmsea} This warmsea object. */ w.noConflict = function() { global.warmsea = previousWarmsea; return this; }; /** * A function that throws an error with the message "Unimplemented". */ w.unimplemented = function() { w.error('Unimplemented'); }; /** * Throws an Error. * @method * @param {string} msg * @throws {Error} */ w.error = function(msg) { if (w.isFunction(w.format)) { msg = w.format.apply(w, arguments); } throw new Error(msg); }; // $FOOTER$ return w; }); })(this);
Format support for w.error() if possible.
Format support for w.error() if possible.
JavaScript
mit
warmsea/WarmseaJS
a0bd12dab161141e958e5d437694a7b22283fe8f
routes/index.js
routes/index.js
/* * Module dependencies */ var app = module.parent.exports, Joiner = require('../libs/joiner').Joiner; /* * Middlewares */ function isAnotherFile (req, res, next) { var folder = req.params.version; if (folder === 'assets' ||Β folder === 'vendor' ||Β folder === 'test' || folder === 'libs') { next('route'); } else { next(); } }; function isView (req, res, next) { if (req.params.type === undefined) { res.render(req.params.version + '.html'); } else { next(); } }; /* * Views */ app.get('/:version/:type?/:min?', isAnotherFile, isView, function (req, res, next) { var name = req.params.version + req.params.type.toUpperCase(), min = ((req.params.min) ? true : false), joiner = new Joiner(); joiner.on('joined', function (data) { res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css')); res.send(data.raw); }); joiner.run(name, min); }); /* * Index */ app.get('/', function (req, res, next) { res.redirect('/ui') });
/* * Module dependencies */ var app = module.parent.exports, Joiner = require('../libs/joiner').Joiner; /* * Middlewares */ function isAnotherFile (req, res, next) { var folder = req.params.version; if (folder === 'assets' ||Β folder === 'vendor' ||Β folder === 'test' || folder === 'libs') { next('route'); } else { next(); } }; function isView (req, res, next) { if (req.params.type === undefined) { res.render(req.params.version + '.html'); } else { next(); } }; /* * Views */ app.get('/:version/:type?', isAnotherFile, isView, function (req, res, next) { var name = req.params.version + req.params.type.toUpperCase(), min = ((req.query.min) ? req.query.min : false), joiner = new Joiner(); joiner.on('joined', function (data) { res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css')); res.send(data.raw); }); joiner.run(name, min); }); /* * Index */ app.get('/', function (req, res, next) { res.redirect('/ui') });
Change the min feature to a parameter as ?min=true to get data form joiner.
Change the min feature to a parameter as ?min=true to get data form joiner.
JavaScript
mit
amireynoso/uxtest,vrleonel/ml-test,atma/chico,mercadolibre/chico,amireynoso/uxtest,vrleonel/chico,vrleonel/chico,vrleonel/ml-test,mercadolibre/chico,atma/chico
70f456cc5409b296cfe481c16614c6444f88b69b
lib/actions/clean-cache.js
lib/actions/clean-cache.js
'use babel'; import yarnExec from '../yarn/exec'; import reportError from '../report-error'; const cleanCache = async () => { const success = await yarnExec(null, 'cache', ['clean']); if (!success) { atom.notifications.addError( 'An error occurred whilst cleaning cache. See output for more information.', ); return; } atom.notifications.addSuccess('Global package cache has been cleaned'); }; const confirmation = async () => { atom.confirm({ message: 'Are you sure you want to clean the global Yarn cache?', detailedMessage: 'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.', buttons: { 'Clean Cache': () => { cleanCache().catch(reportError); }, Cancel: null, }, }); }; export default confirmation;
'use babel'; import yarnExec from '../yarn/exec'; import reportError from '../report-error'; import addProgressNotification from '../add-progress-notification'; const cleanCache = async () => { let progress; const options = { onStart: () => { progress = addProgressNotification('Cleaning global package cache...'); }, }; const success = await yarnExec(null, 'cache', ['clean'], options); progress.dismiss(); if (!success) { atom.notifications.addError( 'An error occurred whilst cleaning global cache. See output for more information.', ); return; } atom.notifications.addSuccess('Global package cache has been cleaned'); }; const confirmation = async () => { atom.confirm({ message: 'Are you sure you want to clean the global Yarn cache?', detailedMessage: 'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.', buttons: { 'Clean Cache': () => { cleanCache().catch(reportError); }, Cancel: null, }, }); }; export default confirmation;
Add progress notification to clean cache command
Add progress notification to clean cache command
JavaScript
mit
cbovis/atom-yarn
1c7c0d1635747f12b82c202155045958907ec0c6
tests/unit/src/defur.js
tests/unit/src/defur.js
(function() { var defur = require('../../../src/defur'); var assert = require('chai').assert; suite('defur:', function() { var services = null; setup(function() { services = {}; }); test('`defur` is a function', function() { assert.isFunction(defur); }); test('`defur` defers execution of definition', function() { defur('foo', services, function() { throw new Error('This should be deferred.'); }); assert.throws(function() { services.foo; }); }); test('`defur` creates the service only once', function() { defur('foo', services, function() { return {}; }); assert.strictEqual(services.foo, services.foo); }); test('`defur` works with multiple service containers', function() { var otherServices = {}; defur('foo', services, function() { return {}; }); defur('foo', otherServices, function() { return {}; }); assert.notEqual(services.foo, otherServices.foo); }); }); })();
(function() { var defur = require('../../../src/defur'); var assert = require('chai').assert; suite('defur:', function() { var services = null; setup(function() { services = {}; }); test('`defur` is a function', function() { assert.isFunction(defur); }); test('`defur` defers execution of definition', function() { defur('foo', services, function() { throw new Error('This should be deferred.'); }); assert.throws(function() { services.foo; }); }); test('`defur` creates the service only once', function() { defur('foo', services, function() { return {}; }); assert.strictEqual(services.foo, services.foo); }); test('`defur` services don\'t collide', function() { defur('foo', services, function() { return {}; }); defur('bar', services, function() { return {}; }); assert.notEqual(services.foo, services.bar); }); test('`defur` works with multiple service containers', function() { var otherServices = {}; defur('foo', services, function() { return {}; }); defur('foo', otherServices, function() { return {}; }); assert.notEqual(services.foo, otherServices.foo); }); }); })();
Add test to cover container collisions
Add test to cover container collisions
JavaScript
mit
adlawson/js-defur,adlawson/js-defur
c4e58fda577b4f7f9165a788df9204d2646d26a3
lib/ext/patch-ember-app.js
lib/ext/patch-ember-app.js
/** * Monkeypatches the EmberApp instance from Ember CLI to contain the hooks we * need to filter environment-specific initializers. Hopefully we can upstream * similar hooks to Ember CLI and eventually remove these patches. */ function patchEmberApp(emberApp) { // App was already patched if (emberApp.addonPreconcatTree) { return; } // Save off original implementation of the `concatFiles` hook var originalConcatFiles = emberApp.concatFiles; // Install method to invoke `preconcatTree` hook on each addon emberApp.addonPreconcatTree = addonPreconcatTree; // Install patched `concatFiles` method. This checks options passed to it // and, if it detects that it's a concat for the app tree, invokes our // preconcat hook. Afterwards, we invoke the original implementation to // return a tree concating the files. emberApp.concatFiles = function(tree, options) { if (options.annotation === 'Concat: App') { tree = this.addonPreconcatTree(tree); } return originalConcatFiles.call(this, tree, options); }; } function addonPreconcatTree(tree) { var workingTree = tree; this.project.addons.forEach(function(addon) { if (addon.preconcatTree) { workingTree = addon.preconcatTree(workingTree); } }); return workingTree; } module.exports = patchEmberApp;
/** * Monkeypatches the EmberApp instance from Ember CLI to contain the hooks we * need to filter environment-specific initializers. Hopefully we can upstream * similar hooks to Ember CLI and eventually remove these patches. */ function patchEmberApp(emberApp) { // App was already patched if (emberApp.addonPreconcatTree) { return; } // Save off original implementation of the `concatFiles` hook var originalConcatFiles = emberApp.concatFiles; // Install method to invoke `preconcatTree` hook on each addon emberApp.addonPreconcatTree = addonPreconcatTree; // Install patched `concatFiles` method. This checks options passed to it // and, if it detects that it's a concat for the app tree, invokes our // preconcat hook. Afterwards, we invoke the original implementation to // return a tree concating the files. emberApp.concatFiles = function(tree, options) { if (options.annotation === 'Concat: App') { tree = this.addonPreconcatTree(tree); } return originalConcatFiles.apply(this, arguments); }; } function addonPreconcatTree(tree) { var workingTree = tree; this.project.addons.forEach(function(addon) { if (addon.preconcatTree) { workingTree = addon.preconcatTree(workingTree); } }); return workingTree; } module.exports = patchEmberApp;
Fix deprecation warning in for using EmberApp.concatFiles
Fix deprecation warning in for using EmberApp.concatFiles
JavaScript
mit
tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,josemarluedke/ember-cli-fastboot,tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,josemarluedke/ember-cli-fastboot
520b14ea01edc333dff77bf0822729be2ae14d1d
step-capstone/src/Components/TravelObject.js
step-capstone/src/Components/TravelObject.js
import React from 'react' export default function TravelObject(props) { let content = null; switch(props.type) { case 'event': content = <div>Event!</div>; break; case 'flight': content = <div>Flight!</div> break; case 'hotel': content = <div>Hotel!</div> break; default: console.log("Invalid type"); break; } return ( <div> {content} <button onClick={() => console.log("editing")}>Edit</button> <button onClick={() => console.log("deleting")}>Delete</button> </div> ) }
import React from 'react' import Flight from './Flight' export default function TravelObject(props) { let content = null; switch(props.type) { case 'event': content = <div>Event!</div>; break; case 'flight': content = <Flight /> break; case 'hotel': content = <div>Hotel!</div> break; default: console.log("Invalid type"); break; } return ( <div> {content} <button onClick={() => console.log("editing")}>Edit</button> <button onClick={() => console.log("deleting")}>Delete</button> </div> ) }
Replace dummy code for flight case with flight component
Replace dummy code for flight case with flight component
JavaScript
apache-2.0
googleinterns/step98-2020,googleinterns/step98-2020
fd1791e92808b2e5b8cf69fc4af7c2a780c76a0d
gulp/config.js
gulp/config.js
var historyApiFallback = require("connect-history-api-fallback"); var dest = "./build"; var src = './src'; module.exports = { browserSync: { server: { // Serve up our build folder baseDir: dest, middleware: [historyApiFallback()] } }, js: { src: src + '/js/app.js' }, templates: { src: src + '/templates/**/*.html' }, css: { src: src + "/js/vendor/highlight.js/styles/docco.css", dest: dest }, sass: { src: src + "/sass/**/*.scss", dest: dest, settings: { outputStyle: "compressed", indentedSyntax: false, // Disable .sass syntax! imagePath: 'img' // Used by the image-url helper } }, images: { src: src + "/img/**", dest: dest + "/img" }, markup: { src: src + "/{index.html,favicon.ico,/platform/**,/resources/**}", dest: dest }, browserify: { bundleConfigs: [{ entries: src + '/js/app.js', dest: dest, outputName: 'worker_ui.js', extensions: [], transform: ["ractivate"] }] }, production: { cssSrc: dest + '/*.css', jsSrc: dest + '/*.js', dest: dest } };
var historyApiFallback = require("connect-history-api-fallback"); var dest = "./build"; var src = './src'; module.exports = { browserSync: { server: { // Serve up our build folder baseDir: dest, middleware: [historyApiFallback()] } }, js: { src: src + '/js/app.js' }, templates: { src: src + '/templates/**/*.html' }, css: { src: src + "/js/vendor/highlight.js/styles/docco.css", dest: dest }, sass: { src: src + "/sass/**/*.scss", dest: dest, settings: { outputStyle: "compressed", indentedSyntax: false, // Disable .sass syntax! imagePath: 'img' // Used by the image-url helper } }, images: { src: src + "/img/**", dest: dest + "/img" }, markup: { src: src + "/{index.html,debug.html,favicon.ico,/platform/**,/resources/**}", dest: dest }, browserify: { bundleConfigs: [{ entries: src + '/js/app.js', dest: dest, outputName: 'worker_ui.js', extensions: [], transform: ["ractivate"] }] }, production: { cssSrc: dest + '/*.css', jsSrc: dest + '/*.js', dest: dest } };
Add debug.html to build script
Add debug.html to build script
JavaScript
apache-2.0
coolcrowd/worker-ui,coolcrowd/worker-ui
304b03a879b0b427214b90e7ae9f0d576876e954
app/javascript/app/utils/redux.js
app/javascript/app/utils/redux.js
import isFunction from 'lodash/isFunction'; import { createAction as CA, handleActions as handle } from 'redux-actions'; // matches action names with reducers and returns an object to // be used with handleActions // passes all state as a third argument export const bindActionsToReducers = (actions, reducerList, appState) => Object.keys(actions).reduce((result, k) => { const c = {}; const name = actions[k]; c[name] = (state, action) => reducerList.reduce((r, reducer) => { if (!reducer.hasOwnProperty(k) || !isFunction(reducer[k])) return r; return reducer[k](r, action, appState); }, state); return { ...result, ...c }; }, {}); export const handleActions = (key, actions, reducers, state) => handle(bindActionsToReducers(actions, [reducers], state), state[key] || {}); // our own actioncreattor that can handle thunks // fires the action as init // and leaves resolve/reject to the thunk creator export const createThunkAction = (name, thunkAction) => { if (!thunkAction) return CA(name); thunkAction.toString = () => name; return thunkAction; };
import isFunction from 'lodash/isFunction'; import { createAction as CA, handleActions as handle } from 'redux-actions'; // matches action names with reducers and returns an object to // be used with handleActions // passes all state as a third argument export const bindActionsToReducers = (actions, reducerList) => Object.keys(actions).reduce((result, k) => { const c = {}; const name = actions[k]; c[name] = (state, action) => reducerList.reduce((r, reducer) => { const hasProperty = Object.prototype.hasOwnProperty.call(reducer, k); if (!hasProperty || !isFunction(reducer[k])) return r; return reducer[k](r, action); }, state); return { ...result, ...c }; }, {}); export const handleActions = (key, actions, reducers, state) => handle(bindActionsToReducers(actions, [reducers], state), state[key] || {}); // our own actioncreattor that can handle thunks // fires the action as init // and leaves resolve/reject to the thunk creator export const createThunkAction = (name, thunkAction) => { if (!thunkAction) return CA(name); thunkAction.toString = () => name; // eslint-disable-line return thunkAction; };
Stop passing all store in each action
Stop passing all store in each action
JavaScript
mit
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
e3b80778bf188ac19ab4d698621864d52819085f
app/js/util/arethusa_generator.js
app/js/util/arethusa_generator.js
"use strict"; // Generators for Arethusa code for things such as // - useful directives function ArethusaGenerator() { this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) { return { restrict: 'A', link: function(scope, element, attrs) { function toggle() { scope.$apply(service.toggle()); } var parent = element.parent(); trsl(trslKey, function(translation) { parent.attr('title', translation); }); element.bind('click', toggle); }, template: template }; }; } var arethusaGenerator = new ArethusaGenerator(); var aG = arethusaGenerator;
"use strict"; // Generators for Arethusa code for things such as // - useful directives function ArethusaGenerator() { this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) { return { restrict: 'A', compile: function(element) { var parent = element.parent(); function updateTitle(translation) { parent.attr('title', translation); } return function link(scope, element, attrs) { function toggle() { scope.$apply(service.toggle()); } trsl(trslKey, updateTitle); element.bind('click', toggle); }; }, template: template }; }; } var arethusaGenerator = new ArethusaGenerator(); var aG = arethusaGenerator;
Refactor panel triggers for speed
Refactor panel triggers for speed
JavaScript
mit
latin-language-toolkit/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa
d2f251b8a375ab011688d740113b8c09c79c5612
src/ex.js
src/ex.js
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Config from "./config.js"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get Config() { return Config; } static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } static initialize() { EX.config = new Config(); EX.config.enableHeader && UI.Header.initialize(); EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; jQuery(function () { try { EX.initialize(); } catch(e) { $("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`); throw e; } });
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Config from "./config.js"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get Config() { return Config; } static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } static initialize() { EX.config = new Config(); EX.config.enableHeader && UI.Header.initialize(); EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; window.moment = moment; jQuery(function () { try { EX.initialize(); } catch(e) { $("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`); throw e; } });
Make moment global for debugging.
[fix] Make moment global for debugging.
JavaScript
mit
evazion/danbooru-ex,evazion/danbooru-ex
0ae0be0b2a0124d19c73f3d1814d92470b1f4960
src/send.js
src/send.js
import { busy, scheduleRetry } from './actions'; import { JS_ERROR } from './constants'; import type { Config, OfflineAction, ResultAction } from './types'; const complete = ( action: ResultAction, success: boolean, payload: {} ): ResultAction => ({ ...action, payload, meta: { ...action.meta, success, completed: true } }); const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => { const metadata = action.meta.offline; dispatch(busy(true)); return config .effect(metadata.effect, action) .then(result => { const commitAction = metadata.commit || config.defaultCommit; try { dispatch(complete(commitAction, true, result)); } catch (e) { dispatch(complete({ type: JS_ERROR, payload: e }, false)); } }) .catch(error => { const rollbackAction = metadata.rollback || config.defaultRollback; // discard if (config.discard(error, action, retries)) { dispatch(complete(rollbackAction, false, error)); return; } const delay = config.retry(action, retries); if (delay != null) { dispatch(scheduleRetry(delay)); return; } dispatch(complete(rollbackAction, false, error)); }); }; export default send;
import { busy, scheduleRetry } from './actions'; import { JS_ERROR } from './constants'; import type { Config, OfflineAction, ResultAction } from './types'; const complete = ( action: ResultAction, success: boolean, payload: {} ): ResultAction => ({ ...action, payload, meta: { ...action.meta, success, completed: true } }); const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => { const metadata = action.meta.offline; dispatch(busy(true)); return config .effect(metadata.effect, action) .then(result => { const commitAction = metadata.commit || { ...config.defaultCommit, meta: { ...config.defaultCommit.meta, offlineAction: action } }; try { dispatch(complete(commitAction, true, result)); } catch (e) { dispatch(complete({ type: JS_ERROR, payload: e }, false)); } }) .catch(error => { const rollbackAction = metadata.rollback || { ...config.defaultRollback, meta: { ...config.defaultRollback.meta, offlineAction: action } }; // discard if (config.discard(error, action, retries)) { dispatch(complete(rollbackAction, false, error)); return; } const delay = config.retry(action, retries); if (delay != null) { dispatch(scheduleRetry(delay)); return; } dispatch(complete(rollbackAction, false, error)); }); }; export default send;
Add offline action to default commit and rollback actions
Add offline action to default commit and rollback actions
JavaScript
mit
redux-offline/redux-offline,jevakallio/redux-offline
7f68b7980f1af0e5e2ac8f19022bb3b2e71675cb
src/api/link.js
src/api/link.js
import props from './props'; function getValue (elem) { const type = elem.type; if (type === 'checkbox' || type === 'radio') { return elem.checked ? elem.value || true : false; } return elem.value; } export default function (elem, target) { return (e) => { // We fallback to checking the composed path. Unfortunately this behaviour // is difficult to impossible to reproduce as it seems to be a possible // quirk in the shadydom polyfill that incorrectly returns null for the // target but has the target as the first point in the path. // TODO revisit once all browsers have native support. const localTarget = target || e.target || e.composedPath()[0]; const value = getValue(localTarget); const localTargetName = e.target.name || 'value'; if (localTargetName.indexOf('.') > -1) { const parts = localTargetName.split('.'); const firstPart = parts[0]; const propName = parts.pop(); const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem); obj[propName || e.target.name] = value; props(elem, { [firstPart]: elem[firstPart] }); } else { props(elem, { [localTargetName]: value }); } }; }
import props from './props'; function getValue (elem) { const type = elem.type; if (type === 'checkbox' || type === 'radio') { return elem.checked ? elem.value || true : false; } return elem.value; } export default function (elem, target) { return (e) => { // We fallback to checking the composed path. Unfortunately this behaviour // is difficult to impossible to reproduce as it seems to be a possible // quirk in the shadydom polyfill that incorrectly returns null for the // target but has the target as the first point in the path. // TODO revisit once all browsers have native support. const localTarget = e.target || e.composedPath()[0]; const value = getValue(localTarget); const localTargetName = target || localTarget.name || 'value'; if (localTargetName.indexOf('.') > -1) { const parts = localTargetName.split('.'); const firstPart = parts[0]; const propName = parts.pop(); const obj = parts.reduce((prev, curr) => (prev && prev[curr]), elem); obj[propName || e.target.name] = value; props(elem, { [firstPart]: elem[firstPart] }); } else { props(elem, { [localTargetName]: value }); } }; }
Fix issue only exposed by certain situations with the shadydom polyfill.
fix: Fix issue only exposed by certain situations with the shadydom polyfill.
JavaScript
mit
chrisdarroch/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs
7de0c1782ac690461693aa308364ac3aa996712a
tests/e2e/utils/activate-amp-and-set-mode.js
tests/e2e/utils/activate-amp-and-set-mode.js
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. * */ export const allowedAmpModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAmpAndSetMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( Object.keys( allowedAmpModes ) ).toContain( mode ); // Active AMP and set the passed mode. await activatePlugin( 'amp' ); await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForSelector( '#setting-error-settings_updated' ); await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } ); };
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. * */ export const allowedAmpModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAmpAndSetMode = async ( mode ) => { await activatePlugin( 'amp' ); await setAMPMode( mode ); }; /** * Set AMP Mode * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const setAMPMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( Object.keys( allowedAmpModes ) ).toContain( mode ); // Set the AMP mode await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForSelector( '#setting-error-settings_updated' ); await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } ); };
Add helper to change AMP mode.
Add helper to change AMP mode.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
41460b6e776e8d3b6cac28c63a4ce4b73541fb27
require-best.js
require-best.js
module.exports = function(moduleName) { var majorVersion = parseInt(process.version.match(/^v(\d+)/) || [])[1] if (majorVersion >= 8) { return require('./src/' + moduleName) } else { return require('./node6/' + moduleName) } }
module.exports = function(moduleName) { var majorVersion = parseInt((process.version.match(/^v(\d+)/) || [])[1]) if (majorVersion >= 8) { return require('./src/' + moduleName) } else { return require('./node6/' + moduleName) } }
Fix using "native" code on node 8+
Fix using "native" code on node 8+
JavaScript
mit
BaronaGroup/migsi,BaronaGroup/migsi
dc390d2733adb5c57866626125a04f1a6e9b5da3
js/cooldown.js
js/cooldown.js
var seconds_match = /^(\d)*s$/; function Cooldown(frames) { frames = frames || 10 if ($.type(frames) == "string") { var seconds = frames.match(seconds_match) if (seconds) { frames = seconds[1] * runtime.fps } else { frames = parseInt(frames) } } var total = frames var result = false this.set_result = function(new_result) { result = new_result } this.frame = function() { frames-- if (frames <= 0) return result return this } this.get_remaining = function() { return total - frames } this.get_pctdone = function() { return (total - frames) / total } }
var seconds_match = /^(\d)*s$/; function Cooldown(frames, inital_result) { frames = frames || 10 if ($.type(frames) == "string") { var seconds = frames.match(seconds_match) if (seconds) { frames = seconds[1] * runtime.fps } else { frames = parseInt(frames) } } var total = frames var result = false this.set_result = function(new_result) { result = new_result } if ($.isFunction(inital_result)) this.set_result(inital_result) this.frame = function() { frames-- if (frames <= 0) return result return this } this.reset = function() { frames = total } this.is_done = function() { return frames >= total } this.get_remaining = function() { return total - frames } this.get_pctdone = function() { return (total - frames) / total } }
Add a shortcut to set the result function in Cooldown
Add a shortcut to set the result function in Cooldown
JavaScript
artistic-2.0
atrodo/fission_engine,atrodo/fission_engine
1d6be34ff63350aa3e3c0cdeb163d653bec307dc
js/services.js
js/services.js
angular.module('services', []) .filter('file', function () { return function (input) { return input.split(' ').join('_').toLowerCase() } }) .factory('responsive', function () { var resizeTimer return { run: function (apply, main, input, output) { main(input, output) $(window).on('resize', function(e) { clearTimeout(resizeTimer) resizeTimer = setTimeout(function () { main(input, output) apply() }, 100) }) } } })
angular.module('services', []) .directive('done', ['$parse', function($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var fn = $parse(attrs.done) if (scope.$last){ scope.done() } } } }]) .filter('file', function () { return function (input) { return input.split(' ').join('_').toLowerCase() } }) .filter('first', function () { return function (input) { var output = input.split(': ') return output[0] } }) .filter('second', function () { return function (input) { var output = input.split(': ') return output[1] } }) .filter('info', function () { return function (input) { return input.split(', ').join(',\ \ ') } }) .factory('responsive', function () { var resizeTimer return { run: function (apply, init, main, input, output) { init(main, input, output) $(window).on('resize', function(e) { window.requestAnimationFrame(function () { main(input, output) apply() }) }) } } })
Add filter/directives for about page
Add filter/directives for about page
JavaScript
mit
Cwejman/martina,Cwejman/martina
6594bafa373173d987271d51833bcbb45ea4cda1
js/settings.js
js/settings.js
var possibleStates = [ 'P,Pipeline', 'R,Request Evaluation', 'Rm,Requirements', 'C,Concept', 'D,Development', 'Dy,Deployment', 'L,Live' ]; var possible_colors = 4;
var possibleStates = [ 'B,Backlog', 'P,Pending ', 'Cs,Current Sprint', 'D,Doing', 'Bl,Blocked', 'Q,QA', 'L,Live' ]; var possible_colors = 4;
Set up more common Kanban columns
Set up more common Kanban columns
JavaScript
mit
rapsli/simple-kanban,rapsli/simple-kanban
5de4f9dde7d1100e4db600c55748278c003df004
lib/profile.js
lib/profile.js
/** * Parse profile. * * @param {Object|String} json * @return {Object} * @api private */ exports.parse = function(json) { if ('string' == typeof json) { json = JSON.parse(json); } var profile = {}; profile.id = json.iupi; profile.email = json.email; return profile; };
/** * Parse profile. * * @param {Object|String} json * @return {Object} * @api private */ exports.parse = function(json) { if ('string' === typeof json) { json = JSON.parse(json); } var profile = {}; profile.id = json.iupi; profile.email = json.email; return profile; };
Improve code quality by change '==' into '==='
Improve code quality by change '==' into '==='
JavaScript
mit
poliveira89/passport-identityua,poliveira89/passport-identityua
a3aff6a41a08614ba68fb590aefbc6e2cb5067a4
routers/download/constants.js
routers/download/constants.js
const ALLOWED_CSV_FIELD_PATHS = [ 'ids.GB-CHC', 'ids.charityId', 'name', 'contact.email', 'contact.person', 'contact.postcode', 'contact.address', 'contact.geo.longitude', 'contact.geo.latitude', 'people.volunteers', 'people.employees', 'people.trustees', 'activities', 'website', 'income.annual', 'areaOfBenefit', 'causes', 'beneficiaries', 'operations', ] const FY_END_YEARS = [ 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, ] module.exports = { ALLOWED_CSV_FIELD_PATHS, FY_END_YEARS, }
const ALLOWED_CSV_FIELD_PATHS = [ 'ids.GB-CHC', 'ids.charityId', 'name', 'contact.address', 'contact.email', 'contact.geo.latitude', 'contact.geo.longitude', 'contact.person', 'contact.phone', 'contact.postcode', 'people.volunteers', 'people.employees', 'people.trustees', 'activities', 'website', 'income.annual', 'areaOfBenefit', 'causes', 'beneficiaries', 'operations', 'objectives', ] const FY_END_YEARS = [ 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, ] module.exports = { ALLOWED_CSV_FIELD_PATHS, FY_END_YEARS, }
Allow downloading objectives & phone
Allow downloading objectives & phone
JavaScript
mit
tithebarn/charity-base,tithebarn/open-charities,tythe-org/charity-base-api
3cd2d32ca72775777962a912fe539cbb540274b0
delay.safariextension/start.js
delay.safariextension/start.js
(function () { "use strict"; var settings, display; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; if (settings.blacklist.indexOf(window.location.hostname) !== -1) { display = document.documentElement.style.display; document.documentElement.style.display = 'none'; window.setTimeout(function () { document.documentElement.style.display = display; }, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter))); } } }, false); }());
(function () { "use strict"; var settings, visibility; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; if (settings.blacklist.indexOf(window.location.hostname) !== -1) { visibility = document.documentElement.style.visibility; document.documentElement.style.visibility = 'hidden'; window.setTimeout(function () { document.documentElement.style.visibility = visibility; }, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter))); } } }, false); }());
Switch from "display:none" to "visibility:hidden".
Switch from "display:none" to "visibility:hidden". That way the page layout won't be affected but it will still be hidden.
JavaScript
mit
tfausak/delay
1200f59759531802d41cf1674d0a22ccaec21ca8
examples/src/examples/YearCalendar.js
examples/src/examples/YearCalendar.js
import React from 'react'; import DayPicker from '../../../src'; import '../../../src/style.css'; import '../styles/year.css'; export default class YearCalendar extends React.Component { constructor(props) { super(props); this.showPrevious = this.showPrevious.bind(this); this.showNext = this.showNext.bind(this); } state = { year: (new Date()).getFullYear(), }; showPrevious() { this.setState({ year: this.state.year - 1, }); } showNext() { this.setState({ year: this.state.year + 1, }); } render() { const { year } = this.state; return ( <div className="YearCalendar"> <h1> <a onClick={ this.showPrevious }>{ year - 1 }</a> { year } <a onClick={ this.showNext }>{ year + 1 }</a> </h1> <DayPicker canChangeMonth={ false } initialMonth={ new Date(year, 0, 1) } numberOfMonths={ 12 } /> </div> ); } }
import React from 'react'; import DayPicker from '../../../src'; import '../../../src/style.css'; import '../styles/year.css'; export default class YearCalendar extends React.Component { constructor(props) { super(props); this.showPrevious = this.showPrevious.bind(this); this.showNext = this.showNext.bind(this); } state = { year: (new Date()).getFullYear(), }; showPrevious() { this.setState({ year: this.state.year - 1, }); } showNext() { this.setState({ year: this.state.year + 1, }); } render() { const { year } = this.state; return ( <div className="YearCalendar"> <h1> <a onClick={ this.showPrevious }>{ year - 1 }</a> { year } <a onClick={ this.showNext }>{ year + 1 }</a> </h1> <DayPicker canChangeMonth={ false } month={ new Date(year, 0, 1) } numberOfMonths={ 12 } /> </div> ); } }
Use month instead of initialMonth
Use month instead of initialMonth
JavaScript
mit
saenglert/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker
cbd505bf2749c62d6baba3e9278a92143b1fc255
example/build.js
example/build.js
var thumbsup = require('../src/index'); thumbsup.build({ // the input folder // with all photos/videos input: 'example/media', // the output folder // for the thumbnails and static pages output: 'example/website', // website title // the first word will be in color title: 'Photo gallery', // main site color // for the title and links css: null, // size of the square thumbnails // in pixels thumbSize: 120, // size of the "fullscreen" view // in pixels largeSize: 400 });
var thumbsup = require('../src/index'); thumbsup.build({ // the input folder // with all photos/videos input: 'example/media', // the output folder // for the thumbnails and static pages output: '_site', // website title // the first word will be in color title: 'Photo gallery', // main site color // for the title and links css: null, // size of the square thumbnails // in pixels thumbSize: 120, // size of the "fullscreen" view // in pixels largeSize: 400 });
Build the example site into _site (published as Github pages)
Build the example site into _site (published as Github pages)
JavaScript
mit
kremlinkev/thumbsup,thumbsup/node-thumbsup,dravenst/thumbsup,rprieto/thumbsup,dravenst/thumbsup,thumbsup/thumbsup,kremlinkev/thumbsup,thumbsup/thumbsup,thumbsup/node-thumbsup,rprieto/thumbsup,thumbsup/node-thumbsup
c5b6ac00c1d05bc69f4dcbd9f999baf43421f0fe
tasks/styles.js
tasks/styles.js
'use strict'; var sass = require('gulp-sass'); var bourbon = require('node-bourbon'); var rev = require('gulp-rev'); var minify = require('gulp-minify-css'); /* compile sass with bourbon */ module.exports = function (stream) { return stream .pipe(sass({ includePaths: bourbon.includePaths })) .pipe(env.not('development', rev())) .pipe(env.not('development', minify())); };
'use strict'; var sass = require('gulp-sass'); var bourbon = require('node-bourbon'); var rev = require('gulp-rev'); var minify = require('gulp-minify-css'); var env = require('../utils/env'); var manifest = require('../utils/manifest'); /* compile sass with bourbon */ module.exports = function (stream) { return stream .pipe(sass({ includePaths: bourbon.includePaths })) .pipe(env.not('development', rev())) .pipe(env.not('development', manifest())) .pipe(env.not('development', minify())); };
Add CSS to asset manifest
Add CSS to asset manifest
JavaScript
mit
bendrucker/gulp-tasks
4a92a6850aa2827cf3d7adf6be530c5329582018
app/assets/javascripts/icons.js
app/assets/javascripts/icons.js
$(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if(gon.gallery[id].aliases !== undefined) { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">β€” No alias β€”</option>'); for(var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide(); } } };
$(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if(gon.gallery[id].aliases !== undefined) { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">β€” No alias β€”</option>'); for(var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide().val(''); } } };
Make sure to reset alias when switching between characters if the new one has no alias
Make sure to reset alias when switching between characters if the new one has no alias
JavaScript
mit
Marri/glowfic,Marri/glowfic,Marri/glowfic,Marri/glowfic
18264d202fb2a48c3f8952246708af1b5e941fbf
app/assets/javascripts/icons.js
app/assets/javascripts/icons.js
/* global gon */ $(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); $('.gallery-minmax').click(function() { var elem = $(this); var id = elem.data('id'); if (elem.html().trim() === '-') { $('#gallery' + id).hide(); $('#gallery-tags-' + id).hide(); elem.html('+'); } else { $('#gallery' + id).show(); $('#gallery-tags-' + id).show(); elem.html('-'); } }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if (typeof gon.gallery[id].aliases !== "undefined") { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">β€” No alias β€”</option>'); for (var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide().val(''); } } }
/* global gon */ $(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if (typeof gon.gallery[id].aliases !== "undefined") { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">β€” No alias β€”</option>'); for (var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide().val(''); } } }
Remove dead duplicate code for gallery minmax
Remove dead duplicate code for gallery minmax
JavaScript
mit
Marri/glowfic,Marri/glowfic,Marri/glowfic,Marri/glowfic
bd223902c3d3f4bc07257ec4c49a540cfd654a95
test/feature.js
test/feature.js
var assert = require('assert'); var Feature = require('../feature'); describe('Feature', function () { describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
Use the database seeds from the Feature spec
Use the database seeds from the Feature spec
JavaScript
mit
nickmccurdy/rose,nicolasmccurdy/rose,nicolasmccurdy/rose,nickmccurdy/rose