commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
3d2e011bc3efd28f6ddaa2dde04a76abeabf3574
website/src/app/models/api/public-comments-api.service.js
website/src/app/models/api/public-comments-api.service.js
class PublicCommentsAPIService { constructor(publicAPIRoute) { this.publicAPIRoute = publicAPIRoute; } getCommentsListFor(targetId) { return this.publicAPIRoute('comments').get({target: targetId}).then( (rv) => { rv = rv.plain(); return rv.val; } ); } } angular.module('materialscommons').service('publicCommentsAPI', PublicCommentsAPIService);
class PublicCommentsAPIService { constructor(Restangular) { this.Restangular = Restangular; } getCommentsListFor(datasetId) { return this.Restangular.one('v3').one('getCommentsForPublishedDataset').customPOST({dataset_id: datasetId}).then( (ds) => ds.plain().data ); } } angular.module('materialscommons').service('publicCommentsAPI', PublicCommentsAPIService);
Switch to actionhero based API
Switch to actionhero based API
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
1274571cbf950f85158974cd575b717753a1db3e
index.js
index.js
var yarn = require('yarn/lib/lockfile/wrapper.js') var express = require('express') var bodyParser = require('body-parser') var app = express() var port = process.env.PORT || 5000; app.use(bodyParser.text()); app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.post("/parse/", bodyParser.text({type: '*/*'}), function(req,res){ var dependencies = yarn.parse(req.body) var deps = [] Object.keys(dependencies).forEach((dep) => { deps.push({ name: dep.split('@')[0], version: dependencies[dep].version, type: 'runtime' }) }) res.json(deps) }); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
var yarn = require('yarn/lib/lockfile/wrapper.js') var express = require('express') var bodyParser = require('body-parser') var app = express() var port = process.env.PORT || 5000; app.use(bodyParser.text()); app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.use(express.bodyParser({limit: '5mb'})); app.post("/parse/", bodyParser.text({type: '*/*'}), function(req,res){ var dependencies = yarn.parse(req.body) var deps = [] Object.keys(dependencies).forEach((dep) => { deps.push({ name: dep.split('@')[0], version: dependencies[dep].version, type: 'runtime' }) }) res.json(deps) }); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
Allow up to 5mb uploads
Allow up to 5mb uploads
JavaScript
agpl-3.0
librariesio/yarn-parser
ffa9d2d83ac39ffbff46036c1c53045f6de488a0
services/api/src/routes/index.js
services/api/src/routes/index.js
// @flow const express = require('express'); const statusRoute = require('./status'); const keysRoute = require('./keys'); const graphqlRoute = require('./graphql'); /* :: import type { $Request, $Response } from 'express'; */ function createRouter() { const router = new express.Router(); // Redirect GET requests on "/" to the status route. router.get('/', (req /* : $Request */, res /* : $Response */) => res.redirect('/status'), ); // Fetch the current api status. router.get('/status', ...statusRoute); // Return keys of all clients from clients.yaml. router.post('/keys', ...keysRoute); // Enable graphql requests. router.all('/graphql', ...graphqlRoute); return router; } module.exports = createRouter;
// @flow const express = require('express'); const statusRoute = require('./status'); const keysRoute = require('./keys'); const graphqlRoute = require('./graphql'); /* :: import type { $Request, $Response } from 'express'; */ function createRouter() { const router = new express.Router(); // Redirect GET requests on "/" to the status route. router.get('/', (req /* : $Request */, res /* : $Response */) => res.redirect('/status'), ); // Fetch the current api status. router.get('/status', ...statusRoute); // Return keys of all customers router.post('/keys', ...keysRoute); // Enable graphql requests. router.all('/graphql', ...graphqlRoute); return router; } module.exports = createRouter;
Update `clients` to `customer` in API routes
Update `clients` to `customer` in API routes
JavaScript
apache-2.0
amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon
115438d4ea6dde1eeaf68054b8f7606a28e13009
challenges-completed.js
challenges-completed.js
var ipc = require('ipc') var userData = require('./user-data.js') document.addEventListener('DOMContentLoaded', function (event) { var data = userData.getData() updateIndex(data.contents) ipc.on('confirm-clear-response', function (response) { if (response === 1) return else clearAllChallenges() }) var clearAllButton = document.getElementById('clear-all-challenges') clearAllButton.addEventListener('click', function () { for (var chal in data) { if (data[chal].completed) { data[chal].completed = false var completedElement = '#' + chal + ' .completed-challenge-list' document.querySelector(completedElement).remove() } } userData.updateData(data, function (err) { // this takes in a challenge, which you're not doing if (err) return console.log(err) }) }) function updateIndex (data) { for (var chal in data) { if (data[chal].completed) { var currentText = document.getElementById(chal).innerHTML var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>" document.getElementById(chal).innerHTML = completedText + ' ' + currentText } } } })
var ipc = require('ipc') var fs = require('fs') var userData = require('./user-data.js') document.addEventListener('DOMContentLoaded', function (event) { var data = userData.getData() var clearAllButton = document.getElementById('clear-all-challenges') updateIndex(data.contents) ipc.on('confirm-clear-response', function (response) { if (response === 1) return else clearAllChallenges(data) }) clearAllButton.addEventListener('click', function () { ipc.send('confirm-clear') }) function updateIndex (data) { for (var chal in data) { if (data[chal].completed) { var currentText = document.getElementById(chal).innerHTML var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>" document.getElementById(chal).innerHTML = completedText + ' ' + currentText } } } }) function clearAllChallenges (data) { for (var chal in data.contents) { if (data.contents[chal].completed) { data.contents[chal].completed = false var completedElement = '#' + chal + ' .completed-challenge-list' document.querySelector(completedElement).remove() } } fs.writeFileSync(data.path, JSON.stringify(data.contents, null, 2)) }
Fix all the bugs in writing data and confirming clear
Fix all the bugs in writing data and confirming clear
JavaScript
bsd-2-clause
dice/git-it-electron,countryoven/git-it-electron,countryoven/git-it-electron,dice/git-it-electron,rets5s/git-it-electron,IonicaBizauKitchen/git-it-electron,jlord/git-it-electron,IonicaBizauKitchen/git-it-electron,countryoven/git-it-electron,shiftkey/git-it-electron,rets5s/git-it-electron,countryoven/git-it-electron,countryoven/git-it-electron,dice/git-it-electron,dice/git-it-electron,dice/git-it-electron,IonicaBizauKitchen/git-it-electron,dice/git-it-electron,countryoven/git-it-electron,IonicaBizauKitchen/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron,dice/git-it-electron,rets5s/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,rets5s/git-it-electron,countryoven/git-it-electron,IonicaBizauKitchen/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,IonicaBizauKitchen/git-it-electron,rets5s/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,rets5s/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,IonicaBizauKitchen/git-it-electron,rets5s/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron
1009736eb9141fec58a34584b6b8764e92a3967e
config/app.json.js
config/app.json.js
module.exports = { "allow_create_new_accounts" : true, "send_emails" : false, "application_sender_email" : process.env.SENDER_EMAIL || "email@test.com", // transports email via SMTP "email_smtp_transporter" : { "host" : process.env.MAILGUN_SMTP_SERVER || "localhost", "port" : process.env.MAILGUN_SMTP_PORT || 25, "auth" : { "user" : process.env.MAILGUN_SMTP_LOGIN || "user", "pass" : process.env.MAILGUN_SMTP_PASSWORD || "pass" } }, // transports emails via Mailgun REST API (which is 3x faster than SMTP) // precedes email_smtp_transporter if api_key and domain are set "email_mailgun_transporter" : { auth: { api_key: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN } }, "crypto_secret" : process.env.CRYPTO_SECRET || "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_", "application_domain" : process.env.APPLICATION_DOMAIN || "http://app.timeoff.management", "promotion_website_domain" : process.env.PROMOTION_WEBSITE_DOMAIN || "http://timeoff.management" }
module.exports = { "allow_create_new_accounts" : true, "send_emails" : false, "application_sender_email" : process.env.SENDER_EMAIL || "email@test.com", // transports email via SMTP "email_smtp_transporter" : { "host" : process.env.SMTP_SERVER || "localhost", "port" : process.env.SMTP_PORT || 25, "auth" : { "user" : process.env.SMTP_LOGIN || "user", "pass" : process.env.SMTP_PASSWORD || "pass" } }, // transports emails via Mailgun REST API (which is 3x faster than SMTP) // precedes email_smtp_transporter if api_key and domain are set "email_mailgun_transporter" : { auth: { api_key: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN } }, "crypto_secret" : process.env.CRYPTO_SECRET || "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_", "application_domain" : process.env.APPLICATION_DOMAIN || "http://app.timeoff.management", "promotion_website_domain" : process.env.PROMOTION_WEBSITE_DOMAIN || "http://timeoff.management" }
Use generic names for SMTP env variables
Use generic names for SMTP env variables
JavaScript
mit
YulioTech/timeoff,YulioTech/timeoff
513507afcb36ad4d56bcc89596bd9252774fca2b
src/replace_country_code.js
src/replace_country_code.js
export default function replaceCountryCode( currentSelectedCountry, nextSelectedCountry, number, ) { const dialCodeRegex = RegExp(`^(${currentSelectedCountry.dialCode})`) const newNumber = number.replace(dialCodeRegex, nextSelectedCountry.dialCode) // if we couldn't find any replacement, just attach the new country's dial code at the front if (newNumber === number) { return nextSelectedCountry.dialCode + number } return newNumber }
export default function replaceCountryCode( currentSelectedCountry, nextSelectedCountry, number, ) { const dialCodeRegex = RegExp(`^(${currentSelectedCountry.dialCode})`) const newNumber = number.replace(dialCodeRegex, nextSelectedCountry.dialCode) return newNumber }
Remove automatic country code appending
Remove automatic country code appending
JavaScript
mit
mukeshsoni/react-telephone-input,mukeshsoni/react-telephone-input
900ef0236d288e29ff715030f53db78c13afa6c1
src/cli/cli.js
src/cli/cli.js
#! /usr/bin/env node import yargs from 'yargs' import { init, change, add, deploy } from './cmds' const argv = yargs.usage("$0 command") .command("init", "create a new generic website") .command("change <field>", "update any field with a new value") .command("add <field>", "add a new key and value") .command("deploy", "deploy your website") .demand(1, "must provide a valid command") .help("h") .alias("h", "help") .argv switch (argv._[0]) { case 'init': init(); break case 'change': change(argv.field); break case 'add': add(argv.field); break case 'deploy': deploy(); break }
#! /usr/bin/env node import yargs from 'yargs' import { init, change, add, deploy } from './cmds' const argv = yargs.usage("$0 command") .command("init", "create a new generic website") .command("change <field>", "update any field with a new value") .command("add", "add a new key and value", (yargs) => ( yargs .option("s", {alias: "section", describe: "add a section"}) .option("f", {alias: "field", describe: "provide a field name"}) .demandOption(['f'], "Please provide a field name, it is required.") .help("h").alias("h", "help") )) .command("deploy <location>", "deploy your website") .demand(1, "must provide a valid command") .help("h") .alias("h", "help") .argv switch (argv._[0]) { case 'init': init(); break case 'change': change(argv.field); break case 'add': console.log(argv); add(argv.field); break case 'deploy': deploy(); break }
Add section options for add cmd
Add section options for add cmd
JavaScript
mpl-2.0
Quite-nice/generic-website
1a8b13fd53e23cd069e792476854e5b9af20f19a
site/gulpfile.js
site/gulpfile.js
var gulp = require('gulp'); var watch = require('gulp-watch'); var uglify = require('gulp-uglify'); var print = require('gulp-print'); var tsc = require('gulp-typescript-compiler'); gulp.task('typescript', function() { return gulp.src( [ '*.ts', '**/*.ts' ] ) .pipe( print() ) .pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, logErrors: true } ) ) .pipe( print() ) .pipe(uglify()); }); // Default Task gulp.task('default', ['typescript']);
var gulp = require('gulp'); var watch = require('gulp-watch'); var uglify = require('gulp-uglify'); var print = require('gulp-print'); var tsc = require('gulp-typescript-compiler'); gulp.task('ts_server', function() { return gulp.src( [ '*.ts', '**/*.ts', '!./public/**/*.ts', '!./node_modules/**/*.ts' ] ) .pipe( print() ) .pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, logErrors: true } ) ) .pipe(uglify()); }); gulp.task('ts_client', function() { return gulp.src( [ './public/**/*.ts' ] ) .pipe( print() ) .pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, logErrors: true } ) ) .pipe(uglify()); }); // Default Task gulp.task( 'default', ['ts_server','ts_client'] );
Split tasks for client-side and server-side typescript files.
Split tasks for client-side and server-side typescript files. Signed-off-by: Michele Ursino <0d7cbec952c33d7c21e19d50988899883a4c91e0@amilink.com>
JavaScript
mit
micurs/relax.js,micurs/relax.js,micurs/relax.js
7f148da89b0048bf05acbfa8c64a39d0927a4e79
scripts/plugins/markdown-markup.js
scripts/plugins/markdown-markup.js
var minimatch = require('minimatch'); var cheerio = require('cheerio'); var extend = require('extend'); var marked = require('marked'); var config = require('../config/marked'); marked.setOptions(config); function plugin(opts) { return function(files, metalsmith, done) { // Get global metadata. var metadata = metalsmith.metadata(); // Get all file names. Object.keys(files) // Get stylesheets file names. .filter(minimatch.filter('*.html', { matchBase: true })) // Curate content. .forEach(function(file) { // Get file data. var data = files[file]; // Get file HTML. var html = data.contents.toString(); // Prepare HTML for analysis. var $ = cheerio.load(html, { decodeEntities: false }); // Find all <jade> nodes. $('md').each(function(i, el) { // Get the content. var source = $(this).html(); // Merge global metadata with local file data. var options = extend({}, opts, metadata, data); // Render the content as Jade. var html = marked(source); // Replace the <jade> node with the new rendered content. $(this).replaceWith(html); }); // Save updated HTML. data.contents = new Buffer($.html(), 'utf8'); }); done(); } } module.exports = plugin;
var minimatch = require('minimatch'); var cheerio = require('cheerio'); var marked = require('marked'); var config = require('../config/marked'); marked.setOptions(config); function plugin(opts) { return function(files, metalsmith, done) { // Get global metadata. var metadata = metalsmith.metadata(); // Get all file names. Object.keys(files) // Get stylesheets file names. .filter(minimatch.filter('*.html', { matchBase: true })) // Curate content. .forEach(function(file) { // Get file data. var data = files[file]; // Get file HTML. var html = data.contents.toString(); // Prepare HTML for analysis. var $ = cheerio.load(html, { decodeEntities: false }); // Find all <jade> nodes. $('md').each(function(i, el) { // Get the content. var source = $(this).html(); // Render the content as Jade. var html = marked(source); // Replace the <jade> node with the new rendered content. $(this).replaceWith(html); }); // Save updated HTML. data.contents = new Buffer($.html(), 'utf8'); }); done(); } } module.exports = plugin;
Remove unused variable and import
Update: Remove unused variable and import
JavaScript
mit
basham/v4.bash.am,basham/v4.bash.am
35748918436e557248c659c837635daf0af2e7bd
src/store/index.js
src/store/index.js
// Main vuex store import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' import intro from './modules/intro' import weeks from './modules/weeks' import switches from './modules/switches' import models from './modules/models' import * as types from './mutation-types' import branding from 'json!yaml!../../config.yaml' Vue.use(Vuex) const state = { // D3 plot objects timeChart: null, choropleth: null, distributionChart: null, // All the data! data: null, updateTime: null, branding: branding.branding } // mutations const mutations = { [types.SET_DATA] (state, val) { state.data = val.data state.updateTime = val.updateTime }, [types.SET_TIMECHART] (state, val) { state.timeChart = val }, [types.SET_CHOROPLETH] (state, val) { state.choropleth = val }, [types.SET_DISTRIBUTIONCHART] (state, val) { state.distributionChart = val }, [types.SET_BRAND_LOGO] (state, val) { state.branding.logo = val } } export default new Vuex.Store({ state, actions, getters, mutations, modules: { intro, weeks, switches, models } })
// Main vuex store import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' import intro from './modules/intro' import weeks from './modules/weeks' import switches from './modules/switches' import models from './modules/models' import * as types from './mutation-types' import branding from 'json!yaml!../../config.yaml' Vue.use(Vuex) const state = { // D3 plot objects timeChart: null, choropleth: null, distributionChart: null, // All the data! data: null, updateTime: null, branding: Object.assign({logo: ''}, branding.branding) } // mutations const mutations = { [types.SET_DATA] (state, val) { state.data = val.data state.updateTime = val.updateTime }, [types.SET_TIMECHART] (state, val) { state.timeChart = val }, [types.SET_CHOROPLETH] (state, val) { state.choropleth = val }, [types.SET_DISTRIBUTIONCHART] (state, val) { state.distributionChart = val }, [types.SET_BRAND_LOGO] (state, val) { state.branding.logo = val } } export default new Vuex.Store({ state, actions, getters, mutations, modules: { intro, weeks, switches, models } })
Fix issue with branding icon by pre allocating logo slot
Fix issue with branding icon by pre allocating logo slot
JavaScript
mit
reichlab/flusight,reichlab/flusight,reichlab/flusight
71130ab567994962d9083c9dbd8bd69ea4a35d52
src/time-travel.js
src/time-travel.js
require('es6-shim'); const intent = require('./intent'); const makeTime$ = require('./time'); const record = require('./record-streams'); const timeTravelStreams = require('./time-travel-streams'); const timeTravelBarView = require('./view'); const scopedDOM = require('./scoped-dom'); function logStreams (DOM, streams, name = '.time-travel') { const {timeTravelPosition$, playing$} = intent(scopedDOM(DOM, name)); const time$ = makeTime$(playing$, timeTravelPosition$); const recordedStreams = record(streams, time$); const timeTravel = timeTravelStreams(recordedStreams, time$); return { DOM: timeTravelBarView(time$, playing$, recordedStreams), timeTravel }; } module.exports = logStreams;
require('es6-shim'); const intent = require('./intent'); const makeTime$ = require('./time'); const record = require('./record-streams'); const timeTravelStreams = require('./time-travel-streams'); const timeTravelBarView = require('./view'); const scopedDOM = require('./scoped-dom'); function TimeTravel (DOM, streams, name = '.time-travel') { const {timeTravelPosition$, playing$} = intent(scopedDOM(DOM, name)); const time$ = makeTime$(playing$, timeTravelPosition$); const recordedStreams = record(streams, time$); const timeTravel = timeTravelStreams(recordedStreams, time$); return { DOM: timeTravelBarView(time$, playing$, recordedStreams), timeTravel }; } module.exports = TimeTravel;
Rename main function form logStreams to TimeTravel
Rename main function form logStreams to TimeTravel
JavaScript
mit
cyclejs/cycle-time-travel
1fc05c7aeba8dc6fa7217ad438980bd99e5a325b
src/subgenerators/errors.js
src/subgenerators/errors.js
// try block handler exports.TryStatement = (node, anscestors, generator) => { generator.advance("try"); // node.block will always be a BlockStatement generator.generate(node.block, anscestors); node.handler && generator.generate(node.handler, anscestors); node.finalizer && generator.generate(node.finalizer, anscestors); }; // catch (param) body exports.CatchClause = (node, anscestors, generator) => { generator.advance("catch("); generator.generate(node.param, anscestors); generator.advance(")"); // node.body will always be a BlockStatement generator.generate(node.body, anscestors); }; // throw expression exports.ThrowStatement = (node, anscestors, generator) => { generator.advance("throw "); generator.generate(node.argument, anscestors); };
// try block handler exports.TryStatement = (node, anscestors, generator) => { generator.advance("try"); // node.block will always be a BlockStatement generator.generate(node.block, anscestors); node.handler && generator.generate(node.handler, anscestors); node.finalizer && generator.generate(node.finalizer, anscestors); }; // catch (param) body exports.CatchClause = (node, anscestors, generator) => { generator.advance("catch("); generator.generate(node.param, anscestors); generator.advance(")"); // node.body will always be a BlockStatement generator.generate(node.body, anscestors); }; // throw expression exports.ThrowStatement = (node, anscestors, generator) => { generator.advance("throw "); generator.generate(node.argument, anscestors); generator.advance(";"); };
Throw statement should end in a `;`.
Throw statement should end in a `;`.
JavaScript
mit
interlockjs/intergenerator
479f229198bdfcfd3a63d02babdddaa8b2209ccb
server/helpers/customValidators.js
server/helpers/customValidators.js
'use strict' const validator = require('validator') const constants = require('../initializers/constants') const customValidators = { eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid, eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid, isArray: isArray } function eachIsRemoteVideosAddValid (values) { return values.every(function (val) { return validator.isLength(val.name, 1, 50) && validator.isLength(val.description, 1, 50) && validator.isLength(val.magnetUri, 10) && validator.isURL(val.podUrl) && !isNaN(val.duration) && val.duration >= 0 && val.duration < constants.MAXIMUM_VIDEO_DURATION && validator.isLength(val.author, 1, constants.MAXIMUM_AUTHOR_LENGTH) && validator.isDate(val.createdDate) }) } function eachIsRemoteVideosRemoveValid (values) { return values.every(function (val) { return validator.isLength(val.magnetUri, 10) }) } function isArray (value) { return Array.isArray(value) } // --------------------------------------------------------------------------- module.exports = customValidators
'use strict' const validator = require('validator') const constants = require('../initializers/constants') const customValidators = { eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid, eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid, isArray: isArray } function eachIsRemoteVideosAddValid (values) { return values.every(function (val) { return validator.isLength(val.name, 1, 50) && validator.isLength(val.description, 1, 50) && validator.isLength(val.magnetUri, 10) && validator.isURL(val.podUrl) && !isNaN(val.duration) && val.duration >= 0 && val.duration < constants.MAXIMUM_VIDEO_DURATION && validator.isLength(val.author, 1, constants.MAXIMUM_AUTHOR_LENGTH) && validator.isBase64(val.thumbnailBase64) && validator.isByteLength(val.thumbnailBase64, { min: 0, max: 20000 }) && validator.isDate(val.createdDate) }) } function eachIsRemoteVideosRemoveValid (values) { return values.every(function (val) { return validator.isLength(val.magnetUri, 10) }) } function isArray (value) { return Array.isArray(value) } // --------------------------------------------------------------------------- module.exports = customValidators
Add check for the thumbnail in base64 (requests inter pods)
Add check for the thumbnail in base64 (requests inter pods)
JavaScript
agpl-3.0
Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube
7eae22dc3a4a35bdd568a559b569964378196ba9
app/core/forms.js
app/core/forms.js
import includes from 'lodash/includes'; import map from 'lodash/map'; import reduce from 'lodash/reduce'; import keys from 'lodash/keys'; import get from 'lodash/get'; import isEmpty from 'lodash/isEmpty'; export const getFieldsMeta = (schema, getFieldMeta) => { const fieldKeys = keys(schema.fields); const reduceFields = (_fieldKeys, prefix = '') => reduce(_fieldKeys, (result, field) => { const nestedFields = get(schema.fields, `${field}.fields`); if (nestedFields) { // Recurse for nested field keys result[field] = reduceFields(keys(nestedFields), `${field}.`); } else { const fieldKey = `${prefix}${field}`; const fieldMeta = getFieldMeta(fieldKey); result[field] = { ...fieldMeta, valid: (!isEmpty(fieldMeta.value) || fieldMeta.touched) && !fieldMeta.error, }; } return result; }, {}); return reduceFields(fieldKeys); }; export const fieldsAreValid = (fieldNames, fieldsMeta) => !includes(map(fieldNames, fieldName => get(fieldsMeta, `${fieldName}.valid`)), false);
import includes from 'lodash/includes'; import map from 'lodash/map'; import reduce from 'lodash/reduce'; import keys from 'lodash/keys'; import get from 'lodash/get'; import isEmpty from 'lodash/isEmpty'; export const getFieldsMeta = (schema, getFieldMeta) => { const fieldKeys = keys(schema.fields); const reduceFields = (_fieldKeys, prefix = '') => reduce(_fieldKeys, (result, field) => { const nestedFields = get(schema.fields, `${field}.fields`); if (nestedFields) { // Recurse for nested field keys result[field] = reduceFields(keys(nestedFields), `${field}.`); } else { const fieldKey = `${prefix}${field}`; const fieldMeta = getFieldMeta(fieldKey); result[field] = { ...fieldMeta, valid: (!isEmpty(fieldMeta.value) || fieldMeta.touched) && !fieldMeta.error, }; } return result; }, {}); return reduceFields(fieldKeys); }; export const fieldsAreValid = (fieldNames, fieldsMeta) => !includes(map(fieldNames, fieldName => get(fieldsMeta, `${fieldName}.valid`)), false); export const getFieldError = fieldMeta => fieldMeta.touched && fieldMeta.error ? fieldMeta.error : null;
Add getFieldError convenience form util
[WEB-819] Add getFieldError convenience form util
JavaScript
bsd-2-clause
tidepool-org/blip,tidepool-org/blip,tidepool-org/blip
af0106c1e90dba0a66c7f162a23f1060b28beaa1
main.js
main.js
const menubar = require('menubar') const { ipcMain } = require('electron') const configure = require('./src/helpers/configure') const mb = menubar({ alwaysOnTop: true, resizable: false, width: 292, height: 344, icon: `${__dirname}/img/iconTemplate.png` }) mb.on('ready', () => { console.log('App started in menu bar.') configure(mb) }) ipcMain.on('APP_PATH_REQUEST', (event) => { event.sender.send('APP_PATH_REPLY', mb.app.getAppPath()) })
const menubar = require('menubar') const { ipcMain } = require('electron') const configure = require('./src/helpers/configure') const mb = menubar({ alwaysOnTop: true, resizable: false, width: 292, height: 344, icon: `${__dirname}/img/iconTemplate.png` }) mb.on('ready', () => { console.log('App started in menu bar.') configure(mb) mb.tray.on('drag-enter', () => mb.showWindow()) }) mb.on('focus-lost', () => mb.hideWindow()); ipcMain.on('APP_PATH_REQUEST', (event) => { event.sender.send('APP_PATH_REPLY', mb.app.getAppPath()) })
Add ability to drag files into Tray to open Alchemy
Add ability to drag files into Tray to open Alchemy * On window blur Alchemy is minimized
JavaScript
mit
dawnlabs/alchemy,dawnlabs/alchemy,dawnlabs/alchemy
945a41728236981a1d5f5884763cbd9793ba42f8
generatorTests/test/fileStructureSpec.js
generatorTests/test/fileStructureSpec.js
var path = require('path'); var chai = require('chai'); chai.use(require('chai-fs')); chai.should(); const ROOT_DIR = path.join(process.cwd(), '..'); describe('As a dev', function() { describe('when testing cartridge file structure', function() { it('then _config files should exist', function() { var pathToTest = path.join(ROOT_DIR, '_config/'); var filePathToTest; var files = [ 'project.json', 'paths.js' ]; files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required base files should exist', function() { var filePathToTest; var files = [ 'gulpfile.js', 'package.json', 'readme.md', ]; files.forEach(function(fileName) { filePathToTest = path.join(ROOT_DIR, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required handlebars view files should exist', function() { var pathToTest = path.join(ROOT_DIR, 'views/'); var files = [ 'index.hbs', 'styleguide.hbs', ] files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) }); });
var path = require('path'); var chai = require('chai'); chai.use(require('chai-fs')); chai.should(); const ROOT_DIR = path.join(process.cwd(), '..'); describe('As a dev', function() { describe('when testing cartridge file structure', function() { it('then _config files should exist', function() { var pathToTest = path.join(ROOT_DIR, '_config/'); var filePathToTest; var files = [ 'project.json' ]; files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required base files should exist', function() { var filePathToTest; var files = [ 'gulpfile.js', 'package.json', 'readme.md', ]; files.forEach(function(fileName) { filePathToTest = path.join(ROOT_DIR, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) it('then required handlebars view files should exist', function() { var pathToTest = path.join(ROOT_DIR, 'views/'); var files = [ 'index.hbs', 'styleguide.hbs', ] files.forEach(function(fileName) { filePathToTest = path.join(pathToTest, fileName); filePathToTest.should.be.a.file().and.not.empty; }); }) }); });
Remove reference to deleted file
tests: Remove reference to deleted file
JavaScript
mit
cartridge/cartridge,code-computerlove/slate,code-computerlove/slate
fb1497b7195af0ed76e00d670d07f7472c1a3fb0
static/main.js
static/main.js
function setCurrentMonthInInput() { console.log("Tried to set month in input. Disabled right now"); } $('#form-submit-button').click(function (a, c) { console.log("Form being submitted", a, c); return false; });
function setCurrentMonthInInput() { console.log("Tried to set month in input. Disabled right now"); } function failureAlert() { return `<div class="alert alert-danger" role="alert" id="failure-alert"> <!-- <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> --> <strong>Error!</strong> Please choose a month before submitting. </div>`; } var table_index = 1; function tableHead(value) { var h = document.createElement('th') h.appendChild(document.createTextNode(value)); return h; } function createAndAppendRow(data) { var row = document.createElement('tr'); row.appendChild(tableHead(table_index)); table_index++; row.appendChild(tableHead(data.messageUids[0])); row.appendChild(tableHead(data.userName)); row.appendChild(tableHead(data.userId)); row.appendChild(tableHead(data.chatName)); row.appendChild(tableHead(data.chat)); var tableBody = $('#table-body'); tableBody.append(row); } $('#form-submit-button').click(function (event, c) { var month = $('#form-month-input').val(); console.log("Form being submitted", event, c, month); if (month === undefined) { // $('.container')[0].innerHTML = failureAlert() + $('.container')[0].innerHTML; // setTimeout(function(){ // if ($('#failure-alert').length > 0) { // $('#failure-alert').remove(); // } // }, 2000) console.log("No month on page."); return false; } console.log("Got Month", month); var data = {'month': month}; $.ajax({ url: '/history', type: 'POST', data: JSON.stringify(data), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(UIDs) { UIDs.forEach(function(UID, index, array) { var data = {'UID': UID}; $.ajax({ url: '/UID', type: 'POST', data: JSON.stringify(data), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(data) { console.log(data); createAndAppendRow(data); } }); }); } }); return false; });
Add JS to handle submission of dates
Add JS to handle submission of dates
JavaScript
mit
ayushgoel/flock-message-reporter,ayushgoel/flock-message-reporter,ayushgoel/flock-message-reporter,ayushgoel/flock-message-reporter
f246bb8163d663ca173ae3be386a9f7bb82fd66c
src/mapHelper.js
src/mapHelper.js
/** * We need to map identifiers between TestSwarm and BrowserStack. * * Sources: * - TestSwarm: https://github.com/jquery/testswarm/blob/master/inc/BrowserInfo.php * - ua-parser: https://github.com/ua-parser/uap-core * - BrowserStack: * https://github.com/browserstack/api * http://api.browserstack.com/3/browsers (requires authentication) */ // These are in the direction testswarm (ua-parser) -> browserstack. module.exports = { browserFamily: { 'Yandex Browser': 'yandex', 'Android': 'Android Browser' }, osFamily: { 'Windows': 'Windows', 'Mac OS X': 'OS X', 'Android': 'android', 'iOS': 'ios' }, // BrowserStack puts device version inside device family. // Normalise them here, we use OS version instead. deviceFamily: { // Match "iPad 2", "iPad 3rd (6.0)", "iPad Air 2", etc. 'iPad': /^iPad\b/, // Match "iPhone 4", "iPhone 4S (6.0)", "iPhone 6S Plus", etc. 'iPhone': /^iPhone\b/ } };
/** * We need to map identifiers between TestSwarm and BrowserStack. * * Sources: * - TestSwarm: https://github.com/jquery/testswarm/blob/master/inc/BrowserInfo.php * - ua-parser: https://github.com/ua-parser/uap-core * - BrowserStack: * https://github.com/browserstack/api * http://api.browserstack.com/3/browsers (requires authentication) */ // These are in the direction testswarm (ua-parser) -> browserstack. module.exports = { browserFamily: { 'Yandex Browser': 'yandex', 'Android': 'Android Browser', // Android 4.4 and higher use Chrome Mobile instead of Android Browser. // BrowserStack supports both Chrome and Firefox on Android through // the UI. However, the v4 API only exposes one of them (Chrome) // but labels it "Android Browser" for back-compat. 'Chrome Mobile': 'Android Browser' }, osFamily: { 'Windows': 'Windows', 'Mac OS X': 'OS X', 'Android': 'android', 'iOS': 'ios' }, // BrowserStack puts device version inside device family. // Normalise them here, we use OS version instead. deviceFamily: { // Match "iPad 2", "iPad 3rd (6.0)", "iPad Air 2", etc. 'iPad': /^iPad\b/, // Match "iPhone 4", "iPhone 4S (6.0)", "iPhone 6S Plus", etc. 'iPhone': /^iPhone\b/ } };
Add mapping for 'Chrome Mobile' -> 'Android Browser'
map: Add mapping for 'Chrome Mobile' -> 'Android Browser' BrowserStack v4 has back-compat mapping that is actually working against us in this case..
JavaScript
mit
clarkbox/testswarm-browserstack,clarkbox/testswarm-browserstack,mzgol/testswarm-browserstack,mzgol/testswarm-browserstack
78c5eab8d563b44269a591b9249439b55d31d72b
test/pages-test.js
test/pages-test.js
const { expect } = require('chai'); const request = require('supertest'); const app = require('../app'); describe('Pages', function() { describe('/', function() { let req; beforeEach(function() { req = request(app).get('/'); }); it('returns 200 OK', function(done) { req.expect(200, done); }); it('renders a template', function (done) { req.expect('Content-Type', /text\/html/, done); }); }); });
const { expect } = require('chai'); const request = require('supertest'); const app = require('../app'); describe('Pages', function() { let req; describe('/', function() { beforeEach(function() { req = request(app).get('/') }); it('returns 200 OK', function(done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); }); describe('/contact', function() { beforeEach(function() { req = request(app).get('/contact'); }); it('returns 200 OK', function (done) { req.expect(200, done); }); it('renders template', function (done) { req.expect('Content-Type', /text\/html/, done); }); }); });
Add tests for /contact page
Add tests for /contact page
JavaScript
mit
slavapavlutin/pavlutin-node,slavapavlutin/pavlutin-node
7361aa3e36272dfe8a138df011894d79e79b4448
tasks/docco.js
tasks/docco.js
// grunt-docco // https://github.com/DavidSouther/grunt-docco // // Copyright (c) 2012 David Souther // Licensed under the MIT license. "use strict" var docco = require('docco'); module.exports = function(grunt) { grunt.registerMultiTask('docco', 'Docco processor.', function() { var options = this.options({ output: this.file.dest }), _this = this, files = this.file.src, fdone = 0; var done = _this.async(); files.forEach(function(file) { var files = grunt.file.expandFiles(file); docco.document(files, options, function(err, result, code){ if(fdone++ == files.length) done(); }); }); }); };
// grunt-docco // https://github.com/DavidSouther/grunt-docco // // Copyright (c) 2012 David Souther // Licensed under the MIT license. "use strict" var docco = require('docco'); module.exports = function(grunt) { grunt.registerMultiTask('docco', 'Docco processor.', function() { var fdone = 0; var flength = this.files.length; var done = this.async(); this.files.forEach(function(file) { var files = grunt.file.expand(file.src); docco.document(files, { output: file.dest }, function(err, result, code){ if(++fdone === flength) done(); }); }); }); };
Update to be compatible with grunt 0.4rc6
Update to be compatible with grunt 0.4rc6
JavaScript
mit
joseph-jja/grunt-docco-dir,DavidSouther/grunt-docco,joseph-jja/grunt-docco-dir,neocotic/grunt-docco
25cdc352467d9302aa6c09cd0124295f4e3b8814
src/swap-case.js
src/swap-case.js
import R from 'ramda'; import compose from './util/compose.js'; import join from './util/join.js'; import not from './util/not.js'; import upperCase from './util/upper-case.js'; import lowerCase from './util/lower-case.js'; import isUpperCase from '../src/is-upper-case.js'; // a -> a const swapCase = compose( join(''), R.map( R.either( R.both(isUpperCase, lowerCase), R.both(compose(not, isUpperCase), upperCase) ) ) ); export default swapCase;
import R from 'ramda'; import compose from './util/compose.js'; import either from './util/either.js'; import join from './util/join.js'; import not from './util/not.js'; import upperCase from './util/upper-case.js'; import lowerCase from './util/lower-case.js'; import isUpperCase from '../src/is-upper-case.js'; // a -> a const swapCase = compose( join(''), R.map( either( R.both(isUpperCase, lowerCase), R.both(compose(not, isUpperCase), upperCase) ) ) ); export default swapCase;
Refactor swapCase function to use custom either function
Refactor swapCase function to use custom either function
JavaScript
mit
restrung/restrung-js
e950c031b3b80ada5110a286e8966d8dce7f2241
src/JBrowse/main.js
src/JBrowse/main.js
// saves some loading time by loading most of the commonly-used // JBrowse modules at the outset require([ 'JBrowse/Browser', 'JBrowse/ConfigAdaptor/JB_json_v1', // default tracklist view 'JBrowse/View/TrackList/Hierarchical', // common stores 'JBrowse/Store/Sequence/StaticChunked', 'JBrowse/Store/SeqFeature/NCList', 'JBrowse/Store/TiledImage/Fixed', 'JBrowse/Store/Names/Hash', 'JBrowse/Store/Names/REST', // common track views 'JBrowse/View/Track/Sequence', 'JBrowse/View/Track/HTMLFeatures', 'JBrowse/View/Track/FixedImage/Wiggle', 'JBrowse/View/Track/Wiggle', 'JBrowse/View/Track/Wiggle/XYPlot', 'JBrowse/View/Track/Wiggle/Density', 'JBrowse/View/Track/Alignments', 'JBrowse/View/Track/Alignments2', 'JBrowse/View/Track/FeatureCoverage', 'JBrowse/View/Track/SNPCoverage', // track lists 'JBrowse/Store/TrackMetaData' ]);
// saves some loading time by loading most of the commonly-used // JBrowse modules at the outset require([ 'JBrowse/Browser', 'JBrowse/ConfigAdaptor/JB_json_v1', // default tracklist view 'JBrowse/View/TrackList/Hierarchical', // common stores 'JBrowse/Store/Sequence/StaticChunked', 'JBrowse/Store/SeqFeature/NCList', 'JBrowse/Store/TiledImage/Fixed', 'JBrowse/Store/Names/Hash', 'JBrowse/Store/Names/REST', // common track views 'JBrowse/View/Track/Sequence', 'JBrowse/View/Track/HTMLFeatures', 'JBrowse/View/Track/FixedImage/Wiggle', 'JBrowse/View/Track/Wiggle', 'JBrowse/View/Track/Wiggle/XYPlot', 'JBrowse/View/Track/Wiggle/Density', 'JBrowse/View/Track/Alignments', 'JBrowse/View/Track/Alignments2', 'JBrowse/View/Track/FeatureCoverage', 'JBrowse/View/Track/SNPCoverage', // track lists 'JBrowse/Store/TrackMetaData', 'xstyle/core/load-css', 'dojox/gfx/svg' ]);
Add back the xstyle and dojox svg modules correctly
Add back the xstyle and dojox svg modules correctly
JavaScript
lgpl-2.1
GMOD/jbrowse,erasche/jbrowse,GMOD/jbrowse,Arabidopsis-Information-Portal/jbrowse,Arabidopsis-Information-Portal/jbrowse,nathandunn/jbrowse,erasche/jbrowse,erasche/jbrowse,nathandunn/jbrowse,nathandunn/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,GMOD/jbrowse,GMOD/jbrowse,nathandunn/jbrowse,Arabidopsis-Information-Portal/jbrowse,GMOD/jbrowse,erasche/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,nathandunn/jbrowse,erasche/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,Arabidopsis-Information-Portal/jbrowse
7edcb97899f0812c280bb73326b6041d734656d1
src/core/GraoModel.js
src/core/GraoModel.js
var GraoModel = function(di) { di.event.newSuccess('Database Connection....'); di.mongoose.connect(di.config.db); di.event.newSuccess('Instance created'); di.models = this; di.models = di.loader.tryLoad(di.loader.loading('model'), di, 'models'); }; module.exports = exports = GraoModel;
var GraoModel = function(di) { di.event.newSuccess('Database Connection....'); //di.mongoose.connect(di.config.db); di.mongoose.connect(di.config.db, {useMongoClient: true}); di.event.newSuccess('Instance created'); di.models = this; di.models = di.loader.tryLoad(di.loader.loading('model'), di, 'models'); }; module.exports = exports = GraoModel;
Add new param to mongoose connection
Add new param to mongoose connection
JavaScript
mit
marcelomf/graojs,marcelomf/graojs,marcelomf/graojs,synackbr/graojs,synackbr/graojs,synackbr/graojs
c1dca6018d44c0090e1b5bbf16eb4df12882ece5
src/player.js
src/player.js
function Player() { this.strength = statRoll(); this.dexterity = statRoll(); this.mind = statRoll(); this.init(arguments); } Mextend(Player, { player: true, name: '<sV|Bvs>(.exe)', experience: 0 }); Player.prototype.act = function(callback) { controls.act(); }; Player.prototype.addExperience = function(exp) { this.experience += exp; unimportant('You gain %d experience.', exp); while (this.experience > this.nextLevel()) { this.levelUp(); } }; /** * Level up the player. */ Player.prototype.levelUp = function() { this.experience -= this.nextLevel(); this.level += 1; var hproll = d6(); this.maxhp += hproll; this.hp = this.maxhp; var mproll = d6(); this.maxmp += mproll; this.mp += mproll; if ((this.level % 3) === 0) this.strength++; // XXX important("You are now at version %d.0!", this.level); }; Player.prototype.nextLevel = function() { return Math.ceil(Math.pow(this.level + 8, 2.1)); };
function Player() { this.strength = statRoll(); this.dexterity = statRoll(); this.mind = statRoll(); this.init(arguments); } Mextend(Player, { player: true, name: '<sV|Bvs>(.exe)', experience: 0 }); Player.prototype.act = function(callback) { controls.act(); }; Player.prototype.addExperience = function(exp) { this.experience += exp; unimportant('You gain %d experience.', exp); while (this.experience > this.nextLevel()) { this.levelUp(); } }; /** * Level up the player. */ Player.prototype.levelUp = function() { this.experience -= this.nextLevel(); this.level += 1; var hproll = d6(); for (var i = 1; i < bonus(this.strength); i++) hproll += d6(); this.maxhp += hproll; this.hp = this.maxhp; var mproll = d6(); this.maxmp += mproll; this.mp += mproll; switch (this.level % 3) { case 0: this.strength++; break; case 1: this.dexterity++; break; case 2: this.mind++; break; } important("You are now at version %d.0!", this.level); }; Player.prototype.nextLevel = function() { return Math.ceil(Math.pow(this.level + 8, 2.1)); };
Make leveling a bit stronger.
Make leveling a bit stronger.
JavaScript
unlicense
skeeto/disc-rl
7f7eae887362b117cca1f567fbd2ea8677082e0c
examples/index.js
examples/index.js
var Gravatar = require('../dist/index.js'); var React = require('react'); React.renderComponent( React.DOM.div(null, [ React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' />"), Gravatar({email: 'mathews.kyle@gmail.com'}), React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' size=100 />"), Gravatar({email: 'mathews.kyle@gmail.com', size: 100}), React.DOM.h2(null, "For emails without a gravatar, use the retro default. You can override this by passing in a different 'default' prop. See https://en.gravatar.com/site/implement/images/ for options."), Gravatar({email: 'blah@blah.com'}), ]), document.body);
var React = require('react'); var Gravatar = React.createFactory(require('../dist/index.js')); React.render( React.DOM.div(null, [ React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' />"), Gravatar({email: 'mathews.kyle@gmail.com'}), React.DOM.h2(null, "<Gravatar email='mathews.kyle@gmail.com' size=100 />"), Gravatar({email: 'mathews.kyle@gmail.com', size: 100}), React.DOM.h2(null, "For emails without a gravatar, use the retro default. You can override this by passing in a different 'default' prop. See https://en.gravatar.com/site/implement/images/ for options."), Gravatar({email: 'blah@blah.com'}), ]), document.body);
Fix example for React 0.13
Fix example for React 0.13
JavaScript
mit
KyleAMathews/react-gravatar
e3c41cb206d1c36622c41cf0ec45e61501bababa
config/config-sample.js
config/config-sample.js
module.exports = { home: '/home', // the path to users home directory (absolute!) tmp: process.env.HOME + '/.ezseed/tmp', //the tmp folder path - default to HOME/.ezseed/tmp (absolute!) watcher: 'unix:///usr/local/opt/ezseed/watcher.sock', watcher_rpc: 'unix:///usr/local/opt/ezseed/watcher_rpc.sock', transmission: false, //is transmission installed? rtorrent: false, //is rtorrent installed? client_link: 'embed', //embed|link do we embed the p2p web interface or should it be openin a new window? theme: 'ezseed-web', scrapper: 'tmdb', lang: 'en', secret: 'really-secret-key' }
module.exports = { home: '/home', // the path to users home directory (absolute!) tmp: process.env.HOME + '/.ezseed/tmp', //the tmp folder path - default to HOME/.ezseed/tmp (absolute!) watcher: 'unix:///usr/local/opt/ezseed/watcher.sock', watcher_rpc: 'unix:///usr/local/opt/ezseed/watcher_rpc.sock', transmission: false, //is transmission installed? rtorrent: false, //is rtorrent installed? client_link: 'embed', //embed|link do we embed the p2p web interface or should it be openin a new window? theme: 'ezseed-web', scrapper: 'tmdb', lang: 'en', secret: 'really-secret-key', base: '/' //ezseed base path }
Add base path to config
feat(config): Add base path to config
JavaScript
bsd-3-clause
ezseed/ezseed,ezseed/ezseed
3b346545f373a2d52db9dc4d8774b75c4cf46246
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var source = require('vinyl-source-stream'); var browserify = require('browserify'); var streamify = require('gulp-streamify'); var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); var prefix = require('gulp-autoprefixer'); var rename = require('gulp-rename'); gulp.task('scripts', function() { browserify('./static/js/app.js') .bundle() .pipe(source('js.min.js')) //.pipe(streamify(uglify())) .pipe(gulp.dest('./static/build')); }); gulp.task('css', function() { gulp.src('./static/sass/style.scss') .pipe(sass({ outputStyle: 'compressed', errLogToConsole: true, error: function(err) { console.log(err); } })) .pipe(prefix("last 1 version", "> 1%", "ie 8", "ie 7")) .pipe(rename('css.min.css')) .pipe(gulp.dest('./static/build')); }); // Watch gulp.task('watch', function() { // Watch .scss files gulp.watch(['static/js/**/*', 'static/sass/**/*'], ['css', 'scripts']); }); gulp.task('default', ['scripts', 'css']);
var gulp = require('gulp'); var source = require('vinyl-source-stream'); var browserify = require('browserify'); var streamify = require('gulp-streamify'); var uglify = require('gulp-uglify'); var sass = require('gulp-sass'); var prefix = require('gulp-autoprefixer'); var rename = require('gulp-rename'); var gutil = require('gulp-util'); var webpack = require('gulp-webpack'); gulp.task('scripts', function() { browserify('./static/js/app.js') .bundle() .pipe(source('js.min.js')) //.pipe(streamify(uglify())) .pipe(gulp.dest('./static/build')); }); gulp.task('css', function() { gulp.src('./static/sass/style.scss') .pipe(sass({ outputStyle: 'compressed', errLogToConsole: true, error: function(err) { console.log(err); } })) .pipe(prefix("last 1 version", "> 1%", "ie 8", "ie 7")) .pipe(rename('css.min.css')) .pipe(gulp.dest('./static/build')); }); gulp.task('webpack', function(callback) { return gulp.src('./static/js/app.js') .pipe(webpack({ /* webpack configuration */ })) .pipe(uglify()) .pipe(rename('js.min.js')) .pipe(gulp.dest('./static/build')); }); // Watch gulp.task('watch', function() { // Watch .scss files gulp.watch(['static/js/**/*', 'static/sass/**/*'], ['css', 'scripts']); }); gulp.task('default', ['scripts', 'css']);
Add in webpack in there.
Add in webpack in there.
JavaScript
mit
eiriksm/sqr,eiriksm/sqr
1726c021482bff178832cb4e3c0816cf560416f0
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var jasmine = require('gulp-jasmine'); gulp.task('jasmine', function () { return gulp.src('spec/**/*.js') .pipe(jasmine({ verbose: true })); }); gulp.task('babel', function () { return gulp.src('src/**/*.js') //.pipe(sourcemaps.init()) .pipe(babel({ stage: 0 // http://babeljs.io/docs/usage/experimental/ })) //.pipe(concat('all.js')) //.pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')); }); gulp.task('watch', function(){ gulp.watch(['src/**/*.js', 'spec/**/*.js'], ['babel', 'jasmine']); }); gulp.task('default', ['watch']);
var gulp = require('gulp'); var sourcemaps = require('gulp-sourcemaps'); var babel = require('gulp-babel'); var concat = require('gulp-concat'); var jasmine = require('gulp-jasmine'); gulp.task('jasmine', function () { return gulp.src('spec/**/*.js') .pipe(jasmine({ verbose: true })); }); gulp.task('babel', function () { return gulp.src('src/**/*.js') //.pipe(sourcemaps.init()) .pipe(babel({ stage: 0 // http://babeljs.io/docs/usage/experimental/ })) .on('error', console.error.bind(console)) //.pipe(concat('all.js')) //.pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')); }); gulp.task('watch', function(){ gulp.watch(['src/**/*.js', 'spec/**/*.js'], ['babel', 'jasmine']); }); gulp.task('default', ['watch']);
Add error handling to make babel not exit on error
Add error handling to make babel not exit on error
JavaScript
mit
trapridge/es67-fun
b10940e31c2a218574f9a5babbf2b782bc7baecd
lib/buster-util/jstestdriver-shim.js
lib/buster-util/jstestdriver-shim.js
function testCase(name, tests) { var testCase = TestCase(name); for (var test in tests) { if (test != "setUp" && test != "tearDown") { testCase.prototype["test " + test] = tests[test]; } else { testCase.prototype[test] = tests[test]; } } return testCase; } var assert = this; (function () { var mappedAssertions = { ok: "True", doesNotThrow: "NoException", throws: "Exception", equal: "Equals" }; for (var assertion in mappedAssertions) { assert[assertion] = assert["assert" + mappedAssertions[assertion]]; } }());
function testCase(name, tests) { var testCase = TestCase(name); for (var test in tests) { if (test != "setUp" && test != "tearDown") { testCase.prototype["test " + test] = tests[test]; } else { testCase.prototype[test] = tests[test]; } } return testCase; } var assert = this; (function () { var mappedAssertions = { ok: "True", doesNotThrow: "NoException", throws: "Exception", equal: "Equals" }; for (var assertion in mappedAssertions) { assert[assertion] = assert["assert" + mappedAssertions[assertion]]; } }()); if (buster.assert && buster.format) { buster.assert.format = buster.format.ascii; buster.assert.fail = fail; }
Add buster.assert hook when it's available
Add buster.assert hook when it's available
JavaScript
bsd-3-clause
busterjs/buster-core,geddski/buster-core,busterjs/buster-core
602fe72de7d59a80ff3a50c011bce5c4f820a905
config/environment.js
config/environment.js
/* eslint-env node */ module.exports = function(environment) { var ENV = { modulePrefix: 'noise', environment: environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.noiseUrl = '//localhost:3000/query' } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.noiseUrl = '//try.noisesearch.org:3000/query' } return ENV; };
/* eslint-env node */ module.exports = function(environment) { var ENV = { modulePrefix: 'noise', environment: environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.noiseUrl = '//localhost:3000/query' } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.noiseUrl = '/query' } return ENV; };
Use the proxied endpoint for production
Use the proxied endpoint for production
JavaScript
apache-2.0
pipedown/try_out_noise,pipedown/try_out_noise,pipedown/try_out_noise
ce8ce0520c7cf64fe954b55fb8e90e6e21b0909d
src/methodCreators.js
src/methodCreators.js
const takeNoArgs = (method) => function() { return method(this.props); }; const takeFirstArg = (method) => function(nextProps) { return method(this.props, nextProps); }; const methodCreators = { componentWillMount: takeNoArgs, componentDidMount: takeNoArgs, componentWillReceiveProps: takeFirstArg, shouldComponentUpdate: takeFirstArg, componentWillUpdate: takeFirstArg, componentDidUpdate: takeFirstArg, componentWillUnmount: takeNoArgs }; if (process.env.NODE_ENV !== 'production') { Object.freeze(methodCreators); } export default methodCreators;
const takeNoArgs = (method) => function() { return method(this.props); }; const takeFirstArg = (method) => function(arg1) { return method(this.props, arg1); }; const methodCreators = { componentWillMount: takeNoArgs, componentDidMount: takeNoArgs, componentWillReceiveProps: takeFirstArg, shouldComponentUpdate: takeFirstArg, componentWillUpdate: takeFirstArg, componentDidUpdate: takeFirstArg, componentWillUnmount: takeNoArgs }; if (process.env.NODE_ENV !== 'production') { Object.freeze(methodCreators); } export default methodCreators;
Use more generic param name
Use more generic param name
JavaScript
mit
jfairbank/react-classify,jfairbank/react-classify
3cc85e098b44c54683820526998e341dd0a184e1
test/bindings.js
test/bindings.js
/*jshint -W030 */ var gremlin = require('../'); describe('Bindings', function() { it('should support bindings with client.execute()', function(done) { var client = gremlin.createClient(); client.execute('g.v(x)', { x: 1 }, function(err, result) { (err === null).should.be.true; result.length.should.equal(1); done(); }); }); it('should support bindings with client.stream()', function(done) { var client = gremlin.createClient(); var stream = client.stream('g.v(x)', { x: 1 }); stream.on('data', function(result) { result.id.should.equal(1); }); stream.on('end', function() { done(); }); }); it('should give an error with erroneous binding name in .exec', function(done) { var client = gremlin.createClient(); client.execute('g.v(id)', { id: 1 }, function(err, result) { (err !== null).should.be.true; (result === undefined).should.be.true; done(); }); }); });
/*jshint -W030 */ var gremlin = require('../'); describe('Bindings', function() { it('should support bindings with client.execute()', function(done) { var client = gremlin.createClient(); client.execute('g.v(x)', { x: 1 }, function(err, result) { (err === null).should.be.true; result.length.should.equal(1); done(); }); }); it('should support bindings with client.stream()', function(done) { var client = gremlin.createClient(); var stream = client.stream('g.v(x)', { x: 1 }); stream.on('data', function(result) { result.id.should.equal(1); }); stream.on('end', function() { done(); }); }); it('should give an error with erroneous binding name in .exec', function(done) { var client = gremlin.createClient(); // This is supposed to throw a NoSuchElementException in Gremlin Server: // --> "The vertex with id id of type does not exist in the graph" // id is a reserved (imported) variable and can't be used in a script client.execute('g.v(id)', { id: 1 }, function(err, result) { (err !== null).should.be.true; (result === undefined).should.be.true; done(); }); }); });
Add explicit comments in test using reserved binding name
Add explicit comments in test using reserved binding name
JavaScript
mit
jbmusso/gremlin-client,hiddenmoo/gremlin-client,CosmosDB/gremlin-javascript,CosmosDB/gremlin-javascript,hiddenmoo/gremlin-client,jbmusso/gremlin-javascript,jbmusso/gremlin-javascript
c8fc979080729361180ab6a04df63c0140a1ffd2
packages/@sanity/server/src/configs/webpack.config.prod.js
packages/@sanity/server/src/configs/webpack.config.prod.js
import webpack from 'webpack' import getBaseConfig from './webpack.config' export default config => { const baseConfig = getBaseConfig(Object.assign({}, config, {env: 'production'})) const skipMinify = config.skipMinify return Object.assign({}, baseConfig, { devtool: config.sourceMaps ? 'source-map' : undefined, plugins: (baseConfig.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), !skipMinify && new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ].filter(Boolean)) }) }
import webpack from 'webpack' import getBaseConfig from './webpack.config' export default config => { const baseConfig = getBaseConfig(Object.assign({}, config, {env: 'production'})) return Object.assign({}, baseConfig, { devtool: config.sourceMaps ? 'source-map' : undefined, plugins: (baseConfig.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }) ].filter(Boolean)) }) }
Move minification out of webpack
Move minification out of webpack
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
e47584cb25cf75311e368a4ad87ba61b68d906ae
src/selection/join.js
src/selection/join.js
function(onenter, onupdate, onexit) { var enter = this.enter(), update = this, exit = this.exit(); if (typeof onenter === "function") { enter = onenter(enter); if (enter) enter = enter.selection(); } else { enter = enter.append(onenter + ""); } if (onupdate != null) { update = onupdate(update); if (update) update = update.selection(); } if (onexit == null) exit.remove(); else onexit(exit); return enter && update ? enter.merge(update).order() : update; }
function(onenter, onupdate, onexit) { var enter = this.enter(), update = this, exit = this.exit(); if (typeof onenter === "function") { enter = onenter(enter); if (enter) enter = enter.selection(); } else { enter = enter.append(onenter + ""); } if (onupdate != null) update = onupdate(update); if (onexit == null) exit.remove(); else onexit(exit); return enter && update ? enter.merge(update).order() : update; }
Revert update logic as it is handled by .merge.
Revert update logic as it is handled by .merge.
JavaScript
isc
d3/d3-selection
62756a7e5ed5297cc2084644ac82d678179a3362
src/components/page.js
src/components/page.js
import React from 'react' import GoogleAnalyticsScript from './scripts/google-analytics' export default Page function Page({ children, title = 'JavaScript Air', description = 'The live JavaScript podcast all about JavaScript and the web platform. Available on YouTube, iTunes, and an RSS audio feed', } = {}) { /* eslint max-len:0 */ return ( <html> <head lang="en"> <title>{title}</title> <meta charSet="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="google-site-verification" content="85n8ZBk_3hSeShlRmsVJXgDolakFG4UsMJgpy3mQyPs" /> <meta name="theme-color" content="#155674" /> <meta name="author" content="Kent C. Dodds" /> <meta name="description" content={description} /> <link rel="shortcut icon" type="image/png" href="/favicon.ico"/> <link rel="stylesheet" href="/styles.dist.css" /> <link rel="stylesheet" href="/resources/font/font.css" /> </head> <body> {children} <GoogleAnalyticsScript /> </body> </html> ) }
import React from 'react' import GoogleAnalyticsScript from './scripts/google-analytics' export default Page function Page({ children, title = 'JavaScript Air', description = 'The live JavaScript podcast all about JavaScript and the web platform. Available on YouTube, iTunes, and an RSS audio feed', } = {}) { /* eslint max-len:0 */ return ( <html> <head lang="en"> <title>{title}</title> <meta charSet="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="google-site-verification" content="85n8ZBk_3hSeShlRmsVJXgDolakFG4UsMJgpy3mQyPs" /> <meta name="theme-color" content="#155674" /> <meta name="author" content="Kent C. Dodds" /> <meta name="description" content={description} /> <link rel="shortcut icon" type="image/png" href="/favicon.ico"/> <link rel="stylesheet" href="/styles.dist.css" /> </head> <body> {children} <GoogleAnalyticsScript /> </body> </html> ) }
Remove now-deleted font reference from Page component
Remove now-deleted font reference from Page component
JavaScript
mit
javascriptair/site,javascriptair/site,javascriptair/site
5337b3add954120583cbee1610ca2d8f188d9322
src/js/home-page.js
src/js/home-page.js
import React from 'react'; import { Link } from 'react-router'; import HomepageTile from './homepage-tile.js'; import chaptersData from './chapter-data.js'; // Clone the chapters since sort mutates the array const chapters = [...chaptersData] .filter(chapter => !chapter.hidden) .sort((chapterA, chapterB) => chapterA.number - chapterB.number); const HomePage = React.createClass({ render: function() { return ( <div className="container homepage"> <div className="pure-g row-gap-small"> <div className="pure-u-1"> <h2>Grade 6 Science</h2> </div> </div> <div className="pure-g"> {chapters.map(chapter => ( <HomepageTile imagePath={chapter.thumbnailImagePath} chapterNumber={chapter.number} title={chapter.title} /> ))} </div> {this.props.children} </div> ); } }); export default HomePage;
import React from 'react'; import { Link } from 'react-router'; import HomepageTile from './homepage-tile.js'; import chaptersData from './chapter-data.js'; // Clone the chapters since sort mutates the array const chapters = [...chaptersData] .filter(chapter => !chapter.hidden) .sort((chapterA, chapterB) => chapterA.number - chapterB.number); const HomePage = React.createClass({ render: function() { return ( <div className="container homepage"> <div className="pure-g row-gap-small"> <div className="pure-u-1"> <h2>Grade 6 Science</h2> </div> </div> <div className="pure-g"> {chapters.map((chapter, index) => ( <HomepageTile key={index} imagePath={chapter.thumbnailImagePath} chapterNumber={chapter.number} title={chapter.title} /> ))} </div> {this.props.children} </div> ); } }); export default HomePage;
Add key to homepage tile items to satisfy react
Add key to homepage tile items to satisfy react
JavaScript
mit
nicolasartman/learning-prototype,nicolasartman/learning-prototype,nicolasartman/chalees-min,nicolasartman/chalees-min
d92c8ce875ce3da991ebce9222c200489da0b18f
test/index.js
test/index.js
var Couleurs = require ("../index"); console.log("Red".rgb([255, 0, 0])); console.log("Yellow".rgb(255, 255, 0)); console.log("Blue".rgb("#2980b9")); console.log("Bold".bold()) console.log("Italic".italic()) console.log("Underline".underline()) console.log("Inverse".inverse()) console.log("Strikethrough".strikethrough()) console.log("All combined" .rgb("#d35400") .bold() .italic() .underline() .inverse() .strikethrough() )
// Dependency var Couleurs = require("../index")(); // No prototype modify console.log(Couleurs.rgb("Red", [255, 0, 0])); console.log(Couleurs.rgb("Yellow", 255, 255, 0)); console.log(Couleurs.rgb("Blue", "#2980b9")); console.log(Couleurs.bold("Bold")); console.log(Couleurs.italic("Italic")); // Modify prototype require("../index")(true); console.log("Underline".underline()); console.log("Inverse".inverse()); console.log("Strikethrough".strikethrough()); console.log("All combined" .rgb("#d35400") .bold() .italic() .underline() .inverse() .strikethrough() );
Call couleurs in different ways.
Call couleurs in different ways.
JavaScript
mit
IonicaBizau/node-couleurs
d43f60a6bbc181c0f08fa5dcfdbd1ab19709afef
lib/modules/fields/class_static_methods/get_list_fields.js
lib/modules/fields/class_static_methods/get_list_fields.js
import _ from 'lodash'; import ListField from '../list_field.js'; function getListFields() { return _.filter(this.getFields(), function(field) { return field instanceof ListField; }); }; export default getListFields;
import _ from 'lodash'; import ListField from '../list_field.js'; function getListFields(classOnly = false) { return _.filter(this.getFields(), function(field) { if (classOnly) { return field instanceof ListField && field.isClass; } return field instanceof ListField; }); }; export default getListFields;
Allow getting only class fields in the getListFields method
Allow getting only class fields in the getListFields method
JavaScript
mit
jagi/meteor-astronomy
c042b19ee5414afe1ab206ebebace8675d55c096
test/sites.js
test/sites.js
var inspector = require('..'); var expect = require('expect.js'); describe("url-inspector", function sites() { it("should get title from http://www.lavieenbois.com/", function(done) { this.timeout(5000); inspector('http://www.lavieenbois.com/', function(err, meta) { expect(err).to.not.be.ok(); expect(meta.title).to.be.ok(); done(); }); }); });
var inspector = require('..'); var expect = require('expect.js'); describe("url-inspector", function sites() { it("should get title from http://www.lavieenbois.com/", function(done) { this.timeout(5000); inspector('http://www.lavieenbois.com/', function(err, meta) { expect(err).to.not.be.ok(); expect(meta.title).to.be.ok(); done(); }); }); it("should return embeddable content at https://myspace.com/unefemmemariee/music/songs", function(done) { this.timeout(5000); inspector('https://myspace.com/unefemmemariee/music/songs', function(err, meta) { expect(err).to.not.be.ok(); expect(meta.ext).to.be("html"); expect(meta.embed).to.be.ok(); expect(meta.html.startsWith('<iframe')).to.be.ok(); done(); }); }); });
Add a test to ensure html objects are embeds
Add a test to ensure html objects are embeds
JavaScript
mit
kapouer/url-inspector
9ccba19417e58ecd619ceb036ea2f3cc48eb64c4
addon/components/banner-with-close-button.js
addon/components/banner-with-close-button.js
import Component from '@ember/component'; import layout from '../templates/components/banner-with-close-button'; import {inject as service} from '@ember/service'; import {computed} from '@ember/object'; export default Component.extend({ layout, cookies: service(), classNames: ['banner-with-close-button'], isBannerCookieSet: computed('closed', function() { let cookieService = this.get('cookies'); return cookieService.read('hasSeenBanner'); }), actions: { setBannerCookie() { let cookieService = this.get('cookies'); cookieService.write('hasSeenBanner', true, {path: '/'}); this.set('closed', true); }, elementClicked({target}) { if (target.tagName.toLowerCase() === 'a') { let cookieService = this.get('cookies'); cookieService.write('hasSeenBanner', true, {path: '/'}); this.set('closed', true); } } }, });
import Component from '@ember/component'; import layout from '../templates/components/banner-with-close-button'; import {inject as service} from '@ember/service'; import {computed} from '@ember/object'; export default Component.extend({ layout, cookies: service(), classNames: ['banner-with-close-button'], isBannerCookieSet: computed('closed', function() { let cookieService = this.get('cookies'); return cookieService.read('hasSeenBanner'); }), actions: { setBannerCookie() { let cookieService = this.get('cookies'); let future = new Date(); future.setDate(future.getDate() + 30); cookieService.write('hasSeenBanner', true, {path: '/', expires: future}); this.set('closed', true); }, elementClicked({target}) { if (target.tagName.toLowerCase() === 'a') { let cookieService = this.get('cookies'); let future = new Date(); future.setDate(future.getDate() + 30); cookieService.write('hasSeenBanner', true, {path: '/', expires: future}); this.set('closed', true); } } }, });
Add 30 day expiration to cookie on gdpr banner
Add 30 day expiration to cookie on gdpr banner
JavaScript
mit
nypublicradio/nypr-ui,nypublicradio/nypr-ui
b8d022270a10d59cc895acafad4742ad61e3460c
server/routes/authRouter.js
server/routes/authRouter.js
var authRouter = require('express').Router(); var jwt = require('jwt-simple'); var auth = require('../lib/auth'); var User = require('../../db/models/User'); var Promise = require('bluebird'); var bcrypt = require('bcryptjs'); bcrypt.compare = Promise.promisify(bcrypt.compare); authRouter.post('/login', function(req, res) { var email = req.body.email; var password = req.body.password; if (!email || !password) { res.status(400).send('Incomplete email/password'); return; } User.query().where('email', email) .then(function(user) { var user = user[0]; if (!user) { throw 'Error: user does not exist'; } else { return Promise.all([ bcrypt.compare(password, user.password), user ]); } }) .spread(function(authenticated, user) { if (!authenticated) { throw 'Invalid password'; } else { var payload = { id: user.id }; var token = jwt.encode(payload, auth.cfg.jwtSecret); res.json({ token: token }); } }) .catch(function(authError) { res.status(401).send(authError); }) .error(function(err) { console.error('Auth server error: ', err); res.status(500).send('Server error'); }); }); module.exports = authRouter;
var authRouter = require('express').Router(); var jwt = require('jwt-simple'); var auth = require('../lib/auth'); var User = require('../../db/models/User'); var Promise = require('bluebird'); var bcrypt = require('bcryptjs'); bcrypt.compare = Promise.promisify(bcrypt.compare); authRouter.post('/login', function(req, res) { var email = req.body.email; var password = req.body.password; if (!email || !password) { res.status(400).send('Incomplete email/password'); return; } User.query().where('email', email) .then(function(user) { var user = user[0]; if (!user) { throw 'Error: user does not exist'; } else { return Promise.all([ bcrypt.compare(password, user.password), user ]); } }) .spread(function(authenticated, user) { if (!authenticated) { throw 'Invalid password'; } else { var payload = { id: user.id, exp: Math.round((Date.now() + 30 * 24 * 60 * 1000) / 1000) }; var token = jwt.encode(payload, auth.cfg.jwtSecret); res.json({ token: token }); } }) .catch(function(authError) { res.status(401).send(authError); }) .error(function(err) { console.error('Auth server error: ', err); res.status(500).send('Server error'); }); }); module.exports = authRouter;
Set JWT expiration date to 30 days
Set JWT expiration date to 30 days
JavaScript
mit
SillySalamanders/Reactivity,SillySalamanders/Reactivity
949254b178c540d98783e3efe3c2df82cd138ce4
src/components/CryptoDropdown.js
src/components/CryptoDropdown.js
import React from 'react' const CryptoDropdown = ({ label, cryptos, action }) => ( <div className="form-group form-group-sm"> <label className="col-sm-2 control-label">{label}</label> <div className="col-sm-10"> <select className="form-control" onChange={ (e) => action(e.target.value)}> <option value="" selected disabled>Select Currency</option> {cryptos.map(crypto => <option key={crypto.id}>{crypto.symbol}</option> ) } </select> </div> </div> ) export default CryptoDropdown
import React from 'react' const CryptoDropdown = ({ label, cryptos, action }) => ( <div className="form-group form-group-sm"> <label className="col-sm-2 control-label">{label}</label> <div className="col-sm-10"> <select className="form-control" onChange={ (e) => action(e.target.value)}> {cryptos.map(crypto => <option key={crypto.id}>{crypto.symbol}</option> ) } </select> </div> </div> ) export default CryptoDropdown
Revert "updated image for documentation"
Revert "updated image for documentation" This reverts commit de6b2b26414dfd46069d170761e457d95c67b589.
JavaScript
mit
davidoevans/react-redux-dapp,davidoevans/react-redux-dapp
d232a4d61f6de338916a15744e925f5ff8e3ca9a
test/types.js
test/types.js
import test from 'ava'; import domLoaded from '../'; test('domLoaded is a function', t => { t.is(typeof domLoaded, 'function'); });
import test from 'ava'; import domLoaded from '../'; test('domLoaded is a function', t => { t.is(typeof domLoaded, 'function'); }); test('domLoaded returns a Promise', t => { t.true(domLoaded() instanceof Promise); });
Test domLoaded returns a Promise
Test domLoaded returns a Promise
JavaScript
mit
lukechilds/when-dom-ready
17ce6c41c8e7b43f1e9f12fe66e4e65ec9f7a487
index.js
index.js
var dust try { dust = require('dustjs-linkedin') try { require('dustjs-helpers') } catch (ex) {} } catch (ex) { try { dust = require('dust') } catch (ex) {} } if (!dust) throw new Error('"dustjs-linkedin" or "dust" module not found') module.exports = { module: { compile: function(template, options, callback) { var compiled = dust.compileFn(template, options && options.name) process.nextTick(function() { callback(null, function(context, options, callback) { compiled(context, callback) }) }) } }, compileMode: 'async' }
var dust var fs = require('fs') var Path = require('path') try { dust = require('dustjs-linkedin') try { require('dustjs-helpers') } catch (ex) {} } catch (ex) { try { dust = require('dust') } catch (ex) {} } if (!dust) throw new Error('"dustjs-linkedin" or "dust" module not found') module.exports = { module: { compile: function(template, options, callback) { var fileExtension = options.defaultExtension || 'dust' dust.onLoad = function(name, callback) { fs.readFile(Path.join(options.basedir, name + '.' + fileExtension), function(err, data) { if (err) throw err callback(err, data.toString()) }) } var compiled = dust.compileFn(template, options && options.name) process.nextTick(function() { callback(null, function(context, options, callback) { compiled(context, callback) }) }) } }, compileMode: 'async' }
Use dust.onLoad to compile templates
Use dust.onLoad to compile templates
JavaScript
mit
mikefrey/hapi-dust
e7afd02eb05683909c88ef0531963f4badf9d351
Multiselect.js
Multiselect.js
Template.Multiselect.onRendered(function multiselectOnRendered() { let template = this; let config = {}; if(template.data.configOptions) { config = template.data.configOptions; } // autorun waits until after the dependent data has been updated template.autorun(function multiselectAutorun() { Template.currentData(); // afterFlush waits until the rest of the DOM elements have been built Tracker.afterFlush(function multiselectAfterFlush() { if(template.data.menuItems.length > 0) { // Finally ready to initialize the multiselect // e.g. after #each has completed creating all elements template.$('select').multiselect(config); } }); }); }); Template.Multiselect.helpers({ 'args': function args() { data = Template.instance().data; selected = false; if(data.selectedList instanceof Array) { selected = Boolean(data.selectedList.indexOf(this.value) > -1 ); } else { selected = this.value === data.selectedList; } return _.extend({}, this, {'selectedAttr': selected ? 'selected' : ''}); } });
Template.Multiselect.onRendered(function multiselectOnRendered() { let template = this; let config = {}; if(template.data.configOptions) { config = template.data.configOptions; } // autorun waits until after the dependent data has been updated template.autorun(function multiselectAutorun() { Template.currentData(); // afterFlush waits until the rest of the DOM elements have been built Tracker.afterFlush(function multiselectAfterFlush() { if(template.data.menuItems.length > 0) { // Finally ready to initialize the multiselect // e.g. after #each has completed creating all elements // If data has updated refresh the multiselect if(template.selector) { template.selector.multiselect('refresh'); } else { template.selector = template.selector || template.$('select'); template.selector.multiselect(config); } } }); }); }); Template.Multiselect.helpers({ 'args': function args() { let template = Template.instance(); let data = template.data; let selected = false; if(data.selectedList instanceof Array) { selected = Boolean(data.selectedList.indexOf(this.value) > -1 ); } else { selected = this.value === data.selectedList; } // if multiselect is initiliazed then any data changes will // need to update the multiselect internal data if(template.selector) { if(selected) { template.selector.multiselect('select', this.value); } else { template.selector.multiselect('deselect', this.value); } } return _.extend({}, this, {'selectedAttr': selected ? 'selected' : ''}); } });
Handle reinitialize case, clean up variable declarations
Handle reinitialize case, clean up variable declarations
JavaScript
mit
brucejo75/meteor-bootstrap-multiselect,brucejo75/meteor-bootstrap-multiselect
1f79b26808612ec1879394fad9ddc0ace5bbe1e6
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptors/forbidden-403.js
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptors/forbidden-403.js
/** * 403 Forbidden Network Error Interceptor * * This interceptor redirects to login page when * any 403 session expired error is returned in any of the * network requests */ var LOGIN_ROUTE = '/login'; var SESSION_EXPIRED = 'session_expired'; var subdomainMatch = /https?:\/\/([^.]+)/; module.exports = function (xhr, textStatus, errorThrown) { if (xhr.status !== 403) return; var error = xhr.responseJSON && xhr.responseJSON.error; if (error === SESSION_EXPIRED) { window.location.href = getRedirectURL(); } }; function getRedirectURL () { // We cannot get accountHost and username from configModel // and userModel because of static pages. God save static pages. var username = getUsernameFromURL(location.href); if (!username) { return ''; } var newURL = location.origin.replace(subdomainMatch, function () { return username; }); return location.protocol + '//' + newURL + LOGIN_ROUTE; } function getUsernameFromURL (url) { var usernameMatches = window.location.pathname.split('/'); if (usernameMatches.length > 2) { return usernameMatches[2]; } var subdomainMatches = url.match(subdomainMatch); if (subdomainMatches) { return subdomainMatches[1]; } return ''; }
/** * 403 Forbidden Network Error Interceptor * * This interceptor redirects to login page when * any 403 session expired error is returned in any of the * network requests */ var LOGIN_ROUTE = '/login?error=session_expired'; var SESSION_EXPIRED = 'session_expired'; var subdomainMatch = /https?:\/\/([^.]+)/; module.exports = function (xhr, textStatus, errorThrown) { if (xhr.status !== 403) return; var error = xhr.responseJSON && xhr.responseJSON.error; if (error === SESSION_EXPIRED) { window.location.href = getRedirectURL(); } }; function getRedirectURL () { // We cannot get accountHost and username from configModel // and userModel because of static pages. God save static pages. var username = getUsernameFromURL(location.href); if (!username) { return ''; } var newURL = location.origin.replace(subdomainMatch, function () { return username; }); return location.protocol + '//' + newURL + LOGIN_ROUTE; } function getUsernameFromURL (url) { var usernameMatches = window.location.pathname.split('/'); if (usernameMatches.length > 2) { return usernameMatches[2]; } var subdomainMatches = url.match(subdomainMatch); if (subdomainMatches) { return subdomainMatches[1]; } return ''; }
Add error parameter to forbidden interceptor
Add error parameter to forbidden interceptor
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
53317d97c5862ab96161066546fd3a744939ca2e
src/Orchard.Web/Modules/TinyMce/Scripts/orchard-tinymce.js
src/Orchard.Web/Modules/TinyMce/Scripts/orchard-tinymce.js
var mediaPlugins = ""; if (mediaPickerEnabled) { mediaPlugins += " mediapicker"; } if (mediaLibraryEnabled) { mediaPlugins += " medialibrary"; } tinyMCE.init({ selector: "textarea.tinymce", theme: "modern", schema: "html5", entity_encoding : "raw", plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime media nonbreaking table contextmenu directionality", "emoticons template paste textcolor colorpicker textpattern", "fullscreen autoresize" + mediaPlugins ], toolbar: "undo redo cut copy paste | bold italic | bullist numlist outdent indent formatselect | alignleft aligncenter alignright alignjustify ltr rtl | " + mediaPlugins + " link unlink charmap | code fullscreen", convert_urls: false, valid_elements: "*[*]", // Shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it. extended_valid_elements: "script[type|defer|src|language]", //menubar: false, //statusbar: false, skin: "orchardlightgray", language: language, auto_focus: autofocus, directionality: directionality, setup: function (editor) { $(document).bind("localization.ui.directionalitychanged", function(event, directionality) { editor.getBody().dir = directionality; }); } });
var mediaPlugins = ""; if (mediaPickerEnabled) { mediaPlugins += " mediapicker"; } if (mediaLibraryEnabled) { mediaPlugins += " medialibrary"; } tinyMCE.init({ selector: "textarea.tinymce", theme: "modern", schema: "html5", plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime media nonbreaking table contextmenu directionality", "emoticons template paste textcolor colorpicker textpattern", "fullscreen autoresize" + mediaPlugins ], toolbar: "undo redo cut copy paste | bold italic | bullist numlist outdent indent formatselect | alignleft aligncenter alignright alignjustify ltr rtl | " + mediaPlugins + " link unlink charmap | code fullscreen", convert_urls: false, valid_elements: "*[*]", // Shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it. extended_valid_elements: "script[type|defer|src|language]", //menubar: false, //statusbar: false, skin: "orchardlightgray", language: language, auto_focus: autofocus, directionality: directionality, setup: function (editor) { $(document).bind("localization.ui.directionalitychanged", function(event, directionality) { editor.getBody().dir = directionality; }); } });
Revert "Fixing that TinyMCE is encoding special chars"
Revert "Fixing that TinyMCE is encoding special chars" This reverts commit 188fabe233c3c9ebef04ccd29c1a07e8a520e882.
JavaScript
bsd-3-clause
armanforghani/Orchard,LaserSrl/Orchard,Serlead/Orchard,AdvantageCS/Orchard,tobydodds/folklife,geertdoornbos/Orchard,hannan-azam/Orchard,rtpHarry/Orchard,brownjordaninternational/OrchardCMS,jagraz/Orchard,gcsuk/Orchard,JRKelso/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,sfmskywalker/Orchard,rtpHarry/Orchard,neTp9c/Orchard,SzymonSel/Orchard,hbulzy/Orchard,JRKelso/Orchard,Praggie/Orchard,vairam-svs/Orchard,Dolphinsimon/Orchard,Fogolan/OrchardForWork,SzymonSel/Orchard,tobydodds/folklife,yersans/Orchard,dcinzona/Orchard,jimasp/Orchard,vairam-svs/Orchard,armanforghani/Orchard,phillipsj/Orchard,abhishekluv/Orchard,jtkech/Orchard,sfmskywalker/Orchard,hbulzy/Orchard,grapto/Orchard.CloudBust,dmitry-urenev/extended-orchard-cms-v10.1,dmitry-urenev/extended-orchard-cms-v10.1,abhishekluv/Orchard,johnnyqian/Orchard,JRKelso/Orchard,SzymonSel/Orchard,phillipsj/Orchard,Dolphinsimon/Orchard,LaserSrl/Orchard,hbulzy/Orchard,AdvantageCS/Orchard,SzymonSel/Orchard,LaserSrl/Orchard,grapto/Orchard.CloudBust,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,abhishekluv/Orchard,johnnyqian/Orchard,Codinlab/Orchard,armanforghani/Orchard,geertdoornbos/Orchard,jimasp/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,jimasp/Orchard,jersiovic/Orchard,JRKelso/Orchard,TalaveraTechnologySolutions/Orchard,jagraz/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,aaronamm/Orchard,mvarblow/Orchard,jchenga/Orchard,Dolphinsimon/Orchard,neTp9c/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,brownjordaninternational/OrchardCMS,sfmskywalker/Orchard,jersiovic/Orchard,hannan-azam/Orchard,SouleDesigns/SouleDesigns.Orchard,aaronamm/Orchard,mvarblow/Orchard,Praggie/Orchard,mvarblow/Orchard,Fogolan/OrchardForWork,grapto/Orchard.CloudBust,Praggie/Orchard,johnnyqian/Orchard,TalaveraTechnologySolutions/Orchard,omidnasri/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard,aaronamm/Orchard,hannan-azam/Orchard,TalaveraTechnologySolutions/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,phillipsj/Orchard,hbulzy/Orchard,omidnasri/Orchard,Dolphinsimon/Orchard,gcsuk/Orchard,IDeliverable/Orchard,brownjordaninternational/OrchardCMS,OrchardCMS/Orchard,hbulzy/Orchard,li0803/Orchard,ehe888/Orchard,gcsuk/Orchard,bedegaming-aleksej/Orchard,jersiovic/Orchard,omidnasri/Orchard,IDeliverable/Orchard,AdvantageCS/Orchard,jagraz/Orchard,gcsuk/Orchard,jersiovic/Orchard,li0803/Orchard,armanforghani/Orchard,fassetar/Orchard,dcinzona/Orchard,geertdoornbos/Orchard,Lombiq/Orchard,tobydodds/folklife,Fogolan/OrchardForWork,fassetar/Orchard,SouleDesigns/SouleDesigns.Orchard,xkproject/Orchard,jtkech/Orchard,Lombiq/Orchard,Serlead/Orchard,armanforghani/Orchard,tobydodds/folklife,hannan-azam/Orchard,abhishekluv/Orchard,vairam-svs/Orchard,dcinzona/Orchard,Codinlab/Orchard,LaserSrl/Orchard,fassetar/Orchard,Lombiq/Orchard,OrchardCMS/Orchard,omidnasri/Orchard,dcinzona/Orchard,fassetar/Orchard,grapto/Orchard.CloudBust,Lombiq/Orchard,tobydodds/folklife,dmitry-urenev/extended-orchard-cms-v10.1,xkproject/Orchard,geertdoornbos/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,bedegaming-aleksej/Orchard,abhishekluv/Orchard,jchenga/Orchard,ehe888/Orchard,Codinlab/Orchard,SouleDesigns/SouleDesigns.Orchard,johnnyqian/Orchard,grapto/Orchard.CloudBust,Lombiq/Orchard,AdvantageCS/Orchard,SzymonSel/Orchard,Serlead/Orchard,mvarblow/Orchard,IDeliverable/Orchard,TalaveraTechnologySolutions/Orchard,Praggie/Orchard,li0803/Orchard,rtpHarry/Orchard,neTp9c/Orchard,yersans/Orchard,aaronamm/Orchard,jtkech/Orchard,rtpHarry/Orchard,jtkech/Orchard,dcinzona/Orchard,Codinlab/Orchard,jersiovic/Orchard,OrchardCMS/Orchard,abhishekluv/Orchard,xkproject/Orchard,Praggie/Orchard,vairam-svs/Orchard,hannan-azam/Orchard,IDeliverable/Orchard,yersans/Orchard,yersans/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,aaronamm/Orchard,johnnyqian/Orchard,AdvantageCS/Orchard,omidnasri/Orchard,li0803/Orchard,fassetar/Orchard,LaserSrl/Orchard,Fogolan/OrchardForWork,omidnasri/Orchard,tobydodds/folklife,JRKelso/Orchard,SouleDesigns/SouleDesigns.Orchard,OrchardCMS/Orchard,xkproject/Orchard,phillipsj/Orchard,sfmskywalker/Orchard,rtpHarry/Orchard,ehe888/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,jtkech/Orchard,ehe888/Orchard,mvarblow/Orchard,omidnasri/Orchard,bedegaming-aleksej/Orchard,TalaveraTechnologySolutions/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,omidnasri/Orchard,jagraz/Orchard,vairam-svs/Orchard,Codinlab/Orchard,jagraz/Orchard,TalaveraTechnologySolutions/Orchard,omidnasri/Orchard,gcsuk/Orchard,li0803/Orchard,grapto/Orchard.CloudBust,jchenga/Orchard,ehe888/Orchard,jchenga/Orchard,Dolphinsimon/Orchard,neTp9c/Orchard,Serlead/Orchard,Fogolan/OrchardForWork,geertdoornbos/Orchard,yersans/Orchard,Serlead/Orchard,xkproject/Orchard,phillipsj/Orchard,jchenga/Orchard,SouleDesigns/SouleDesigns.Orchard,neTp9c/Orchard,sfmskywalker/Orchard,IDeliverable/Orchard
8feed977590b87f7936992c58235b99b91b2028a
src/js/controllers/navbar_top.js
src/js/controllers/navbar_top.js
'use strict'; /** * @ngdoc function * @name Pear2Pear.controller:NavbarTopCtrl * @description * # NavbarTop Ctrl */ angular.module('Pear2Pear') .controller( 'NavbarTopCtrl', [ 'SwellRTSession', '$scope', function(SwellRTSession, $scope){ var getSharedMode = function(){ if ($scope.project){ return $scope.project.shareMode; } return null; }; $scope.shareIcon = function shareIcon() { switch (getSharedMode()) { case 'link': return 'fa-link'; case 'public': return 'fa-globe'; default: return ''; } }; $scope.isShared = function(mode) { if ($scope.project){ return getSharedMode() === mode; } return false; }; $scope.setShared = function setShared(mode){ $scope.project.setShareMode(mode); }; $scope.timestampProjectAccess = function(){ $scope.project.timestampProjectAccess(); }; }]);
'use strict'; /** * @ngdoc function * @name Pear2Pear.controller:NavbarTopCtrl * @description * # NavbarTop Ctrl */ angular.module('Pear2Pear') .controller( 'NavbarTopCtrl', [ 'SwellRTSession', '$scope', function(SwellRTSession, $scope){ var getSharedMode = function(){ if ($scope.project){ return $scope.project.shareMode; } return null; }; $scope.$on('$locationChangeStart', function(event) { SwellRTSession.onLoad(function(){ if ($route.current.params.id){ pear.projects.find($route.current.params.id) .then(function(proxy) { $scope.project = proxy; }); } }); }); $scope.shareIcon = function shareIcon() { switch (getSharedMode()) { case 'link': return 'fa-link'; case 'public': return 'fa-globe'; default: return ''; } }; $scope.isShared = function(mode) { if ($scope.project){ return getSharedMode() === mode; } return false; }; $scope.setShared = function setShared(mode){ $scope.project.setShareMode(mode); }; $scope.timestampProjectAccess = function(){ $scope.project.timestampProjectAccess(); }; }]);
Revert "avoid unnecesary call to onLoad"
Revert "avoid unnecesary call to onLoad" This reverts commit 5a81300cb8a99c7428d9aeea26276d4415efcf64.
JavaScript
agpl-3.0
Grasia/teem,P2Pvalue/teem,P2Pvalue/teem,Grasia/teem,P2Pvalue/teem,Grasia/teem,P2Pvalue/pear2pear,P2Pvalue/pear2pear
4d398ea4ccecad68c5938c266506f8a4a30acc2d
src/javascript/binary/websocket_pages/user/telegram_bot.js
src/javascript/binary/websocket_pages/user/telegram_bot.js
const TelegramBot = (() => { 'use strict'; const form = '#frm_telegram_bot'; const onLoad = () => { const bot_name = 'binary_test_bot'; $(form).on('submit', (e) => { e.preventDefault(); const token = $('#token').val(); const url = `https://t.me/${bot_name}/?start=${token}`; window.location.assign(url); }); }; const onUnload = () => { $(form).off('submit'); }; return { onLoad : onLoad, onUnload: onUnload, }; })(); module.exports = TelegramBot;
const FormManager = require('../../common_functions/form_manager'); const TelegramBot = (() => { 'use strict'; const form = '#frm_telegram_bot'; const onLoad = () => { const bot_name = 'binary_test_bot'; FormManager.init(form, [ { selector: '#token', validations: ['req'], exclude_request: 1 } ]); FormManager.handleSubmit({ form_selector: form, fnc_response_handler: () => { const token = $('#token').val(); const url = `https://t.me/${bot_name}/?start=${token}`; window.location.assign(url); } }); }; const onUnload = () => { $(form).off('submit'); }; return { onLoad: onLoad, onUnload: onUnload, }; })(); module.exports = TelegramBot;
Rewrite code to use formManager
Rewrite code to use formManager
JavaScript
apache-2.0
raunakkathuria/binary-static,ashkanx/binary-static,negar-binary/binary-static,4p00rv/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static,binary-com/binary-static,kellybinary/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,binary-static-deployed/binary-static,binary-com/binary-static,kellybinary/binary-static,kellybinary/binary-static,negar-binary/binary-static,raunakkathuria/binary-static,4p00rv/binary-static,ashkanx/binary-static
d6593eeea21a624ff0bb1b1d43f433f77ae55e47
src/reducers/reducer_workload.js
src/reducers/reducer_workload.js
export default function(state={}, action) { switch(action.type) { case 'example_data': return 'The action controller worked properly' default: return state; } }
import { FETCH_OPPS } from '../actions'; export default function(state={}, action) { switch(action.type) { case FETCH_OPPS: return action.payload default: return state; } }
Modify switch statement in WorkloadReducer
Modify switch statement in WorkloadReducer
JavaScript
mit
danshapiro-optimizely/bandwidth,danshapiro-optimizely/bandwidth
caf0a2289145c699a853aa75449bbaebacb0b7e9
webpack.production.config.js
webpack.production.config.js
'use strict' const webpack = require('webpack') const path = require('path') const configuration = { entry: path.resolve(__dirname, 'app'), output: { path: path.resolve(__dirname, 'public'), filename: '[name].js' }, module: { loaders: [ { test: /\.js?$/, loader: 'react-hot-loader', include: path.join(__dirname, 'app') }, { test: /\.js?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader' ] } ] }, plugins: [ new webpack.DefinePlugin( { 'process.env.NODE_ENV': JSON.stringify('production') } ), new webpack.optimize.AggressiveMergingPlugin(), new webpack.optimize.OccurrenceOrderPlugin() ], devtool: 'cheap-source-map', cache: true } module.exports = configuration
'use strict' const webpack = require('webpack') const path = require('path') var HtmlWebpackPlugin = require('html-webpack-plugin') const configuration = { entry: [ path.resolve(__dirname, 'app') ], output: { path: path.resolve(__dirname, 'public/build/'), filename: '[hash].js' }, module: { loaders: [ { test: /\.js?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader' ] }, { test: /\.html$/, loaders: [ 'html-loader' ] } ] }, plugins: [ new webpack.DefinePlugin( { 'process.env.NODE_ENV': JSON.stringify('production') } ), new HtmlWebpackPlugin( { template: path.resolve(__dirname, 'public/index.html'), favicon: path.resolve(__dirname, 'public/favicon.ico'), inject: true, minify: {} } ), new webpack.optimize.AggressiveMergingPlugin(), new webpack.optimize.OccurrenceOrderPlugin() ], devtool: 'cheap-source-map', cache: true } module.exports = configuration
Add a new build process for the production environment.
Add a new build process for the production environment.
JavaScript
mit
rhberro/the-react-client,rhberro/the-react-client
048cc348d0bd0b614e05913cc5619b54b174463e
src/server/services/discovery.js
src/server/services/discovery.js
import Promise from 'bluebird'; import { lookupServiceAsync } from '../utils/lookup-service'; function findService(fullyQualifiedName) { // Get just the service name from the fully qualified name let nameParts = fullyQualifiedName.split('.'); let serviceName = nameParts[nameParts.length - 1]; // Insert a dash before any capital letters, convert to lowercase, and remove any leading dash serviceName = serviceName.replace(/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/g, '-$&').toLowerCase(); if (serviceName.startsWith('-')) { serviceName = serviceName.substr(1); } // We should have something like 'video-catalog-service' now, so try and find the service return lookupServiceAsync(serviceName).then(hosts => hosts[0]); } /** * Finds the location for a service from the fully qualified name and returns a Promise that resolves to a * string of the IP:Port where that service can be found. */ export const findServiceAsync = Promise.method(findService);
import Promise from 'bluebird'; import { lookupServiceAsync } from '../utils/lookup-service'; function findService(fullyQualifiedName) { // Get just the service name from the fully qualified name let nameParts = fullyQualifiedName.split('.'); let serviceName = nameParts[nameParts.length - 1]; // We should have something like 'video-catalog-service' now, so try and find the service return lookupServiceAsync(serviceName).then(hosts => hosts[0]); } /** * Finds the location for a service from the fully qualified name and returns a Promise that resolves to a * string of the IP:Port where that service can be found. */ export const findServiceAsync = Promise.method(findService);
Use the short service name when resolving Grpc services
Use the short service name when resolving Grpc services
JavaScript
apache-2.0
KillrVideo/killrvideo-web,KillrVideo/killrvideo-web,KillrVideo/killrvideo-web
fb8473d0e16f20b8828dd1692206e86497bcf507
client/MobiApp.js
client/MobiApp.js
Geolocation.latLng() Template.newIssue.events({ 'submit form': function(){ event.preventDefault(); var title = event.target.title.value; var description = event.target.description.value; var imageURL = Session.get('imageURL'); console.log(title, description); if (title && description && Geolocation.latLng()) { Issues.insert({ title: title, description: description, status: 'open', lat: Geolocation.latLng().lat, lng: Geolocation.latLng().lng, userID: Meteor.userId(), imageURL: imageURL, createdAt: new Date(), lastModified: new Date() }); Router.go('/issues-list'); } else { console.log("form not valid"); } } }); Template.dashboard.helpers({ title: function(){ return "Status of Submitted" }, issues: function (){ // Show newest tasks at the top return Issues.find({'userID': this.userId}, {sort: {createdAt: 1}}) } }); Template.task.helpers({ label_mapper: function(par){ var dict = {}; //Updates labels for submitted issues dict["open"] = "-warning"; dict["rejected"] = "-danger"; dict["solved"] = "-success"; dict["pending"] = "-info" return dict[par] } });
Geolocation.latLng() Template.newIssue.events({ 'submit form': function(){ event.preventDefault(); var title = event.target.title.value; var description = event.target.description.value; var imageURL = Session.get('imageURL'); console.log(title, description); if (title && description && Geolocation.latLng()) { Issues.insert({ title: title, description: description, status: 'open', lat: Geolocation.latLng().lat, lng: Geolocation.latLng().lng, userID: Meteor.userId(), imageURL: imageURL, createdAt: new Date(), lastModified: new Date() }); Router.go('/issues-list'); } else { console.log("form not valid"); } } }); Template.IssuesList.helpers({ title: function(){ return "Status of Submitted" }, issues: function (){ // Show newest tasks at the top return Issues.find({'userID': Meteor.userId()}, {sort: {createdAt: 1}}) } }); Template.task.helpers({ label_mapper: function(par){ var dict = {}; //Updates labels for submitted issues dict["open"] = "-warning"; dict["rejected"] = "-danger"; dict["solved"] = "-success"; dict["pending"] = "-info" return dict[par] } });
Fix issue list after change of authentication package
Fix issue list after change of authentication package
JavaScript
agpl-3.0
kennyzlei/MobiApp,kennyzlei/MobiApp
593ec57633fbef471f09501e0c886899e51bd467
code/geosearch.js
code/geosearch.js
// GEOSEARCH ///////////////////////////////////////////////////////// window.setupGeosearch = function() { $('#geosearch').keypress(function(e) { if((e.keyCode ? e.keyCode : e.which) != 13) return; var search = $(this).val(); if (!runHooks('geoSearch', search)) { return; } $.getJSON(NOMINATIM + encodeURIComponent(search), function(data) { if(!data || !data[0]) return; var b = data[0].boundingbox; if(!b) return; var southWest = new L.LatLng(b[0], b[2]), northEast = new L.LatLng(b[1], b[3]), bounds = new L.LatLngBounds(southWest, northEast); window.map.fitBounds(bounds); if(window.isSmartphone()) window.smartphone.mapButton.click(); }); e.preventDefault(); }); $('#geosearchwrapper img').click(function(){ map.locate({setView : true});; }); }
// GEOSEARCH ///////////////////////////////////////////////////////// window.setupGeosearch = function() { $('#geosearch').keypress(function(e) { if((e.keyCode ? e.keyCode : e.which) != 13) return; var search = $(this).val(); if (!runHooks('geoSearch', search)) { return; } $.getJSON(NOMINATIM + encodeURIComponent(search), function(data) { if(!data || !data[0]) return; var b = data[0].boundingbox; if(!b) return; var southWest = new L.LatLng(b[0], b[2]), northEast = new L.LatLng(b[1], b[3]), bounds = new L.LatLngBounds(southWest, northEast); window.map.fitBounds(bounds); if(window.isSmartphone()) window.smartphone.mapButton.click(); }); e.preventDefault(); }); $('#geosearchwrapper img').click(function(){ map.locate({setView : true, maxZoom: 13});; }); }
Set maxZoom = 13 for desktop locate button too.
Set maxZoom = 13 for desktop locate button too.
JavaScript
isc
tony2001/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion
b9399f212ba6744374a0a54d4b06b21200865bb4
src/server/pages.js
src/server/pages.js
import nextRoutes from 'next-routes'; const pages = nextRoutes(); pages .add('signin', '/signin/:token?') .add('createEvent', '/:parentCollectiveSlug/events/(new|create)') .add('events-iframe', '/:collectiveSlug/events/iframe') .add('event', '/:parentCollectiveSlug/events/:eventSlug') .add('editEvent', '/:parentCollectiveSlug/events/:eventSlug/edit') .add('events', '/:collectiveSlug/events') .add('tiers', '/:collectiveSlug/tiers') .add('editTiers', '/:collectiveSlug/tiers/edit') .add('orderCollectiveTier', '/:collectiveSlug/order/:TierId/:amount?/:interval?', 'createOrder') .add('orderEventTier', '/:collectiveSlug/events/:eventSlug/order/:TierId', 'createOrder') .add('donate', '/:collectiveSlug/:verb(donate|pay|contribute)/:amount?/:interval?', 'createOrder') .add('tiers-iframe', '/:collectiveSlug/tiers/iframe') .add('transactions', '/:collectiveSlug/transactions') .add('nametags', '/:parentCollectiveSlug/events/:eventSlug/nametags') .add('button', '/:collectiveSlug/:verb(contribute|donate)/button') .add('collective', '/:slug') .add('editCollective', '/:slug/edit') module.exports = pages;
import nextRoutes from 'next-routes'; const pages = nextRoutes(); pages .add('widgets', '/widgets') .add('tos', '/tos') .add('privacypolicy', '/privacypolicy') .add('signin', '/signin/:token?') .add('button', '/:collectiveSlug/:verb(contribute|donate)/button') .add('createEvent', '/:parentCollectiveSlug/events/(new|create)') .add('events-iframe', '/:collectiveSlug/events/iframe') .add('event', '/:parentCollectiveSlug/events/:eventSlug') .add('editEvent', '/:parentCollectiveSlug/events/:eventSlug/edit') .add('events', '/:collectiveSlug/events') .add('tiers', '/:collectiveSlug/tiers') .add('editTiers', '/:collectiveSlug/tiers/edit') .add('orderCollectiveTier', '/:collectiveSlug/order/:TierId/:amount?/:interval?', 'createOrder') .add('orderEventTier', '/:collectiveSlug/events/:eventSlug/order/:TierId', 'createOrder') .add('donate', '/:collectiveSlug/:verb(donate|pay|contribute)/:amount?/:interval?', 'createOrder') .add('tiers-iframe', '/:collectiveSlug/tiers/iframe') .add('transactions', '/:collectiveSlug/transactions') .add('expenses', '/:collectiveSlug/expenses') .add('nametags', '/:parentCollectiveSlug/events/:eventSlug/nametags') .add('collective', '/:slug') .add('editCollective', '/:slug/edit') module.exports = pages;
Fix for /widgets, /tos, /privacypolicy, /:slug/:verb/button
Fix for /widgets, /tos, /privacypolicy, /:slug/:verb/button
JavaScript
mit
OpenCollective/frontend
b27471e3ae289e4b3e97302ff7a5e9cc4ace59e8
src/Result.js
src/Result.js
'use strict' var chalk = require('chalk') var deepEqual = require('deep-equal') var indent = require('./indent') var os = require('os') const CHECK = '\u2713' const CROSS = '\u2717' const PASS_COLOR = 'green' const FAIL_COLOR = 'red' module.exports = class Result { constructor (runnable, options) { options = options || {} this.runnable = runnable this.error = options.error this.results = options.results || [] this.actual = options.actual this.expected = options.expected if (this.error === undefined && (this.actual !== undefined || this.expected !== undefined)) { this.error = !deepEqual(this.actual, this.expected, { strict: true }) } } isErroring () { return Boolean(this.error || this.results.some(result => result.isErroring())) } toString () { var isErroring = this.isErroring() var status = isErroring ? CROSS : CHECK var color = isErroring ? FAIL_COLOR : PASS_COLOR return chalk[color](`${status} ${this.runnable}`) } toTree () { var indented = this.results.map(result => indent(result.toTree())) return [this.toString()].concat(indented).join(os.EOL) } }
'use strict' var chalk = require('chalk') var deepEqual = require('deep-equal') var indent = require('./indent') var os = require('os') const CHECK = '✓' const CROSS = '✗' const PASS_COLOR = 'green' const FAIL_COLOR = 'red' module.exports = class Result { constructor (runnable, options) { options = options || {} this.runnable = runnable this.error = options.error this.results = options.results || [] this.actual = options.actual this.expected = options.expected if (this.error === undefined && (this.actual !== undefined || this.expected !== undefined)) { this.error = !deepEqual(this.actual, this.expected, { strict: true }) } } isErroring () { return Boolean(this.error || this.results.some(result => result.isErroring())) } toString () { var isErroring = this.isErroring() var status = isErroring ? CROSS : CHECK var color = isErroring ? FAIL_COLOR : PASS_COLOR return chalk[color](`${status} ${this.runnable}`) } toTree () { var indented = this.results.map(result => indent(result.toTree())) return [this.toString()].concat(indented).join(os.EOL) } }
Use unicode special characters directly in source
Use unicode special characters directly in source
JavaScript
isc
nickmccurdy/purespec
1f8b40ecfe9a2c7d7c31a0f71a72049dc413749d
src/issue-strategies/bug-maintenance.js
src/issue-strategies/bug-maintenance.js
export function apply(issue, jiraClientAPI) { if(issue === null || issue.fields.status.statusCategory.colorName !== 'yellow') { return Promise.reject(new Error(`Cannot commit against this issue ${issue.key}`)); } return Promise.resolve(true); }
export function apply(issue, jiraClientAPI) { if(issue === null || issue.fields.status.statusCategory.colorName !== 'yellow') { return Promise.reject(new Error(`Cannot commit against this issue ${issue.key}. Make sure the issue exists and has a yellow status`)); } return Promise.resolve(true); }
Add additional issue status error info
Add additional issue status error info Closes #23
JavaScript
mit
DarriusWrightGD/jira-precommit-hook,TWExchangeSolutions/jira-precommit-hook
21edc4ec471a55a0dce9dd2c7d3e84a5576aaf84
src/js/graphic/background/background.js
src/js/graphic/background/background.js
import Geometric from './geometric/geometric.js' export default class Background { static draw(p) { Background.changeColor(p) Background.translateCamera(p) Background.translateCameraByMouse(p) Geometric.draw(p) } static changeColor(p) { const hexColorMax = 255 const radianX2 = p.PI * 2 const fps = 60 const fpsGear = 1 / 20 const radianPerFrame = radianX2 / fps const radianPerFrameGeared = radianPerFrame * fpsGear const fpsReal = fps / fpsGear const frame = p.frameCount % fpsReal const radian = radianPerFrameGeared * frame const sine = p.sin(radian) const sineMapped1 = (sine + 1) / 2 const hexColor = sineMapped1 * hexColorMax p.background(hexColor) } static translateCamera(p) { const xTranslate = p.frameCount * 0.01 const yTranslate = 0 const zTranslate = -(p.windowHeight / 2) p.translate(xTranslate, yTranslate, zTranslate) } static translateCameraByMouse(p) { const xTranslate = -p.mouseX / 10 const yTranslate = -p.mouseY / 10 p.translate(xTranslate, yTranslate) } }
import Geometric from './geometric/geometric.js' export default class Background { static draw(p) { Background.changeColor(p) Background.translateCamera(p) Background.translateCameraByMouse(p) Geometric.draw(p) } static changeColor(p) { const hexColorMax = 255 const radianX2 = p.PI * 2 const fps = 60 const fpsGear = 1 / 20 const radianPerFrame = radianX2 / fps const radianPerFrameGeared = radianPerFrame * fpsGear const fpsReal = fps / fpsGear const frame = p.frameCount % fpsReal const radian = radianPerFrameGeared * frame const sine = p.sin(radian) const sineMapped1 = (sine + 1) / 2 const hexColor = sineMapped1 * hexColorMax p.background(hexColor) } static translateCamera(p) { const xTranslate = p.frameCount * 0.01 const yTranslate = 0 let zTranslate = -(p.width / 3) if (window.screen.width < 600) { zTranslate = window.screen.width / 5 } p.translate(xTranslate, yTranslate, zTranslate) } static translateCameraByMouse(p) { const xTranslate = -p.mouseX / 10 const yTranslate = -p.mouseY / 10 p.translate(xTranslate, yTranslate) } }
Fix main camera zTranslation responsive issue
Fix main camera zTranslation responsive issue
JavaScript
mit
yuki-nit2a/yuki.nit2a.com,yuki-nit2a/yuki.nit2a.com
44ddb35699ed2a7cff9e5dc2f4b36823931a57b6
app/process_request.js
app/process_request.js
var requirejs = require('requirejs'); var PageConfig = requirejs('page_config'); var get_dashboard_and_render = require('./server/mixins/get_dashboard_and_render'); var renderContent = function (req, res, model) { model.set(PageConfig.commonConfig(req)); var ControllerClass = model.get('controller'); var controller = new ControllerClass({ model: model, url: req.originalUrl }); controller.once('ready', function () { res.set('Cache-Control', 'public, max-age=600'); if (model.get('published') !== true) { res.set('X-Robots-Tag', 'none'); } req['spotlight-dashboard-slug'] = model.get('slug'); res.send(controller.html); }); controller.render({ init: true }); return controller; }; var setup = function (req, res) { var client_instance = setup.get_dashboard_and_render(req, res, setup.renderContent); //I have no idea what this does, can't find anything obvious in the docs or this app. client_instance.set('script', true); client_instance.setPath(req.url.replace('/performance', '')); }; setup.renderContent = renderContent; setup.get_dashboard_and_render = get_dashboard_and_render; module.exports = setup;
var requirejs = require('requirejs'); var PageConfig = requirejs('page_config'); var get_dashboard_and_render = require('./server/mixins/get_dashboard_and_render'); var renderContent = function (req, res, model) { model.set(PageConfig.commonConfig(req)); var ControllerClass = model.get('controller'); var controller = new ControllerClass({ model: model, url: req.originalUrl }); controller.once('ready', function () { res.set('Cache-Control', 'public, max-age=600'); if (model.get('published') !== true) { res.set('X-Robots-Tag', 'none'); } req['spotlight-dashboard-slug'] = model.get('slug'); res.send(controller.html); }); controller.render({ init: true }); return controller; }; var setup = function (req, res) { var client_instance = setup.get_dashboard_and_render(req, res, setup.renderContent); client_instance.set('script', true); client_instance.setPath(req.url.replace('/performance', '')); }; setup.renderContent = renderContent; setup.get_dashboard_and_render = get_dashboard_and_render; module.exports = setup;
Remove comment about client_instance script
Remove comment about client_instance script The script attribute of a client_instance is tested in the view, for example in body-end.html: <% if (model.get('script')) { %> It can be set to false to disable including of our rather large JavaScript assets.
JavaScript
mit
alphagov/spotlight,tijmenb/spotlight,alphagov/spotlight,keithiopia/spotlight,alphagov/spotlight,tijmenb/spotlight,keithiopia/spotlight,keithiopia/spotlight,tijmenb/spotlight
8bd45a62113fa47b03217887e027afe0bfdd04dc
lib/util/parse.js
lib/util/parse.js
// Code based largely on this module: // https://www.npmjs.org/package/git-credential function parseOutput(data, callback) { var output = {}; if (data) { output = data.toString('utf-8') .split('\n') .map(function (line) { return line.split('='); }) .filter(function (lineItems) { // Filter out empty lines return lineItems.length === 2; }) .reduce(function (obj, val) { obj[val[0].trim()] = val[1].trim(); return obj; }, {}); } callback(null, output); } module.exports = parseOutput;
// Code based largely on this module: // https://www.npmjs.org/package/git-credential function parseOutput(data, callback) { var output = {}; if (data) { output = data.toString('utf-8') .split('\n') .map(function (line) { var index = line.indexOf('='); if (index !== -1) { return [line.substr(0, index), line.substr(index + 1)]; } else { return line; } }) .filter(function (lineItems) { // Filter out empty lines return lineItems.length === 2; }) .reduce(function (obj, val) { obj[val[0].trim()] = val[1].trim(); return obj; }, {}); } callback(null, output); } module.exports = parseOutput;
Return password when it contains =
Return password when it contains = Fixes #3
JavaScript
mit
nwinkler/git-credential-helper
8671f86ecc9ece19dd1739edfb9f3a6cc92af12e
reducer/stationboards.js
reducer/stationboards.js
const initState = {}; export default (state = initState, action) => { switch (action.type) { case "GET_STATIONBOARD_REQUESTED": const { stationId } = action.payload; return { ...state, [stationId]: { data: [], pending: true, }, }; case "GET_STATIONBOARD_FULFILLED": const { stationboard } = action.payload; return { ...state, [action.payload.stationId]: { ...state[action.payload.stationId], data: stationboard.map( ({ category, number, to, stop: { departureTimestamp }, }) => ({ category, number, to, departureTimestamp, }), ), pending: false, }, }; default: return state; } };
const initState = {}; export default (state = initState, action) => { switch (action.type) { case "GET_STATIONBOARD_REQUESTED": const { stationId } = action.payload; return { ...state, [stationId]: { data: [], pending: true, }, }; case "GET_STATIONBOARD_FULFILLED": const { stationboard } = action.payload; return { ...state, [action.payload.stationId]: { ...state[action.payload.stationId], data: stationboard.map( ({ category, number, to, stop: { departureTimestamp }, passList: checkpoints, }) => ({ category, number, to, departureTimestamp, checkpoints, }), ), pending: false, }, }; default: return state; } };
Add checkpoints to the stationboard objects
Add checkpoints to the stationboard objects
JavaScript
mit
rafaelkallis/hackzurich2017
3bf6e52f7955fd688de4c90e6f1d5fda241b45d2
builder-bob.js
builder-bob.js
/** * 12-22-2016 * ~~ Scott Johnson */ /** List jshint ignore directives here. **/ /* jslint node: true */ /* jshint esversion: 6 */ /*eslint-env es6*/ // Stop jshint from complaining about the promise.catch() syntax. /* jslint -W024 */ var util = require( './lib/bob-util.js' ); var Batch = require( './lib/bob-batch.js' ); var Bob = module.exports = {}; Bob.createBatch = function(){ var self = Batch.apply( this, arguments ); return self; };// /createBatch() Bob.watch = function(){ return util.watch.apply( this, arguments ); };// /watch() Bob.log = function(){ return util.log.apply( this, arguments ); };// /log()
/** * 12-22-2016 * ~~ Scott Johnson */ /** List jshint ignore directives here. **/ /* jslint node: true */ /* jshint esversion: 6 */ /*eslint-env es6*/ // Stop jshint from complaining about the promise.catch() syntax. /* jslint -W024 */ var util = require( './lib/bob-util.js' ); var Batch = require( './lib/bob-batch.js' ); var Bob = module.exports = {}; Bob.createBatch = function(){ var self = Batch.apply( this, arguments ); return self; };// /createBatch() Bob.createJob = function(){ var batch = Bob.createBatch(); return batch.createJob.apply( batch, arguments ); };// /createJob() Bob.watch = function(){ return util.watch.apply( this, arguments ); };// /watch() Bob.log = function(){ return util.log.apply( this, arguments ); };// /log()
Create jobs directly through bob.
Create jobs directly through bob.
JavaScript
mit
lucentminds/builder-bob
3fba858b12cd7d3d36fdc8618e2e6c1f11a83263
challengers.js
challengers.js
// Welcome! // Add your github user if you accepted the challenge! var players = [ 'raphamorim', 'israelst', 'afonsopacifer', 'rafaelfragosom', 'brunokinoshita', 'paulinhoerry', 'enieber', 'alanrsoares' ]; module.exports = players;
// Welcome! // Add your github user if you accepted the challenge! var players = [ 'raphamorim', 'israelst', 'afonsopacifer', 'rafaelfragosom', 'brunokinoshita', 'paulinhoerry', 'enieber', 'alanrsoares', 'brunodsgn' ]; module.exports = players;
Add brunodsgn as new challenger
Add brunodsgn as new challenger
JavaScript
mit
joselitojunior/write-code-every-day,vitorleal/write-code-every-day,raphamorim/write-code-every-day,mabrasil/write-code-every-day,Gcampes/write-code-every-day,arthurvasconcelos/write-code-every-day,cesardeazevedo/write-code-every-day,hocraveiro/write-code-every-day,mauriciojunior/write-code-every-day,rtancman/write-code-every-day,ogilvieira/write-code-every-day,rafaelstz/write-code-every-day,pablobfonseca/write-code-every-day,hocraveiro/write-code-every-day,fredericksilva/write-code-every-day,viniciusdacal/write-code-every-day,willianjusten/write-code-every-day,Pompeu/write-code-every-day,Gcampes/write-code-every-day,pablobfonseca/write-code-every-day,ogilvieira/write-code-every-day,joselitojunior/write-code-every-day,AgtLucas/write-code-every-day,jackmakiyama/write-code-every-day,gpedro/write-code-every-day,jozadaquebatista/write-code-every-day,jackmakiyama/write-code-every-day,letanloc/write-code-every-day,guilouro/write-code-every-day,welksonramos/write-code-every-day,pablobfonseca/write-code-every-day,fdaciuk/write-code-every-day,rafaelfragosom/write-code-every-day,marabesi/write-code-every-day,guidiego/write-code-every-day,gpedro/write-code-every-day,edueo/write-code-every-day,arthurvasconcelos/write-code-every-day,vinimdocarmo/write-code-every-day,beni55/write-code-every-day,Rodrigo54/write-code-every-day,Rodrigo54/write-code-every-day,willianjusten/write-code-every-day,ppamorim/write-code-every-day,marabesi/write-code-every-day,raphamorim/write-code-every-day,ppamorim/write-code-every-day,beni55/write-code-every-day,AgtLucas/write-code-every-day,michelwilhelm/write-code-every-day,diegosaraujo/write-code-every-day,AbraaoAlves/write-code-every-day,arthurvasconcelos/write-code-every-day,fdaciuk/write-code-every-day,andersonweb/write-code-every-day,guidiego/write-code-every-day,rafaelfragosom/write-code-every-day,mabrasil/write-code-every-day,jhonmike/write-code-every-day,rafael-neri/write-code-every-day,jhonmike/write-code-every-day,rafael-neri/write-code-every-day,edueo/write-code-every-day,michelwilhelm/write-code-every-day,welksonramos/write-code-every-day,chocsx/write-code-every-day,AbraaoAlves/write-code-every-day,rafaelstz/write-code-every-day,jozadaquebatista/write-code-every-day,raphamorim/write-code-every-day,vinimdocarmo/write-code-every-day,chocsx/write-code-every-day,rtancman/write-code-every-day,vitorleal/write-code-every-day,mauriciojunior/write-code-every-day,cesardeazevedo/write-code-every-day,viniciusdacal/write-code-every-day,Pompeu/write-code-every-day,letanloc/write-code-every-day,guilouro/write-code-every-day,diegosaraujo/write-code-every-day,andersonweb/write-code-every-day,fredericksilva/write-code-every-day
86bd1cf69106768f9a576278f569700b4a48ee1c
src/components/BodyAttributes.js
src/components/BodyAttributes.js
import { Component, Children, PropTypes } from "react"; import withSideEffect from "react-side-effect"; const supportedHTML4Attributes = { "bgColor": "bgcolor" }; class BodyAttributes extends Component { render() { return Children.only(this.props.children); } } BodyAttributes.propTypes = { children: PropTypes.node.isRequired }; function reducePropsToState(propsList) { const attrs = {}; propsList.forEach(function (props) { const transformedAttrs = transformHTML4Props(props); Object.assign(attrs, props, transformedAttrs); }); return attrs; } function handleStateChangeOnClient(attrs) { for (const key in attrs) { document.body.setAttribute(key, attrs[key]); } } function transformHTML4Props(props) { const transformedProps = {}; // Provide support for HTML4 attributes on the body tag for // e-mail purposes. Convert tags to ones oy-vey can translate // during the render. Object.keys(supportedHTML4Attributes).forEach(propName => { if (props.hasOwnProperty(propName)) { const name = supportedHTML4Attributes[propName]; const value = props[propName]; const transformedProp = { [`data-oy-${name}`]: value }; Object.assign(transformedProps, transformedProp); } }); return transformedProps; } export default withSideEffect( reducePropsToState, handleStateChangeOnClient )(BodyAttributes);
import { Component, Children, PropTypes } from "react"; import withSideEffect from "react-side-effect"; const supportedHTML4Attributes = { "bgColor": "bgcolor" }; class BodyAttributes extends Component { render() { return Children.only(this.props.children); } } BodyAttributes.propTypes = { children: PropTypes.node.isRequired }; function reducePropsToState(propsList) { const attrs = {}; propsList.forEach(function (props) { const transformedAttrs = transformHTML4Props(props); Object.assign(attrs, props, transformedAttrs); }); return attrs; } function handleStateChangeOnClient(attrs) { for (const key in attrs) { document.body.setAttribute(key, attrs[key]); } } function transformHTML4Props(props) { const transformedProps = {}; /* * Provide support for HTML4 attributes on the body tag for * e-mail purposes. Convert tags to ones oy-vey can translate * during the render. * * Note: Only attributes that are white-listed by oy-vey will be rendered * */ Object.keys(supportedHTML4Attributes).forEach(propName => { if (props.hasOwnProperty(propName)) { const name = supportedHTML4Attributes[propName]; const value = props[propName]; const transformedProp = { [`data-oy-${name}`]: value }; Object.assign(transformedProps, transformedProp); } }); return transformedProps; } export default withSideEffect( reducePropsToState, handleStateChangeOnClient )(BodyAttributes);
Improve comment around transformed attributes
Improve comment around transformed attributes
JavaScript
mit
TrueCar/gluestick-shared,TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick
0e4cebad2acb269667b14ddc58cb3bb172809234
katas/es6/language/block-scoping/let.js
katas/es6/language/block-scoping/let.js
// block scope - let // To do: make all tests pass, leave the asserts unchanged! describe('`let` restricts the scope of the variable to the current block', () => { describe('`let` vs. `var`', () => { it('`var` works as usual', () => { if (true) { var varX = true; } assert.equal(varX, true); }); it('`let` restricts scope to inside the block', () => { if(true) { let letX = true; } assert.throws(() => console.log(letX)); }); }); it('`let` use in `for` loops', () => { let obj = {x: 1}; for (let key in obj) {} assert.throws(() => console.log(key)); }); it('create artifical scope, using curly braces', () => { { let letX = true; } assert.throws(() => console.log(letX)); }); });
// block scope - let // To do: make all tests pass, leave the asserts unchanged! describe('`let` restricts the scope of the variable to the current block', () => { describe('`let` vs. `var`', () => { it('`var` works as usual', () => { if (true) { let varX = true; } assert.equal(varX, true); }); it('`let` restricts scope to inside the block', () => { if (true) { var letX = true; } assert.throws(() => console.log(letX)); }); }); describe('`let` usage', () => { it('`let` use in `for` loops', () => { let obj = {x: 1}; for (var key in obj) {} assert.throws(() => console.log(key)); }); it('create artifical scope, using curly braces', () => { { var letX = true; } assert.throws(() => console.log(letX)); }); }); });
Make it nicer and break it, to be a kata :).
Make it nicer and break it, to be a kata :).
JavaScript
mit
cmisenas/katas,JonathanPrince/katas,cmisenas/katas,rafaelrocha/katas,JonathanPrince/katas,ehpc/katas,cmisenas/katas,rafaelrocha/katas,JonathanPrince/katas,Semigradsky/katas,tddbin/katas,ehpc/katas,tddbin/katas,Semigradsky/katas,Semigradsky/katas,rafaelrocha/katas,tddbin/katas,ehpc/katas
9fd827df81a400df1577c3405a646e26a1b17c51
src/exampleApp.js
src/exampleApp.js
"use strict"; // For conditions of distribution and use, see copyright notice in LICENSE /* * @author Tapani Jamsa * @author Erno Kuusela * @author Toni Alatalo * Date: 2013 */ var app = new Application(); app.host = "localhost"; // IP to the Tundra server app.port = 2345; // and port to the server app.start(); // app.viewer.useCubes = true; // Use wireframe cube material for all objects app.connect(app.host, app.port);
"use strict"; // For conditions of distribution and use, see copyright notice in LICENSE /* * @author Tapani Jamsa * @author Erno Kuusela * @author Toni Alatalo * Date: 2013 */ var app = new Application(); var host = "localhost"; // IP to the Tundra server var port = 2345; // and port to the server app.start(); // app.viewer.useCubes = true; // Use wireframe cube material for all objects app.connect(host, port);
Make host and port standard variables
Make host and port standard variables
JavaScript
apache-2.0
playsign/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra,AlphaStaxLLC/WebTundra,playsign/WebTundra,AlphaStaxLLC/WebTundra,realXtend/WebTundra
7dcb583e7425bff4964b1e3ce52c745c512b1489
src/game/index.js
src/game/index.js
import Phaser from 'phaser-ce'; import { getConfig } from './config'; import TutorialState from './TutorialState'; export default class WreckSam { constructor() { const config = getConfig(); this.game = new Phaser.Game(config); this.game.state.add('tutorial', new TutorialState()); } start(state) { this.game.state.start(state); } pause(){ this.game.lockRender = true; } unpause(){ this.game.lockRender = false; } destroy() { this.game.destroy(); this.game = null; } }
import Phaser from 'phaser-ce'; import { getConfig } from './config'; import TutorialState from './TutorialState'; export default class WreckSam { constructor() { const config = getConfig(); this.game = new Phaser.Game(config); this.game.state.add('tutorial', new TutorialState()); } start(state) { this.game.state.start(state); } pause(){ this.game.paused = true; } unpause(){ this.game.paused = false; } destroy() { this.game.destroy(); this.game = null; } }
Use game paused property instead of lockRender
Use game paused property instead of lockRender
JavaScript
mit
marc1404/WreckSam,marc1404/WreckSam
ec679a27b227877a5e383af2bf9deabf0a3c2072
loader.js
loader.js
// Loader to create the Ember.js application /*global require */ window.App = require('ghost/app')['default'].create();
// Loader to create the Ember.js application /*global require */ if (!window.disableBoot) { window.App = require('ghost/app')['default'].create(); }
Add initial client unit test.
Add initial client unit test.
JavaScript
mit
kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,airycanon/Ghost-Admin,JohnONolan/Ghost-Admin,airycanon/Ghost-Admin,TryGhost/Ghost-Admin,JohnONolan/Ghost-Admin,TryGhost/Ghost-Admin,dbalders/Ghost-Admin,acburdine/Ghost-Admin,kevinansfield/Ghost-Admin,dbalders/Ghost-Admin
e8a8fed47acf2a7bb9a72720e7c92fbfa6c94952
src/lintStream.js
src/lintStream.js
import postcss from "postcss" import fs from "fs" import gs from "glob-stream" import rcLoader from "rc-loader" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { const stylelintConfig = config || rcLoader("stylelint") if (!stylelintConfig) { throw new Error("No stylelint config found") } const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { if (files) { const filepath = chunk.path fs.readFile(filepath, "utf8", (err, css) => { if (err) { linter.emit("error", err) } lint({ css, filepath: filepath }, callback) }) } else { lint({ css: chunk }, callback) } } function lint({ css, filepath }, callback) { const processOptions = {} if (filepath) { processOptions.from = filepath } postcss() .use(plugin(stylelintConfig)) .process(css, processOptions) .then(result => { callback(null, result) }) .catch(err => { linter.emit("error", new Error(err)) }) } if (files) { const fileStream = gs.create(files) return fileStream.pipe(linter) } return linter }
import postcss from "postcss" import fs from "fs" import gs from "glob-stream" import { Transform } from "stream" import plugin from "./plugin" export default function ({ files, config } = {}) { const linter = new Transform({ objectMode: true }) linter._transform = function (chunk, enc, callback) { if (files) { const filepath = chunk.path fs.readFile(filepath, "utf8", (err, css) => { if (err) { linter.emit("error", err) } lint({ css, filepath: filepath }, callback) }) } else { lint({ css: chunk }, callback) } } function lint({ css, filepath }, callback) { const processOptions = {} if (filepath) { processOptions.from = filepath } postcss() .use(plugin(config)) .process(css, processOptions) .then(result => { callback(null, result) }) .catch(err => { linter.emit("error", new Error(err)) }) } if (files) { const fileStream = gs.create(files) return fileStream.pipe(linter) } return linter }
Add bin to package.json and move rc-loading to plugin.js
Add bin to package.json and move rc-loading to plugin.js
JavaScript
mit
gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,heatwaveo8/stylelint,stylelint/stylelint,hudochenkov/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,stylelint/stylelint,gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,gaidarenko/stylelint,evilebottnawi/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,m-allanson/stylelint,gucong3000/stylelint,evilebottnawi/stylelint
bf04e2c0a7637b0486562167c6046cb8c2a74a26
src/database/DataTypes/TemperatureBreachConfiguration.js
src/database/DataTypes/TemperatureBreachConfiguration.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import Realm from 'realm'; export class TemperatureBreachConfiguration extends Realm.Object {} TemperatureBreachConfiguration.schema = { name: 'TemperatureBreachConfiguration', primaryKey: 'id', properties: { id: 'string', minimumTemperature: { type: 'double', optional: true }, maximumTemperature: { type: 'double', optional: true }, duration: { type: 'double', optional: true }, description: { type: 'string', optional: true }, colour: { type: 'string', optional: true }, location: { type: 'Location', optional: true }, type: 'string', }, }; export default TemperatureBreachConfiguration;
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import Realm from 'realm'; export class TemperatureBreachConfiguration extends Realm.Object { toJSON() { return { id: this.id, minimumTemperature: this.minimumTemperature, maximumTemperature: this.maximumTemperature, duration: this.duration, description: this.description, colour: this.colour, locationID: this.location?.id ?? '', type: this.type, }; } } TemperatureBreachConfiguration.schema = { name: 'TemperatureBreachConfiguration', primaryKey: 'id', properties: { id: 'string', minimumTemperature: { type: 'double', optional: true }, maximumTemperature: { type: 'double', optional: true }, duration: { type: 'double', optional: true }, description: { type: 'string', optional: true }, colour: { type: 'string', optional: true }, location: { type: 'Location', optional: true }, type: 'string', }, }; export default TemperatureBreachConfiguration;
Add breach config adapter method
Add breach config adapter method
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
b2987678c06e7527491984a11e86a63da1d17cb4
src/_fixMobile/EventPath.js
src/_fixMobile/EventPath.js
(function(global){ // For Android 4.3- (included) document.body.addEventListener('click', function(e) { if (!e.path) { e.path = []; var t = e.target; while (t !== document) { e.path.push(t); t = t.parentNode; } e.path.push(document); e.path.push(window); } }, true) })(window);
(function(global){ // For Android 4.3- (included) var pathFill = function() { var e = arguments[0]; if (!e.path) { e.path = []; var t = e.target; while (t !== document) { e.path.push(t); t = t.parentNode; } e.path.push(document); e.path.push(window); } } document.body.addEventListener('click', pathFill); document.body.addEventListener('click', pathFill, true); })(window);
Handle event when bubbles event and catch event.
Handle event when bubbles event and catch event.
JavaScript
mit
zhoukekestar/web-modules,zhoukekestar/modules,zhoukekestar/web-modules,zhoukekestar/modules,zhoukekestar/modules,zhoukekestar/web-modules
aceeb92a1c71a2bdae0f1ebfce50c2391a20bbe2
models.js
models.js
var orm = require('orm'); var db = orm.connect('sqlite://db.sqlite'); function init(callback) { db.sync(callback); } module.exports = { init: init };
var orm = require('orm'); var db = orm.connect('sqlite://' + __dirname + '/db.sqlite'); function init(callback) { db.sync(callback); } module.exports = { init: init };
Use correct directory for sqlite database
Use correct directory for sqlite database
JavaScript
mit
dashersw/cote-workshop,dashersw/cote-workshop
16162985c41a9cd78e17a76b66de27fe2b7bc31d
src/components/NewEngagementForm.js
src/components/NewEngagementForm.js
import 'react-datepicker/dist/react-datepicker.css' import '../App.css' import React, { Component } from 'react' import { Field, reduxForm } from 'redux-form' import { Form } from 'semantic-ui-react' import DatePicker from 'react-datepicker' import moment from 'moment' import styled from 'styled-components' const StyledForm = styled.div`width: 100%;` class NewEngagementForm extends Component { state = { startDate: moment() } handleChange = date => { this.setState({ startDate: date }) } handleSubmit = () => { this.props.handleSubmit(this.state.startDate) } render() { return ( <Form onSubmit={this.handleSubmit}> <Form.Field width={5}> <StyledForm> <DatePicker onChange={this.handleChange} selected={this.state.startDate} showTimeSelect dateFormat="LLL" /> </StyledForm> </Form.Field> <Form.Field> <Field name="email" component="input" type="text" /> </Form.Field> <input type="submit" /> </Form> ) } } export default reduxForm({ form: 'newEngagement' })(NewEngagementForm)
import 'react-datepicker/dist/react-datepicker.css' import '../App.css' import React, { Component } from 'react' import { Field, reduxForm } from 'redux-form' import { Form } from 'semantic-ui-react' import DatePicker from 'react-datepicker' import moment from 'moment' import styled from 'styled-components' const StyledForm = styled.div`width: 100%;` class NewEngagementForm extends Component { state = { startDate: moment() } handleChange = date => { this.setState({ startDate: date }) } handleSubmit = () => { this.props.handleSubmit(this.state.startDate) } render() { return ( <Form onSubmit={this.handleSubmit}> <Form.Field> <StyledForm> <DatePicker onChange={this.handleChange} selected={this.state.startDate} showTimeSelect dateFormat="LLL" /> </StyledForm> </Form.Field> <input type="submit" /> </Form> ) } } export default reduxForm({ form: 'newEngagement' })(NewEngagementForm)
Remove unneeded input form from new engagement form
Remove unneeded input form from new engagement form
JavaScript
mit
cernanb/personal-chef-react-app,cernanb/personal-chef-react-app
92978a1a24c2b2df4dba8f622c40f34c4fa7ca12
modules/signin.js
modules/signin.js
'use strict'; const builder = require('botbuilder'); const timesheet = require('./timesheet'); module.exports = exports = [(session) => { builder.Prompts.text(session, 'Please tell me your domain user?'); }, (session, results, next) => { session.send('Ok. Searching for your stuff...'); session.sendTyping(); timesheet .searchColleagues(results.response) .then((colleagues) => { session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { console.log(ex); }).finally(() => { next(); }); }, (session) => { if (!session.impersonated) { console.log('Oops! Couldn\'t impersonate'); return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)'); }];
'use strict'; const builder = require('botbuilder'); const timesheet = require('./timesheet'); module.exports = exports = [(session) => { builder.Prompts.text(session, 'Please tell me your domain user?'); }, (session, results, next) => { session.send('Ok. Searching for your stuff...'); session.sendTyping(); timesheet .searchColleagues(results.response) .then((colleagues) => { console.log('Found %s', colleagues.length); session.userData = colleagues[0]; session.userData.impersonated = true; }).catch((ex) => { console.log(ex); }).finally(() => { next(); }); }, (session) => { if (!session.userData.impersonated) { return session.endDialog('Oops! Couldn\'t impersonate'); } session.endDialog('(y)'); }];
Fix impersonated user check issue.
Fix impersonated user check issue.
JavaScript
mit
99xt/jira-journal,99xt/jira-journal
6dc8a96b20179bd04a2e24fa4c3b0106d35ebaba
src/main.js
src/main.js
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; this.setTab(el.id, true); } }, accessors: { role: { attribute: {} } }, methods: { setTab: function (tabid, fireEvent) { var eventName = "tabChange", result = true; //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" result = false; } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); return result; } } }); })();
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; this.setTab(el.id, true); } }, accessors: { role: { attribute: {} } }, methods: { setTab: function (tabid, fireEvent) { var eventName = "tabChange"; if (!this.querySelector("[id='"+tabid+"'][role='tab']")) { console.error("Cannot set to unknown tabid"); return false; } //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); return true; } } }); })();
Add handler for when setTab is given a non-exsitant tab id
Add handler for when setTab is given a non-exsitant tab id
JavaScript
apache-2.0
Swissnetizen/sam-tabbar
0715d2b60dd1ebd851d4e5ea9ec9073424211012
src/function/lazyLoading.js
src/function/lazyLoading.js
define([ 'jquery' ], function($) { return function() { var self = this; if (!self.sprite && self.lasyEmoji[0]) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() { var e = $(this), top = e.offset().top; if (top > pickerTop && top < pickerBottom) { e.attr("src", e.data("src")).removeClass("lazy-emoji"); } }) self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji"); } } });
define([ 'jquery' ], function($) { return function() { var self = this; if (!self.sprite && self.lasyEmoji[0] && self.lasyEmoji.eq(0).is(".lazy-emoji")) { var pickerTop = self.picker.offset().top, pickerBottom = pickerTop + self.picker.height() + 20; self.lasyEmoji.each(function() { var e = $(this), top = e.offset().top; if (top > pickerTop && top < pickerBottom) { e.attr("src", e.data("src")).removeClass("lazy-emoji"); } }) self.lasyEmoji = self.lasyEmoji.filter(".lazy-emoji"); } } });
Fix 'disconnected from the document' error
Fix 'disconnected from the document' error ref https://github.com/mervick/emojionearea/pull/240
JavaScript
mit
mervick/emojionearea
7a328c49ea155df7ff2ae55825aa299c541bf31e
test/index.js
test/index.js
var nocache = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('nocache', function () { it('sets headers properly', function (done) { var app = connect() app.use(function (req, res, next) { res.setHeader('ETag', 'abc123') next() }) app.use(nocache()) app.use(function (req, res) { res.end('Hello world!') }) request(app).get('/') .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate') .expect('Pragma', 'no-cache') .expect('Expires', '0') .expect('ETag', 'abc123') .end(done) }) it('names its function and middleware', function () { assert.equal(nocache.name, 'nocache') assert.equal(nocache().name, 'nocache') }) })
var nocache = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('nocache', function () { it('sets headers properly', function (done) { var app = connect() app.use(function (req, res, next) { res.setHeader('ETag', 'abc123') next() }) app.use(nocache()) app.use(function (req, res) { res.end('Hello world!') }) request(app).get('/') .expect('Surrogate-Control', 'no-store') .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate') .expect('Pragma', 'no-cache') .expect('Expires', '0') .expect('ETag', 'abc123') .end(done) }) it('names its function and middleware', function () { assert.equal(nocache.name, 'nocache') assert.equal(nocache().name, 'nocache') }) })
Add missing test for `Surrogate-Control` header
Add missing test for `Surrogate-Control` header Fixes #13.
JavaScript
mit
helmetjs/nocache
5ac0fccde96dd50007767263c19b1432bb4e41d8
test/index.js
test/index.js
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint-env node, mocha */ import test from 'ava'; import endpoint from '../src/endpoint'; test('happy ponies', () => { const fetch = () => null; api(null, null, { baseUri: 'http://api.example.com/v1', endpoints: [ { endpoint: '/happy/ponies/{id}', method: 'GET', requiredParams: ['id'], optionalParams: ['lastSeenId'], } ] }); }); test.skip('returns a request object with the correct url', (t) => { const testUrl = 'http://api.example.com/v1/'; const Request = (url) => { t.true(url === testUrl); }; endpoint(Request); }); test.skip('should append a trailing slash if one is missing in the given url', (t) => { const testUrl = 'http://api.example.com/v1'; const Request = (url) => { t.true(url === `${testUrl}/`); }; endpoint(Request); });
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint-env node, mocha */ import test from 'ava'; import endpoint from '../src/endpoint'; test('endpoint returns correctly partially applied function', (t) => { const endpointConfig = { uri: 'http://example.com', }; const init = () => {}; const Request = (uriOpt, initOpt) => { t.true(uriOpt === endpointConfig.uri); t.true(initOpt.toString() === init.toString()); }; endpoint(Request, init)(endpointConfig); }); test.skip('returns a request object with the correct url', (t) => { const testUrl = 'http://api.example.com/v1/'; const Request = (url) => { t.true(url === testUrl); }; endpoint(Request); }); test.skip('should append a trailing slash if one is missing in the given url', (t) => { const testUrl = 'http://api.example.com/v1'; const Request = (url) => { t.true(url === `${testUrl}/`); }; endpoint(Request); });
Add spec for endpoints function
Add spec for endpoints function
JavaScript
mit
hughrawlinson/api-client-helper
684d9d693b19bc4d09c26627bb16ddcfa6230c63
src/main.js
src/main.js
import './main.sass' import 'babel-core/polyfill' import React from 'react' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { Router } from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' import { createStore, applyMiddleware, combineReducers } from 'redux' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' const logger = createLogger({ collapsed: true }) const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore) const reducer = combineReducers(reducers) const store = createStoreWithMiddleware(reducer) function createRedirect(from, to) { return { path: from, onEnter(nextState, transition) { transition.to(to) }, } } const rootRoute = { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/Onboarding'), ], } const element = ( <Provider store={store}> {() => <Router history={createBrowserHistory()} routes={rootRoute} /> } </Provider> ) React.render(element, document.getElementById('root'))
import './main.sass' import 'babel-core/polyfill' import React from 'react' import thunk from 'redux-thunk' import createLogger from 'redux-logger' import { Router } from 'react-router' import createBrowserHistory from 'history/lib/createBrowserHistory' import { createStore, applyMiddleware, combineReducers } from 'redux' import { Provider } from 'react-redux' import * as reducers from './reducers' import { analytics, uploader, requester } from './middleware' import App from './containers/App' const logger = createLogger({ collapsed: true }) const createStoreWithMiddleware = applyMiddleware(thunk, uploader, requester, analytics, logger)(createStore) const reducer = combineReducers(reducers) const store = createStoreWithMiddleware(reducer) function createRedirect(from, to) { return { path: from, onEnter(nextState, replaceState) { replaceState(nextState, to) }, } } const rootRoute = { path: '/', component: App, childRoutes: [ createRedirect('onboarding', '/onboarding/communities'), require('./routes/Onboarding'), ], } const element = ( <Provider store={store}> {() => <Router history={createBrowserHistory()} routes={rootRoute} /> } </Provider> ) React.render(element, document.getElementById('root'))
Fix an issue with redirects
Fix an issue with redirects
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
18c94b0fcf2fdab6dea4ee0f3c0de11ba6e368f6
test/index.js
test/index.js
var ienoopen = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('ienoopen', function () { beforeEach(function () { this.app = connect() this.app.use(ienoopen()) this.app.use(function (req, res) { res.setHeader('Content-Disposition', 'attachment; filename=somefile.txt') res.end('Download this cool file!') }) }) it('sets header properly', function (done) { request(this.app).get('/') .expect('X-Download-Options', 'noopen', done) }) it('names its function and middleware', function () { assert.equal(ienoopen.name, 'ienoopen') assert.equal(ienoopen().name, 'ienoopen') }) })
var ienoopen = require('..') var assert = require('assert') var connect = require('connect') var request = require('supertest') describe('ienoopen', function () { beforeEach(function () { this.app = connect() this.app.use(ienoopen()) this.app.use(function (req, res) { res.setHeader('Content-Disposition', 'attachment; filename=somefile.txt') res.end('Download this cool file!') }) }) it('sets header properly', function () { return request(this.app).get('/') .expect('X-Download-Options', 'noopen') }) it('names its function and middleware', function () { assert.equal(ienoopen.name, 'ienoopen') assert.equal(ienoopen().name, 'ienoopen') }) })
Use promises instead of callbacks in test
Use promises instead of callbacks in test
JavaScript
mit
helmetjs/ienoopen
5bd8d02a8073fc55560fbc534f840627e81683de
src/main.js
src/main.js
'use strict'; const electron = require('electron'); const { app, BrowserWindow } = electron; let mainWindow; // Ensures garbage collection does not remove the window app.on('ready', () => { // Creates the application window and sets its dimensions to fill the screen const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width, height }); // Loads index.html in as the main application page mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.on('closed', () => { mainWindow = null; // allow window to be garbage collected }); });
'use strict'; const electron = require('electron'); const { app, BrowserWindow } = electron; const path = require('path'); const url = require('url'); let mainWindow; // Ensures garbage collection does not remove the window app.on('ready', () => { // Creates the application window and sets its dimensions to fill the screen const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width, height }); // Loads index.html in as the main application page mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })); mainWindow.on('closed', () => { mainWindow = null; // allow window to be garbage collected }); });
Change method of loading index.html
Change method of loading index.html
JavaScript
mit
joyceky/interactive-periodic-table,joyceky/interactive-periodic-table,joyceky/interactive-periodic-table
d650050d72d0272a350d26c1f03b2e4534e99b33
test/index.js
test/index.js
'use strict'; var expect = require('chai').expect; var rm = require('../'); describe('1rm', function () { // 400# x 4 var expectations = { brzycki: 436, epley: 453, lander: 441, lombardi: 459, mayhew: 466, oconner: 440, wathan: 451 }; Object.keys(expectations).forEach(function (method) { it('can estimate with the #' + method + ' method', function () { expect(rm[method](400, 4)).to.be.closeTo(expectations[method], 1); }); }); });
'use strict'; var expect = require('chai').expect; var rm = require('../'); describe('1rm', function () { // 400# x 4 var expectations = { epley: 453, brzycki: 436, lander: 441, lombardi: 459, mayhew: 466, oconner: 440, wathan: 451 }; Object.keys(expectations).forEach(function (method) { it('can estimate with the #' + method + ' method', function () { expect(rm[method](400, 4)).to.be.closeTo(expectations[method], 1); }); }); });
Order tests to match source
Order tests to match source
JavaScript
mit
bendrucker/1rm.js
10bfd8221e3264d12e6f12470a0d24debc855bd8
test/index.js
test/index.js
var expect = require('chai').expect, hh = require('../index'); describe('#method', function () { it('hh.method is a function', function () { expect(hh.method).a('function'); }); });
var assert = require('chai').assert, hh = require('../index'); describe('#hh.method()', function () { it('should be a function', function () { assert.typeOf(hh.method, 'function', 'hh.method is a function'); }); });
Change tests to assert style
Change tests to assert style
JavaScript
mit
rsp/node-hapi-helpers
3c83c85662300646972a2561db80e26e80432f48
server.js
server.js
const express = require('express') const app = express() const path = require('path') var cors = require('cors') var bodyParser = require('body-parser') // var pg = require('pg') // var format = require('pg-format') // var client = new pg.Client() // var getTimeStamp = require('./get-timestamp.js') // var timestamp = getTimeStamp app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.text()) app.use(cors()) app.use(express.static('client/build')) app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/client/build/index.html')) }) app.post('/', function (req, res) { var thought = req.body.text // var thought = 'cool stuff' console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err var textToDB = format('INSERT INTO thoughtentries (date, thought) VALUES(%L, %L);', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) }) */ }) app.listen(3000, function () { console.log('listening on 3000') })
const express = require('express') const app = express() const path = require('path') var cors = require('cors') var bodyParser = require('body-parser') // var pg = require('pg') // var format = require('pg-format') // var client = new pg.Client() // var getTimeStamp = require('./get-timestamp.js') // var timestamp = getTimeStamp app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.text()) app.use(cors()) app.use(express.static('client/build')) app.get('/', function (req, res) { res.sendFile(path.join(__dirname, '/client/build/index.html')) }) app.post('/', function (req, res) { var thought = req.body res.end('done') console.log('We received this from the client: ' + thought) /* client.connect(function (err) { if (err) throw err var textToDB = format('INSERT INTO thoughtentries VALUES(%L, %L)', timestamp, thought) client.query(textToDB, function (err, result) { if (err) throw err console.log(result.rows[0]) client.end(function (err) { if (err) throw err }) }) }) */ return }) app.listen(3000, function () { console.log('listening on 3000') })
Add res.end() to end the POST request
Add res.end() to end the POST request @chinedufn Line 24 is where I get the contents of `req.body` in order to get the text from the textbox the problem is I believe it should be `req.body.text` like the example on the 'body-parser' page shows.
JavaScript
mit
acucciniello/notebook-sessions,acucciniello/notebook-sessions
4cf7eb019de9b51505dbf1ba8e2b5f9bc77e0b20
recruit/client/applications.js
recruit/client/applications.js
Meteor.subscribe('regions'); Meteor.subscribe('applications'); Template.applications.helpers({ applications: function() { return Applications.find({}, {limit: 10}); }, formatDate: function(date) { return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); }, regionName: function(id) { return Regions.findOne({id: id}).name; }, }); Template.applications.rendered = function() { $('#applications').dataTable({ searching: false, scrollX: true, pagingType: 'full_numbers', language: { decimal: ',', thousands: '.', }, }); };
Meteor.subscribe('regions'); Meteor.subscribe('applications'); Template.applications.helpers({ applications: function() { return Applications.find({}, {limit: 10}); }, formatDate: function(date) { if (typeof date === 'undefined') { return null; } return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); }, regionName: function(id) { if (typeof id === 'undefined') { return null; } return Regions.findOne({id: id}).name; }, }); Template.applications.rendered = function() { $('#applications').dataTable({ searching: false, scrollX: true, pagingType: 'full_numbers', language: { decimal: ',', thousands: '.', }, }); };
Fix exceptions when application region or date is undefined
Fix exceptions when application region or date is undefined
JavaScript
apache-2.0
IngloriousCoderz/GetReel,IngloriousCoderz/GetReel
df11a29999a30f430162e2a6742903879f4608c4
web/webpack.common.js
web/webpack.common.js
const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: { app: './src/app/app.js' }, module: { rules: [ { test: /\.html$/, use: 'raw-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'head' }), new CopyWebpackPlugin([ { from: './src/assets/', to: 'assets/' }, { from: './src/styles/', to: 'styles/' }, { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } ]) ], output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, };
const path = require('path'); const webpack = require('webpack'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: { app: './src/app/app.js' }, module: { rules: [ { test: /\.html$/, use: 'raw-loader' } ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'head' }), new CopyWebpackPlugin({patterns: [ { from: './src/assets/', to: 'assets/' }, { from: './src/styles/', to: 'styles/' }, { from: './src/app/lib/stockfish.js', to: 'lib/stockfish.js' } ]}) ], output: { filename: 'app.js', path: path.resolve(__dirname, 'dist') }, };
Update webpack copy plugin configuration
Update webpack copy plugin configuration
JavaScript
mit
ddugovic/RelayChess,ddugovic/RelayChess,ddugovic/RelayChess
b9eccecc4a5574ec05e29c55b16e19814b7d2c19
Kinect2Scratch.js
Kinect2Scratch.js
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; ext.my_first_block = function(callback) { wait = 1; window.setTimeout(function() { callback(); }, wait*1000); }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ] }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; ext.my_first_block = function() { }; ext.power = function(base, exponent) { return Math.pow(base, exponent); }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ] }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
Stop terrible idea; make reporter block do something
Stop terrible idea; make reporter block do something
JavaScript
bsd-3-clause
visor841/SkelScratch,Calvin-CS/SkelScratch
46f2f3e86783a0b1eeed9be1ac35cd50a3ce1939
src/pkjs/index.js
src/pkjs/index.js
/* global Pebble navigator */ function pebbleSuccess(e) { // do nothing } function pebbleFailure(e) { console.error(e); } var reportPhoneBatt; Pebble.addEventListener('ready', function(e) { if (navigator.getBattery) { navigator.getBattery().then(function (battery) { reportPhoneBatt = function () { Pebble.sendAppMessage({ 'PHONE_BATT_LEVEL': Math.floor(battery.level * 100), 'PHONE_BATT_CHARGING': battery.charging ? 1 : 0 }, pebbleSuccess, pebbleFailure); }; battery.addEventListener('levelchange', function() { console.log('Level change: '+ (battery.level * 100) +'%'); reportPhoneBatt(); }); battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); } else { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); } }); Pebble.addEventListener('appmessage', function(e) { if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) { return reportPhoneBatt(); } });
/* global Pebble navigator */ function pebbleSuccess(e) { // do nothing } function pebbleFailure(e) { console.error(e); } var reportPhoneBatt; Pebble.addEventListener('ready', function(e) { if (navigator.getBattery) { navigator.getBattery().then(function (battery) { reportPhoneBatt = function () { Pebble.sendAppMessage({ 'PHONE_BATT_LEVEL': Math.floor(battery.level * 100), 'PHONE_BATT_CHARGING': battery.charging ? 1 : 0 }, pebbleSuccess, pebbleFailure); }; battery.addEventListener('levelchange', function() { console.log('Level change: '+ (battery.level * 100) +'%'); reportPhoneBatt(); }); battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); } else if (navigator.userAgent) { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); } else { console.log('No navigator.userAgent, probably running in emulator'); } }); Pebble.addEventListener('appmessage', function(e) { if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) { return reportPhoneBatt(); } });
Add log message about starting in the emulator
Add log message about starting in the emulator
JavaScript
mit
stuartpb/rainpower-watchface,stuartpb/rainpower-watchface,stuartpb/rainpower-watchface
a9d67c9f29270b56be21cb71073020f8957374d4
test/client/scripts/arcademode/store/configureStore.spec.js
test/client/scripts/arcademode/store/configureStore.spec.js
'use strict'; /* Unit tests for file client/scripts/arcademode/store/configureStore.js. */ import { expect } from 'chai'; import configureStore from '../../../../../client/scripts/arcademode/store/configureStore'; describe('configureStore()', () => { it('should do return an object', () => { const store = configureStore(); expect(typeof store).to.equal('object'); const state = store.getState(); expect(state).not.to.empty; }); it('should do accept dispatched actions', () => { const store = configureStore(); store.dispatch({ type: 'DUMMY' }); }); });
'use strict'; /* Unit tests for file client/scripts/arcademode/store/configureStore.js. */ import { expect } from 'chai'; import configureStore from '../../../../../client/scripts/arcademode/store/configureStore'; describe('Store: configureStore()', () => { it('should return an object representing the store', () => { const store = configureStore(); expect(typeof store).to.equal('object'); const state = store.getState(); expect(state).not.to.be.empty; }); it('should accept dispatched actions and update its state', () => { const store = configureStore(); store.dispatch({ type: 'MODAL_CLOSE' }); expect(store.getState().getIn(['modal', 'modal'])).to.be.false; }); });
Test store, dispatch, and state
Test store, dispatch, and state
JavaScript
bsd-3-clause
freeCodeCamp/arcade-mode,kevinnorris/arcade-mode,kevinnorris/arcade-mode,kevinnorris/arcade-mode,freeCodeCamp/arcade-mode,freeCodeCamp/arcade-mode,kevinnorris/arcade-mode,freeCodeCamp/arcade-mode
be4104b7fa5e985da4970d733231ba2f9f4d1c24
lib/async-to-promise.js
lib/async-to-promise.js
// Return promise for given async function 'use strict'; var f = require('es5-ext/lib/Function/functionalize') , concat = require('es5-ext/lib/List/concat').call , slice = require('es5-ext/lib/List/slice/call') , deferred = require('./deferred') , apply; apply = function (fn, scope, args, resolve) { fn.apply(scope, concat(args, function (error, result) { if (error == null) { resolve((arguments.length > 2) ? slice(arguments, 1) : result); } else { resolve(error); } })); } exports = module.exports = f(function () { var d = deferred(); apply(this, null, arguments, d.resolve); return d.promise; }); exports._apply = apply;
// Return promise for given async function 'use strict'; var f = require('es5-ext/lib/Function/functionalize') , slice = require('es5-ext/lib/List/slice/call') , toArray = require('es5-ext/lib/List/to-array').call , deferred = require('./deferred') , apply; apply = function (fn, scope, args, resolve) { fn.apply(scope, toArray(args).concat(function (error, result) { if (error == null) { resolve((arguments.length > 2) ? slice(arguments, 1) : result); } else { resolve(error); } })); } exports = module.exports = f(function () { var d = deferred(); apply(this, null, arguments, d.resolve); return d.promise; }); exports._apply = apply;
Update up to changes in es5-ext
Update up to changes in es5-ext
JavaScript
isc
medikoo/deferred
97b8f1d793341c20acf7eabb9395ee575b7bcb59
app/routes/interestgroups/components/InterestGroupList.js
app/routes/interestgroups/components/InterestGroupList.js
import styles from './InterestGroup.css'; import React from 'react'; import InterestGroup from './InterestGroup'; import Button from 'app/components/Button'; import { Link } from 'react-router'; export type Props = { interestGroups: Array }; const InterestGroupList = (props: Props) => { const groups = props.interestGroups.map((group, key) => ( <InterestGroup group={group} key={key} /> )); return ( <div className={styles.root}> <div className={styles.section}> <div> <h1>Interessegrupper</h1> <p> <strong>Her</strong> finner du all praktisk informasjon knyttet til våre interessegrupper. </p> </div> <Link to={'/interestgroups/create'} className={styles.link}> <Button>Lag ny interessegruppe</Button> </Link> </div> <div className="groups">{groups}</div> </div> ); }; export default InterestGroupList;
import styles from './InterestGroup.css'; import React from 'react'; import InterestGroup from './InterestGroup'; import Button from 'app/components/Button'; import { Link } from 'react-router'; import NavigationTab, { NavigationLink } from 'app/components/NavigationTab'; export type Props = { interestGroups: Array }; const InterestGroupList = (props: Props) => { const groups = props.interestGroups.map((group, key) => ( <InterestGroup group={group} key={key} /> )); const showCreate = props.loggedIn; return ( <div className={styles.root}> <div className={styles.section}> <div> <NavigationTab title="Interessegrupper"> <NavigationLink to={`/`}>Hjem</NavigationLink> </NavigationTab> <p> <strong>Her</strong> finner du all praktisk informasjon knyttet til våre interessegrupper. </p> {showCreate && ( <Link to={'/interestgroups/create'} className={styles.link}> <Button>Lag ny interessegruppe</Button> </Link> )} </div> </div> <div className="groups">{groups}</div> </div> ); }; export default InterestGroupList;
Use NavigationTab in InterestGroup list
Use NavigationTab in InterestGroup list
JavaScript
mit
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
64ae5257caf51aa470249561184b7b8c7a4d614c
stylefmt.js
stylefmt.js
'use strict'; var stylefmt = require('stylefmt'); var data = ''; // Get options if needed if (process.argv.length > 2) { var opts = JSON.parse(process.argv[2]); process.chdir(opts.file_path); } process.stdin.on('data', function(css) { data += css; }); process.stdin.on('end', function() { try { process.stdout.write(stylefmt.process(data)); } catch (err) { throw err; } });
'use strict'; var stylefmt = require('stylefmt'); var data = ''; // Get options if needed if (process.argv.length > 2) { var opts = JSON.parse(process.argv[2]); process.chdir(opts.file_path); } process.stdin.on('data', function(css) { data += css; }); process.stdin.on('end', function() { stylefmt.process(data).then(function(result) { try { process.stdout.write(result.css); } catch (err) { throw err; } }); });
Update for new postcss promises
Update for new postcss promises
JavaScript
isc
dmnsgn/sublime-cssfmt,dmnsgn/sublime-cssfmt,dmnsgn/sublime-stylefmt
47eb145d096e569254fcc96d1b71925cf0ff631f
src/background.js
src/background.js
'use strict'; /** * Returns a BlockingResponse object with a redirect URL if the request URL * matches a file type extension. * * @param {object} request * @return {object|undefined} the blocking response */ function requestInterceptor(request) { var url = request.url; var hasParamTs = /\?.*ts=/; var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) return {redirectUrl: addTabSizeParam(url, 2)}; } /** * Returns a URL with the query param ts=size included. * * @param {string} url * @param {number} size * @return {string} */ function addTabSizeParam(url, size) { var urlWithTs = new Url(url); urlWithTs.query.ts = size; return urlWithTs.toString(); } chrome.webRequest.onBeforeRequest.addListener( requestInterceptor, {urls: ['https://github.com/*']}, ['blocking'] );
'use strict'; var tabSize = 2; /** * Returns a BlockingResponse object with a redirect URL if the request URL * matches a file type extension. * * @param {object} request * @return {object|undefined} the blocking response */ function requestInterceptor(request) { var url = request.url; var hasParamTs = /\?.*ts=/; var hasExtGo = /\.go/; if (!hasParamTs.test(url) && hasExtGo.test(url)) return {redirectUrl: addTabSizeParam(url, tabSize)}; } /** * Returns a URL with the query param ts=size included. * * @param {string} url * @param {number} size * @return {string} */ function addTabSizeParam(url, size) { var urlWithTs = new Url(url); urlWithTs.query.ts = size; return urlWithTs.toString(); } chrome.webRequest.onBeforeRequest.addListener( requestInterceptor, {urls: ['https://github.com/*']}, ['blocking'] ); chrome.storage.sync.get({tabSize: tabSize}, function(items) { tabSize = items.tabSize; }); chrome.storage.onChanged.addListener(function(items) { tabSize = items.tabSize.newValue; });
Use tab size from Chrome storage
Use tab size from Chrome storage
JavaScript
mit
nysa/github-tab-sizer
6653fcba245b25adc7c20bf982a3d119f2659711
.prettierrc.js
.prettierrc.js
module.exports = { printWidth: 100, tabWidth: 2, useTabs: false, semi: true, singleQuote: true, quoteProps: 'consistent', trailingComma: 'all', bracketSpacing: true, arrowParens: 'always', };
module.exports = { printWidth: 100, tabWidth: 2, useTabs: false, semi: true, singleQuote: true, quoteProps: 'consistent', trailingComma: 'all', bracketSpacing: true, arrowParens: 'always', endOfLine: 'lf', };
Set endOfLine to "lf" in prettier-config
:wrench: Set endOfLine to "lf" in prettier-config
JavaScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
1b2d9602dade5c599390645bd02e9b066f4f0ef5
cla_frontend/assets-src/javascripts/app/test/protractor.conf.local.js
cla_frontend/assets-src/javascripts/app/test/protractor.conf.local.js
(function () { 'use strict'; var extend = require('extend'), defaults = require('./protractor.conf'); exports.config = extend(defaults.config, { // --- uncomment to use mac mini's --- // seleniumAddress: 'http://clas-mac-mini.local:4444/wd/hub', // baseUrl: 'http://Marcos-MacBook-Pro-2.local:8001/', multiCapabilities: [ { browserName: 'chrome' }, { browserName: 'firefox' } ] }); })();
(function () { 'use strict'; var extend = require('extend'), defaults = require('./protractor.conf'); exports.config = extend(defaults.config, { // --- uncomment to use mac mini's --- // seleniumAddress: 'http://clas-mac-mini.local:4444/wd/hub', // baseUrl: 'http://Marcos-MacBook-Pro-2.local:8001/', multiCapabilities: [ { browserName: 'chrome', 'chromeOptions': { args: ['--test-type'] } }, { browserName: 'firefox' } ] }); })();
Remove chrome warnings during e2e tests
Remove chrome warnings during e2e tests
JavaScript
mit
ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend
276492033ce2a3048b453d75c0e361bf4ebfd5d7
tests/spec/QueueTwoStacksSpec.js
tests/spec/QueueTwoStacksSpec.js
describe("Implement queue with two stacks", function() { const Queue = new QueueTwoStacks(); Queue.enqueue(1); Queue.enqueue(2); Queue.enqueue(3); describe("enqueue()", function() { it("appends an element to tail", function() { Queue.enqueue(4); const expected = [1,2,3,4]; expect(Queue.inStack).toEqual(expected); }) it("appends an element correctly after dequeing", function() { Queue.dequeue(); Queue.enqueue(5); const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) }) describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); }) }) describe("when queue is empty", function() { it("throws an error", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); expect(function() { Queue.dequeue(); }).toThrow(); }) }) })
describe("Implement queue with two stacks", function() { const Queue = new QueueTwoStacks(); Queue.enqueue(1); Queue.enqueue(2); Queue.enqueue(3); describe("enqueue()", function() { it("appends an element to tail", function() { Queue.enqueue(4); const expected = [1,2,3,4]; expect(Queue.inStack).toEqual(expected); }) it("appends an element correctly after dequeing", function() { Queue.dequeue(); Queue.enqueue(5); const expected = [2,3,4,5]; expect(Queue.inStack).toEqual(expected); }) }); describe("dequeue()", function () { it("removes an element from head", function () { Queue.dequeue(); const expected = [3,4,5]; expect(Queue.inStack).toEqual(expected); }); it("throws an error when queue is empty", function() { Queue.dequeue(); Queue.dequeue(); Queue.dequeue(); expect(function() { Queue.dequeue(); }).toThrow(); }) }); })
Move code to correct semantics in spec
Move code to correct semantics in spec
JavaScript
mit
ThuyNT13/algorithm-practice,ThuyNT13/algorithm-practice
009e3a12d21aa5b04acd1f17616a6af2458046b1
src/projects/TicTacToe/TicTacToe.js
src/projects/TicTacToe/TicTacToe.js
import React from 'react'; import './TicTacToe.scss'; import { connect } from 'react-redux'; import ticTacToeActions from 'actions/tictactoe'; import GameBoard from './components/GameBoard'; const mapStateToProps = (state) => { return { playerTurn: state.tictactoe.playerTurn }; }; class TicTacToe extends React.Component { static propTypes = { playerTurn: React.PropTypes.bool, computer_move: React.PropTypes.func } componentWillReceiveProps (propObj) { if (!propObj.playerTurn) { this.props.computer_move(); } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein } else if (propObj.winner) { // do very cool modal fadein with computer winning } // nothing else, the player can't win } render () { return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> <GameBoard /> </div> ); } } export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
import React from 'react'; import './TicTacToe.scss'; import { connect } from 'react-redux'; import ticTacToeActions from 'actions/tictactoe'; import GameBoard from './components/GameBoard'; const mapStateToProps = (state) => { return { playerTurn: state.tictactoe.playerTurn, winner: state.tictactoe.winner }; }; class TicTacToe extends React.Component { static propTypes = { playerTurn: React.PropTypes.bool, computer_move: React.PropTypes.func } componentWillReceiveProps (propObj) { if (!propObj.playerTurn) { this.props.computer_move(); } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein console.log('DRAW'); } else if (propObj.winner) { // do very cool modal fadein with computer winning console.log('YOU LOST'); } // nothing else, the player can't win } render () { return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> <h2 className='text-center'>Open your console to see messages</h2> <h3 className='text-center'>You can't win</h3> <GameBoard /> </div> ); } } export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
Add console statements for initial notification
Add console statements for initial notification
JavaScript
mit
terakilobyte/terakilobyte.github.io,terakilobyte/terakilobyte.github.io
520a7ecf81d37df70aefe39efe2e9e1092f25a52
tests/unit/models/canvas-test.js
tests/unit/models/canvas-test.js
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('canvas', 'Unit | Model | canvas', { // Specify the other units that are required for this test. needs: 'model:op model:pulseEvent model:team model:user'.w() }); test('it exists', function(assert) { const model = this.subject(); assert.ok(Boolean(model)); });
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('canvas', 'Unit | Model | canvas', { // Specify the other units that are required for this test. needs: 'model:comment model:op model:pulseEvent model:team model:user'.w() }); test('it exists', function(assert) { const model = this.subject(); assert.ok(Boolean(model)); });
Add missing model dependency for canvas model test
Add missing model dependency for canvas model test
JavaScript
apache-2.0
usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2
7d8ef029b25f4869bf046e6e28fc4bd801614944
src/atom/index.js
src/atom/index.js
class Atom { constructor(state) { this.state = state; this.watches = {}; } reset(state) { return this._change(state); } swap(f, ...args) { return this._change(f(this.state, ...args)); } deref() { return this.state; } addWatch(k, f) { // if (this.watches[key]) { // console.warn(`adding a watch with an already registered key: ${k}`); // } this.watches[k] = f; return this; } removeWatch(k) { // if (!this.watches[key]) { // console.warn(`removing a watch with an unknown key: ${k}`); // } delete this.watches[key]; return this; } _change(newState) { const { state, watches } = this; Object.keys(watches).forEach(k => watches[k](k, state, newState)); this.state = newState; return this.state; } } export default function atom(state) { return new Atom(state); }
class Atom { constructor(state) { this.state = state; this.watches = {}; } reset(state) { return this._change(state); } swap(f, ...args) { return this._change(f(this.state, ...args)); } deref() { return this.state; } addWatch(k, f) { // if (this.watches[key]) { // console.warn(`adding a watch with an already registered key: ${k}`); // } this.watches[k] = f; return this; } removeWatch(k) { // if (!this.watches[key]) { // console.warn(`removing a watch with an unknown key: ${k}`); // } delete this.watches[key]; return this; } _change(newState) { const { state, watches } = this; this.state = newState; Object.keys(watches).forEach(k => watches[k](k, state, newState)); return this.state; } } export default function atom(state) { return new Atom(state); }
Update atom state before calling watches
Update atom state before calling watches
JavaScript
mit
mike-casas/lock,mike-casas/lock,auth0/lock-passwordless,mike-casas/lock,auth0/lock-passwordless,auth0/lock-passwordless
fc4428b965c58dda423f8bd100ccbb0760d44893
spec/case-sensitive/program.js
spec/case-sensitive/program.js
var test = require("test"); require("a"); try { require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) { } test.print("DONE", "info");
var test = require("test"); try { require("a"); require("A"); test.assert(false, "should fail to require alternate spelling"); } catch (error) { } test.print("DONE", "info");
Update case sensitivity test to capture errors on first require
Update case sensitivity test to capture errors on first require as this throws on case sensitive systems.
JavaScript
bsd-3-clause
kriskowal/mr,kriskowal/mr