commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
3c4b2a07c509c7031e7e914729982fc3431872d9
server.js
server.js
'use strict'; const express = require('express'); const app = express(); const path = require('path'); const twilio = require('twilio'); const bodyparser = require('body-parser'); const onConnect = require('./lib/socket').onConnect; const twilioRoute = require('./lib/twilio'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyparser.json()); app.post('/twilio/response', twilio.webhook({ validate: false }), twilioRoute.response); const server = require('http').createServer(app); const io = require('socket.io')(server); server.listen(process.env.port || 3000); io.on('connection', onConnect);
'use strict'; const express = require('express'); const app = express(); const path = require('path'); const twilio = require('twilio'); const bodyparser = require('body-parser'); const onConnect = require('./lib/socket').onConnect; const twilioRoute = require('./lib/twilio'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyparser.urlencoded({ extended: false })); app.post('/twilio/response', twilio.webhook({ validate: false }), twilioRoute.response); const server = require('http').createServer(app); const io = require('socket.io')(server); server.listen(process.env.port || 3000); io.on('connection', onConnect);
Switch json for url parser
Switch json for url parser
JavaScript
apache-2.0
peterjuras/askeighty,peterjuras/askeighty
ecd6064267b8bbdd126dbda09e74f85cdabc729f
src/reducers/visibilityFilter.js
src/reducers/visibilityFilter.js
const visibilityFilter = (state = 'SHOW_ALL', action) => { switch(action.type) { case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; export default visibilityFilter;
const visibilityFilter = (state = 'SHOW_ALL', action) => { switch(action.type) { case 'ADD_ITEM': return 'SHOW_ALL'; case 'SET_VISIBILITY_FILTER': return action.filter; default: return state; } }; export default visibilityFilter;
Set viz-filter to SHOW_ALL when adding a new item
Set viz-filter to SHOW_ALL when adding a new item
JavaScript
mit
blaqbern/lists,blaqbern/lists
286aaa28ea38b4b3022b35fac03b8948d8ff2807
src/cli/Host.js
src/cli/Host.js
'use strict'; const program = require('commander'); const path = require('path'); const FlaCompiler = require('./FlaCompiler'); program .version(require('../../package.json').version) .option('--interactive-compiler <path>', 'full path to Flash.exe') .option('--input-directory <path>', 'full path to input directory that contains FLA files') .option('--output-directory <path>', 'full path to input directory to put build artifacts into') .option('--include-pattern [pattern]', 'list of files to include in a build, default is *.fla', '*.fla') .option('--debug [value]', 'activate session 0 debugging mode', (value) => Boolean(parseInt(value)), false) .parse(process.argv); const compilerConfig = { interactiveCompiler: program.interactiveCompiler, inputDirectory: path.resolve(program.inputDirectory), outputDirectory: path.resolve(program.outputDirectory), includePattern: program.includePattern, debug: program.debug }; const compiler = new FlaCompiler(compilerConfig); compiler.compile();
'use strict'; const program = require('commander'); const path = require('path'); const FlaCompiler = require('./FlaCompiler'); program .version(require('../../package.json').version) .option('--interactive-compiler <path>', 'absolute or relative path to Flash.exe') .option('--input-directory <path>', 'absolute or relative path to input directory that contains FLA files') .option('--output-directory <path>', 'absolute or relative path to input directory to put build artifacts into') .option('--include-pattern [pattern]', 'list of files to include in a build, default is *.fla', '*.fla') .option('--debug [value]', 'activate session 0 debugging mode', (value) => Boolean(parseInt(value)), false) .parse(process.argv); const compilerConfig = { interactiveCompiler: path.resolve(program.interactiveCompiler), inputDirectory: path.resolve(program.inputDirectory), outputDirectory: path.resolve(program.outputDirectory), includePattern: program.includePattern, debug: program.debug }; const compiler = new FlaCompiler(compilerConfig); compiler.compile();
Allow relative path for interactive compiler parameter. Update help
Allow relative path for interactive compiler parameter. Update help
JavaScript
mit
alexeiskachykhin/flc
b2f2591150c2bcc640fd706eef8cd2ae1cc740ad
src/actions/headerNav.js
src/actions/headerNav.js
import { HEADER_NAV_MOUSE_ENTER, HEADER_NAV_MOUSE_LEAVE, SET_HEADER_NAV } from '../constants/headerNav'; import { setCurrentAsset } from '../actions/assets'; import keyBy from 'lodash/keyBy'; export const setCurrentHeaderNav = headerNavID => dispatch => { dispatch({ type: SET_HEADER_NAV, payload: headerNavID }); }; export const headevNavMouseEnter = headerNavID => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_ENTER, payload: headerNavID }); }; export const headevNavMouseLeave = () => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_LEAVE }); }; export const headerNavClick = headerNavID => (dispatch, getState) => { const mapping = keyBy(getState().assetsToHeaderNavMapping, 'headerNavID')[headerNavID]; mapping && dispatch(setCurrentAsset(mapping.assetID)); dispatch(setCurrentHeaderNav(headerNavID)); };
import { HEADER_NAV_MOUSE_ENTER, HEADER_NAV_MOUSE_LEAVE, SET_HEADER_NAV } from '../constants/headerNav'; import { setCurrentAsset } from '../actions/assets'; import keyBy from 'lodash/keyBy'; export const setCurrentHeaderNav = headerNavID => dispatch => { dispatch({ type: SET_HEADER_NAV, payload: headerNavID }); }; export const headevNavMouseEnter = headerNavID => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_ENTER, payload: headerNavID }); }; export const headevNavMouseLeave = () => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_LEAVE }); }; export const headerNavClick = headerNavID => (dispatch, getState) => { const mapping = keyBy(getState().assetsToHeaderNavMapping, 'headerNavID')[headerNavID]; mapping && dispatch(setCurrentAsset(mapping.assetID)); dispatch(setCurrentHeaderNav(headerNavID)); dispatch(headevNavMouseLeave()); };
Hide submenu on click sub menu item
Hide submenu on click sub menu item
JavaScript
mit
g8extended/Character-Generator,g8extended/Character-Generator
b487ddf16e2a8c396b927fb580919716a951f0a3
bin/imp.js
bin/imp.js
#! /usr/bin/env node var program = require("commander"); program .version("0.0.1") .command("devices [options]", "Lists devices, or adds/removes devices from project") .command("deploy [options]", "Deploys the project") .command("init", "Creates a new imp project") .command("log [options]", "Logs messages from specified device") .command("login [options]", "Sets your global API-Key") .command("models [options]", "Lists models, or sets the project's model") .command("pull [options]", "Fetches the most recent code from the imp server") .command("migrate [options]", "Migrates model from development imp server to production imp server") program.parse(process.argv);
#! /usr/bin/env node var program = require("commander"); program .version("0.0.1") .command("devices [options]", "Lists devices, or adds/removes devices from project") .command("deploy [options]", "Deploys the project") .command("init", "Creates a new imp project") .command("log [options]", "Logs messages from specified device") .command("login [options]", "Sets your global API-Key") .command("models [options]", "Lists models, or sets the project's model") .command("pull [options]", "Fetches the most recent code from the imp server") .command("migrate [options]", "Migrates model from one imp account to another (useful for commercial customers with dev accounts and limited access production accounts)") program.parse(process.argv);
Update migrate help text so that its purpose was more clear
Update migrate help text so that its purpose was more clear
JavaScript
mit
deldrid1/imp-cli,matt-haines/imp-cli,cat-haines/imp-cli
9e1f44dd5609ae683e9bb147f7c84955b3b7bdaa
bleep.com-dance-all-night.user.js
bleep.com-dance-all-night.user.js
// ==UserScript== // @name bleep.com dance all night // @namespace rob@middlerob.com // @include https://bleep.com/* // @version 1 // @description Disable the 60 second pause on bleep.com // @license MIT // @oujs:author middlerob // @grant none // ==/UserScript== eval(durationChanged.toString().replace('durationChanged', 'fixedDurationChanged').replace(60, 1000000)) $('#jplayer') .unbind($.jPlayer.event.timeupdate) .bind($.jPlayer.event.timeupdate, fixedDurationChanged)
// ==UserScript== // @name bleep.com dance all night // @namespace rob@middlerob.com // @include https://bleep.com/* // @version 2 // @description Disable the 60 second pause on bleep.com // @license MIT // @oujs:author middlerob // @grant none // ==/UserScript== setInterval(function() { window.playableTime = 1000000 }, 2000)
Fix script to work with latest website updates
Fix script to work with latest website updates
JavaScript
mit
Rob-ot/bleep.com-dance-all-night
8f05bb23c68bf3ded65cbf9b145f1f299b44205c
src/defaults.js
src/defaults.js
const defaults = { /** * Label */ label: 'Dialog', /** * Description - ID of HTMLElement to use as aria-describedby */ description: '', /** * Focus - HTMLElement to focus on open */ focus: '', /** * Alert - Is the dialog an alert? */ alert: false, openClass: 'is-open', /** * Auto initiate on instantiation */ autoInit: true, }; export default defaults;
/** * Default configuration. * * @property {string} label - ID of HTMLElement to use as label or a string. * @property {string} description - ID of HTMLElement to use as aria-describedby. * @property {boolean} alert - Set dialog role to alertdialog. * @property {string} openClass - The class applied to elements.dialog when open. */ const defaults = { label: 'Dialog', description: '', alert: false, openClass: 'is-open', }; export default defaults;
Add docblock to default configuration object
Add docblock to default configuration object
JavaScript
mit
rynpsc/dialog,rynpsc/dialog
3561e1abd475ac6b1d3a48076b9f5d8a5ebaf3f1
src/components/Facets/FacetsGroup.js
src/components/Facets/FacetsGroup.js
import React, { Component } from 'react' import Facet from './Facet' import { isActive } from '../../helpers/manageFilters' const styles = { type: { textTransform: 'capitalize', fontSize: '1em', fontWeight: 400, marginBottom: '1em', }, group: { marginBottom: '1em', } } class FacetsGroup extends Component { render() { const { type, facets, filters, addFilter } = this.props return ( <div style={styles.group}> <h4 style={styles.type}>{type}</h4> {facets.map((facet, idx) => <Facet key={idx} name={type} value={facet.value} count={facet.count} isActive={isActive(filters, {name: type, value: facet.value})} addFilter={addFilter} />)} </div> ) } } export default FacetsGroup
import React, { Component } from 'react' import Facet from './Facet' import { isActive } from '../../helpers/manageFilters' const styles = { type: { textTransform: 'capitalize', fontSize: '1em', fontWeight: 400, marginBottom: '1em', }, group: { marginBottom: '1em', } } class FacetsGroup extends Component { render() { const { type, facets, filters, addFilter } = this.props const activeMap = facets.map(facet => isActive(filters, {name: type, value: facet.value})) if (activeMap.indexOf(false) === -1) { return null; } return ( <div style={styles.group}> <h4 style={styles.type}>{type}</h4> {facets.map((facet, idx) => <Facet key={idx} name={type} value={facet.value} count={facet.count} isActive={activeMap[idx]} addFilter={addFilter} />)} </div> ) } } export default FacetsGroup
Hide facet if no filters are still inactive inside
Hide facet if no filters are still inactive inside
JavaScript
mit
sgmap/inspire,sgmap/inspire
7ebb7b380645c5dc496d2b4376979bd7a9bbaa87
src/converter/r2t/ConvertCodeCell.js
src/converter/r2t/ConvertCodeCell.js
import convertSourceCode from './convertSourceCode' export default class ConvertCodeCell { /* Collect <code specific-use="cell"> and turn it into cell elements in TextureJATS TODO: - Properly handle CDATA content - Implement export method */ import(dom, converter) { let cells = dom.findAll('code[specific-use=cell]') cells.forEach((oldCell) => { let cell = dom.createElement('cell') cell.append( convertSourceCode(oldCell, converter) ) oldCell.getParent().replaceChild(oldCell, cell) }) } export(/*dom*/) { console.error('TODO: implement ConvertCodeCell.export') } }
import convertSourceCode from './convertSourceCode' export default class ConvertCodeCell { /* Collect <code specific-use="cell"> and turn it into cell elements in TextureJATS TODO: - Properly handle CDATA content - Implement export method */ import(dom, converter) { let cells = dom.findAll('code[specific-use=cell]') cells.forEach((oldCell) => { let cell = dom.createElement('cell').attr('id', oldCell.id) cell.append( convertSourceCode(oldCell, converter) ) oldCell.getParent().replaceChild(oldCell, cell) }) } export(/*dom*/) { console.error('TODO: implement ConvertCodeCell.export') } }
Save cell id during conversion.
Save cell id during conversion.
JavaScript
mit
substance/texture,substance/texture
bf33de8661a8d2ff1dfa415929c86679eb7c8cc0
src/css-clean-src/sortCss/sortCss.js
src/css-clean-src/sortCss/sortCss.js
function sortCss(settings, cssObject) { function sortDeep(array) { sortCss.scope(settings, array, { displace : [ 'sass function', 'sass import', 'sass include', 'sass include arguments', 'sass mixin', 'sass include block', 'sass extend', 'property group', ] }); for (var i = 0, n = array.length; i < n; i++) { if (Array.isArray(array[i].content) && array[i].content.length) { sortDeep(array[i].content); } } } sortCss.scope(settings, cssObject, { displace : [ 'sass import', 'sass include', 'sass variable assignment', 'font face', 'sass function', 'sass mixin', 'sass include block', 'sass placeholder', ] }); if (settings.sortBlockScope) { for (var i = 0, n = cssObject.length; i < n; i++) { if (Array.isArray(cssObject[i].content) && cssObject[i].content.length) { sortDeep(cssObject[i].content); } } } } sortCss.list = {}; sortCss.each = {};
function sortCss(settings, cssObject) { var displaceDeep = [ 'sass function', 'sass import', 'sass include', 'sass include arguments', 'sass mixin', 'sass include block', 'sass extend', 'property group', ]; var displaceZeroDepth = [ 'sass import', 'sass include', 'sass variable assignment', 'font face', 'sass function', 'sass mixin', 'sass include block', 'sass placeholder', ]; function sortDeep(array) { sortCss.scope(settings, array, { displace : displaceDeep }); for (var i = 0, n = array.length; i < n; i++) { if (Array.isArray(array[i].content) && array[i].content.length) { sortDeep(array[i].content); } } } sortCss.scope(settings, cssObject, { displace : displaceZeroDepth }); if (settings.sortBlockScope) { for (var i = 0, n = cssObject.length; i < n; i++) { if (Array.isArray(cssObject[i].content) && cssObject[i].content.length) { sortDeep(cssObject[i].content); } } } } sortCss.list = {}; sortCss.each = {};
Declare 'displace' arrays at the top of the function
Declare 'displace' arrays at the top of the function
JavaScript
mit
SeanJM/atom-css-clean
3eb178c27d595833fe1ea7ebeb846c37ffd094e4
js/board.js
js/board.js
import settings from 'settings'; import { bind } from 'util/dom'; var worker; var messageCount; var callbacks; function post (command, data, callback) { callbacks[messageCount] = callback; worker.postMessage({ id: messageCount, command: command, data: JSON.parse(JSON.stringify(data)), }); messageCount++; } function messageHandler (event) { var message = event.data; if (callbacks[message.id]) { callbacks[message.id](message.data); delete callbacks[message.id]; } } export function getJewel (x, y, callback) { post('getJewel', { x: x, y: y, }, callback); } export function getBoard (callback) { post('getBoard', null, callback); } export function print () { post('print', null, function (jewels) { console.log(jewels); }); } export function swap (x1, y1, x2, y2, callback) { post('swap', { x1: x1, y1: y1, x2: x2, y2: y2 }, callback); } export function initialize (callback) { messageCount = 0; callbacks = []; worker = new Worker('/scripts/workers/board.js'); bind(worker, 'message', messageHandler); post('initialize', settings, callback); }
import settings from 'settings'; import { bind } from 'util/dom'; var worker; var messageCount; var callbacks; function post (command, data, callback) { callbacks[messageCount] = callback; worker.postMessage({ id: messageCount, command: command, data: JSON.parse(JSON.stringify(data)), }); messageCount++; } function messageHandler (event) { var message = event.data; if (callbacks[message.id]) { callbacks[message.id](message.data); delete callbacks[message.id]; } } export function getJewel (x, y, callback) { post('getJewel', { x: x, y: y, }, callback); } export function getBoard (callback) { post('getBoard', null, callback); } export function print () { post('print', null, function (jewels) { console.log(jewels); }); } export function swap (x1, y1, x2, y2, callback) { post('swap', { x1: x1, y1: y1, x2: x2, y2: y2 }, callback); } export function initialize (callback) { messageCount = 0; callbacks = []; worker = new Worker('/scripts/workers/board.js'); bind(worker, 'message', messageHandler); bind(worker, 'error', function (err) { console.log('worker error:', err); }); post('initialize', settings, callback); }
Add error handler to Web Worker
Add error handler to Web Worker
JavaScript
mit
darvelo/match-three
4d84f4549135fce864890b00deedfb81eed3ad23
js/count.js
js/count.js
document.addEventListener("DOMContentLoaded", function (event) { // redirect to 7777 port // ping golang counter httpGetAsync("http://www.aracki.me:7777/count", function (res) { alert(res); }) }); function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4 && xmlHttp.status === 200) callback(xmlHttp.responseText); }; xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.setRequestHeader("Access-Control-Allow-Origin", '*'); xmlHttp.setRequestHeader("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS'); xmlHttp.setRequestHeader("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token'); xmlHttp.send("ivan"); }
document.addEventListener("DOMContentLoaded", function (event) { // redirect to 7777 port // ping golang counter getRequest("localhost:7777/count", function (request) { var response = request.currentTarget.response || request.target.responseText; console.log(response); }) }); function getRequest(url, success) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = success; xhr.send(); return xhr; }
Add getRequest() to golang app
Add getRequest() to golang app
JavaScript
mit
Aracki/aracki.me,Aracki/aracki.me
f4035de99216e3c4d587a53e5f728316acab1f22
server.js
server.js
const express = require('express') const path = require('path') const fs = require('fs') const formidable = require('formidable') const app = express() const PORT = process.env.PORT || 9000 const UPLOAD_DIR = path.join(__dirname, 'uploads/') if (!fs.existsSync(UPLOAD_DIR)) { console.warn('Creating uploads folder...') fs.mkdirSync(UPLOAD_DIR) } console.info(`Uploads will be saved in ${UPLOAD_DIR}`) app.use(express.static(path.join(__dirname, 'build'))) app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')) }) app.post('/uploads', function (req, res) { var form = new formidable.IncomingForm() form.parse(req) form.on('fileBegin', function (name, file) { file.path = `${UPLOAD_DIR}${file.name}` }) form.on('file', function (name, file) { console.log('Uploaded ' + file.name) }) res.header('Access-Control-Allow-Origin', '*') res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ) res.status(200).json({ success: true, status: 'Form successfully submitted' }) }) app.listen(PORT, _ => console.info(`Server listening on PORT ${PORT}...`))
const express = require('express') const path = require('path') const fs = require('fs') const formidable = require('formidable') const app = express() const PORT = process.env.PORT || 9000 const UPLOAD_DIR = path.join(__dirname, 'uploads/') const CORS = process.env.NODE_ENV === 'production' ? process.env.HOST : '*' if (!fs.existsSync(UPLOAD_DIR)) { console.warn('Creating uploads folder...') fs.mkdirSync(UPLOAD_DIR) } console.info(`Uploads will be saved in ${UPLOAD_DIR}`) app.use(express.static(path.join(__dirname, 'build'))) app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'build', 'index.html')) }) app.post('/uploads', function (req, res) { var form = new formidable.IncomingForm() form.parse(req) form.on('fileBegin', function (name, file) { file.path = `${UPLOAD_DIR}${file.name}` }) form.on('file', function (name, file) { console.log('Uploaded ' + file.name) }) res.header('Access-Control-Allow-Origin', CORS) res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ) res.status(200).json({ success: true, status: 'Form successfully submitted' }) }) app.listen(PORT, _ => console.info(`Server listening on PORT ${PORT}...`))
Change CORS to be set by environment
Change CORS to be set by environment
JavaScript
mit
planigan/resource-center,planigan/resource-center,fus-marcom/resource-center,fus-marcom/resource-center
647e62ffa45e6cd91bf2232c7dfbe78055705599
knexfile.js
knexfile.js
/** * This file is automatically loaded when knex runs migrations */ require('babel-register')(); const config = require('./server/config').default; module.exports = { client: 'mssql', connection: { server: config.db.server, user: config.db.user, password: config.db.password, database: config.db.name, options: { encrypt: true, }, }, };
/** * This file is automatically loaded when knex runs migrations */ require('babel-register')(); const config = require('./server/config').default; module.exports = { client: 'mssql', connection: { server: config.db.server, user: config.db.user, password: config.db.password, database: config.db.name, options: { encrypt: true, }, }, acquireConnectionTimeout: 5000, };
Use a more sensible connection timeout for knex
Use a more sensible connection timeout for knex
JavaScript
mit
noms-digital-studio/csra-app,noms-digital-studio/csra-app,noms-digital-studio/csra-app
5df0f46b25b9d97e5a20a9488de3ee01fc9baa71
app/assets/javascripts/deck.js
app/assets/javascripts/deck.js
var Deck = function(cards = []) { this.cards = cards; }; Deck.prototype.addCard = function(card) { this.cards.push(card); }; Deck.prototype.nextCard = function(card) { return this.cards.pop(); }; Deck.prototype.fetchCards = function() { var request = $.ajax({ method: 'POST', url: '/decks/new', data: $("input").serialize() }) .done(function(resp) { deckCallBack(resp); }) }; Deck.prototype.updateHistory = function(card, state) { // Send back the result of the card json_card = { card_id: card["id"], card_name: card["name"], card_state: state } $.ajax({ method: 'PUT', url: '/decks/' + card["id"] + '/update', data: json_card }) };
var Deck = function() { this.cards = []; }; Deck.prototype.addCard = function(card) { this.cards.push(card); }; Deck.prototype.nextCard = function(card) { return this.cards.pop(); }; Deck.prototype.fetchCards = function() { var request = $.ajax({ method: 'POST', url: '/decks/new', data: $("input").serialize() }) .done(function(resp) { deckCallBack(resp); }) }; Deck.prototype.updateHistory = function(card, state) { // Send back the result of the card json_card = { card_id: card["id"], card_name: card["name"], card_state: state } $.ajax({ method: 'PUT', url: '/decks/' + card["id"] + '/update', data: json_card }) };
Remove cards == [] from Deck()
Remove cards == [] from Deck()
JavaScript
mit
zjuanz/tendr,zjuanz/tendr,zjuanz/tendr
b2416e04739afc0ee2c52ed64dabdd069c2ccaa2
app/controllers/application.js
app/controllers/application.js
import Ember from 'ember'; export default Ember.Controller.extend({ flashError: null, nextFlashError: null, showUserOptions: false, stepFlash: function() { this.set('flashError', this.get('nextFlashError')); this.set('nextFlashError', null); }, resetDropdownOption: function(controller, option) { controller.set(option, !controller.get(option)); if (controller.get(option)) { Ember.$(document).on('mousedown.useroptions', function() { Ember.run.later(function() { controller.set(option, false); }, 100); Ember.$(document).off('mousedown.useroptions'); }); } }, actions: { search: function(query) { this.transitionToRoute('search', {queryParams: {q: query}}); }, toggleUserOptions: function() { this.resetDropdownOption(this, 'showUserOptions'); }, }, });
import Ember from 'ember'; export default Ember.Controller.extend({ flashError: null, nextFlashError: null, showUserOptions: false, stepFlash: function() { this.set('flashError', this.get('nextFlashError')); this.set('nextFlashError', null); }, resetDropdownOption: function(controller, option) { controller.set(option, !controller.get(option)); if (controller.get(option)) { Ember.$(document).on('mousedown.useroptions', function() { Ember.run.later(function() { controller.set(option, false); }, 150); Ember.$(document).off('mousedown.useroptions'); }); } }, actions: { search: function(query) { this.transitionToRoute('search', {queryParams: {q: query}}); }, toggleUserOptions: function() { this.resetDropdownOption(this, 'showUserOptions'); }, }, });
Extend the visible time after-click for a dropdown
Extend the visible time after-click for a dropdown
JavaScript
apache-2.0
chenxizhang/crates.io,withoutboats/crates.io,sfackler/crates.io,mbrubeck/crates.io,chenxizhang/crates.io,chenxizhang/crates.io,sfackler/crates.io,BlakeWilliams/crates.io,sfackler/crates.io,withoutboats/crates.io,Susurrus/crates.io,mbrubeck/crates.io,steveklabnik/crates.io,Gankro/crates.io,BlakeWilliams/crates.io,achanda/crates.io,rust-lang/crates.io,mbrubeck/crates.io,achanda/crates.io,steveklabnik/crates.io,BlakeWilliams/crates.io,achanda/crates.io,mbrubeck/crates.io,withoutboats/crates.io,Gankro/crates.io,steveklabnik/crates.io,BlakeWilliams/crates.io,Gankro/crates.io,chenxizhang/crates.io,Susurrus/crates.io,Susurrus/crates.io,rust-lang/crates.io,achanda/crates.io,Gankro/crates.io,rust-lang/crates.io,withoutboats/crates.io,Susurrus/crates.io,steveklabnik/crates.io,rust-lang/crates.io
f04da7379d9c870cc065460d5a20fd90d21dbf78
app/libs/utils/color-string.js
app/libs/utils/color-string.js
'use strict'; // Load requirements const clk = require('chalk'), chalk = new clk.constructor({level: 1, enabled: true}); // Formats a string with ANSI styling module.exports = function(str) { // Variables const regex = /\{([a-z,]+)\:(.+?)\}/gi; let m; // Check for a non-string if ( typeof str !== 'string' ) { return ''; } // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { // Allow for multiple formatting options let split = m[1].split(','), partial = m[2]; // Wrap the replacement area for ( let i in split ) { if ( chalk[split[i]] !== undefined ) { partial = chalk[split[i]](partial); } } // Make the replacement in the original string str = str.replace(m[0], partial); } // Still matches to be made return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
'use strict'; // Load requirements const clk = require('chalk'), chalk = new clk.constructor({level: 1, enabled: true}); // Formats a string with ANSI styling module.exports = function(str) { // Variables const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi; let m; // Check for a non-string if ( typeof str !== 'string' ) { return ''; } // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { // Allow for multiple formatting options let split = m[1].split(','), partial = m[2]; // Wrap the replacement area for ( let i in split ) { if ( chalk[split[i]] !== undefined ) { partial = chalk[split[i]](partial); } } // Make the replacement in the original string str = str.replace(m[0], partial); } // Still matches to be made return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
Improve color string regex pattern for multiline matches
Improve color string regex pattern for multiline matches
JavaScript
apache-2.0
transmutejs/core
0ee588e3e67535829d31b06b5da91ffb3d1910a8
src/apis/GifAPI.js
src/apis/GifAPI.js
import * as _ from 'lodash' import UUID from 'node-uuid'; const KEY = 'GIFS'; export const loadData = () => { let data = JSON.parse(localStorage.getItem(KEY)); if (_.isEmpty(data)) { return {}; } else { return data; } }; export const update = (update) => { localStorage.setItem(KEY, JSON.stringify(update)); }; export const mock = (max = 10) => { localStorage.clear(); let data = []; for(let i = 0; i < max; i++) { data.push({ id: UUID.v4(), name: 'Test ' + i, url: 'http://media2.giphy.com/media/geozuBY5Y6cXm/giphy.gif' }); } localStorage.setItem(KEY, JSON.stringify(data)) };
import * as _ from 'lodash' import UUID from 'node-uuid'; const KEY = 'GIFS'; export const loadData = () => { let data = JSON.parse(localStorage.getItem(KEY)); if (_.isEmpty(data)) { return {}; } else { return data; } }; export const update = (update) => { localStorage.setItem(KEY, JSON.stringify(update)); }; export const mock = (max = 10) => { localStorage.clear(); let data = []; for(let i = 0; i < max; i++) { data.push({ id: UUID.v4(), name: 'Test ' + i, url: 'http://media2.giphy.com/media/geozuBY5Y6cXm/giphy.gif', still_url: 'https://media2.giphy.com/media/geozuBY5Y6cXm/giphy_s.gif' }); } localStorage.setItem(KEY, JSON.stringify(data)) };
Add stil url in mock
Add stil url in mock
JavaScript
mit
macpie/Gif-Chrome-Extension,macpie/Gif-Chrome-Extension
f60385580b7db9ef8a0a8a137d95e08abccb854e
lib/util.js
lib/util.js
/** * Download tool for Unicode CLDR JSON data * * Copyright 2013 Rafael Xavier de Souza * Released under the MIT license * https://github.com/rxaviers/cldr-data-downloader/blob/master/LICENSE-MIT */ "use strict"; var assert = require("assert"); var fs = require("fs"); var url = require("url"); module.exports = { deepEqual: function(a, b) { try { assert.deepEqual(a, b); } catch (error) { if (error.name === "AssertionError") { return false; } throw error; } return true; }, isUrl: function(urlOrPath) { urlOrPath = url.parse(urlOrPath); return urlOrPath.hostname ? true : false; }, readJSON: function(filepath) { return JSON.parse(fs.readFileSync(filepath)); } };
/** * Download tool for Unicode CLDR JSON data * * Copyright 2013 Rafael Xavier de Souza * Released under the MIT license * https://github.com/rxaviers/cldr-data-downloader/blob/master/LICENSE-MIT */ "use strict"; var assert = require("assert"); var fs = require("fs"); var url = require("url"); module.exports = { deepEqual: function(a, b) { try { assert.deepEqual(a, b); } catch (error) { if (error instanceof assert.AssertionError) { return false; } throw error; } return true; }, isUrl: function(urlOrPath) { urlOrPath = url.parse(urlOrPath); return urlOrPath.hostname ? true : false; }, readJSON: function(filepath) { return JSON.parse(fs.readFileSync(filepath)); } };
Check error with instance of
Check error with instance of Closes #22 Signed-off-by: Dominic Bartl <a9662aa7a7b7ac6326ee7732d0f7f2070642dd85@gmail.com>
JavaScript
mit
rxaviers/cldr-data-downloader
9163379bf273fde65b13d8a6b989c9c3b09a079e
app/webpacker/packs/vue_app.js
app/webpacker/packs/vue_app.js
import Vue from 'vue/dist/vue.esm'; import store from '../store/index.js.erb'; import '../config/axios'; import '../directives/selectionchange'; import TheAnnotator from '../components/TheAnnotator.vue.erb'; import AnnotationHandle from "../components/AnnotationHandle"; document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ el: '#app', store, components: { TheAnnotator, AnnotationHandle } }); window.app = app; });
import 'polyfills'; import Vue from 'vue/dist/vue.esm'; import store from '../store/index.js.erb'; import '../config/axios'; import '../directives/selectionchange'; import TheAnnotator from '../components/TheAnnotator.vue.erb'; import AnnotationHandle from "../components/AnnotationHandle"; document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ el: '#app', store, components: { TheAnnotator, AnnotationHandle } }); window.app = app; });
Include polyfills for vue app js
Include polyfills for vue app js
JavaScript
agpl-3.0
harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o
666bc930fece85dc2b45221bd7ffcecb73a057a3
config/bootstrap.js
config/bootstrap.js
/** * Bootstrap * (sails.config.bootstrap) * * An asynchronous bootstrap function that runs before your Sails app gets lifted. * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. * * For more information on bootstrapping your app, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html */ module.exports.bootstrap = function(cb) { Video.findOne({ playing: true }).exec(function(err, current) { if (current) { SyncService.startVideo(current); } cb(); }); };
/** * Bootstrap * (sails.config.bootstrap) * * An asynchronous bootstrap function that runs before your Sails app gets lifted. * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. * * For more information on bootstrapping your app, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html */ module.exports.bootstrap = function(cb) { Video.findOne({ playing: true }).then(function(err, current) { if (current) { SyncService.startVideo(current); } cb(); }); };
Change Bootstrap .exec to .then for consistency
Change Bootstrap .exec to .then for consistency
JavaScript
mit
TheConnMan/jukebot,TheConnMan/jukebot,TheConnMan/jukebot
5712884c7ddbe7edafdf2c3e03f456d031d96e84
app/js/controllers/main_controller.js
app/js/controllers/main_controller.js
annotationApp.controller('MainController', function($scope) { $scope.tokens = [ { 'string' : 'Marcus', 'id' : '1' }, { 'string' : 'rosam', 'id' : '2' }, { 'string' : 'videt', 'id' : '3' }, { 'string' : '.', 'id' : '4' } ]; $scope.selectedToken = { id: '1' }; $scope.currentToken = function() { return $scope.tokens[$scope.selectedToken.id - 1] }; });
annotationApp.controller('MainController', function($scope) { $scope.tokens = [ { 'string' : 'Marcus', 'id' : '1' }, { 'string' : 'rosam', 'id' : '2' }, { 'string' : 'videt', 'id' : '3' }, { 'string' : '.', 'id' : '4' } ]; $scope.selectedToken = { id: '1' }; $scope.currentToken = function() { return $scope.tokens[$scope.selectedToken.id - 1] }; $scope.selectToken = function(id) { $scope.selectedToken.id = id } });
Add function to select a token
Add function to select a token
JavaScript
mit
fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa
4c36269339935f0ccb44dc600d4c1dcd5d2725ec
config/webpack.dev.js
config/webpack.dev.js
const path = require("path"); const merge = require("webpack-merge"); const webpack = require("webpack"); const common = require("./webpack.common.js"); const postCSSPlugins = [ require("postcss-easy-import")({ prefix: "_" }), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-color-function"), require("postcss-hexrgba"), require("autoprefixer") ]; module.exports = merge(common, { entry: [ "webpack-dev-server/client?http://localhost:3000/", "webpack/hot/only-dev-server" ], mode: "development", devtool: "eval-cheap-module-source-map", watch: true, devServer: { headers: { "Access-Control-Allow-Origin": "*" }, hot: true, port: 3000, disableHostCheck: true, overlay: true, contentBase: path.join(__dirname, "../src") }, plugins: [new webpack.HotModuleReplacementPlugin()], module: { rules: [ { test: /\.css$/, use: [ "style-loader", { loader: "css-loader", options: { url: false } }, { loader: "postcss-loader", options: { plugins: postCSSPlugins } } ] } ] } });
const path = require("path"); const merge = require("webpack-merge"); const webpack = require("webpack"); const common = require("./webpack.common.js"); const postCSSPlugins = [ require("postcss-easy-import")({ prefix: "_" }), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-color-function"), require("postcss-hexrgba"), require("autoprefixer") ]; module.exports = merge(common, { entry: [ "webpack-dev-server/client?http://localhost:3000/", "webpack/hot/only-dev-server" ], mode: "development", devtool: "eval-source-map", watch: true, devServer: { headers: { "Access-Control-Allow-Origin": "*" }, hot: true, port: 3000, disableHostCheck: true, overlay: true, contentBase: path.join(__dirname, "../src") }, plugins: [new webpack.HotModuleReplacementPlugin()], module: { rules: [ { test: /\.css$/, use: [ "style-loader", { loader: "css-loader", options: { url: false } }, { loader: "postcss-loader", options: { plugins: postCSSPlugins } } ] } ] } });
Use more reliable JS source mapping technique
Use more reliable JS source mapping technique
JavaScript
mit
trendyminds/pura,trendyminds/pura
091842d279f0456ca9f8f2f062a7d207c4e1466e
spec/client.spec.js
spec/client.spec.js
const Client = require('../lib/client'); const options = { baseUrl: 'some value', username: 'some value', password: 'some value' }; describe('Client', () => { it('should be constructor and factory function', () => { expect(Client).toBeFunction(); expect(new Client(options)).toBeObject(); expect(Client(options)).toBeObject(); }); it('should have properties with api', () => { const client = new Client(options); const apiKeys = Object.keys(client); expect(apiKeys.length).toEqual(1); expect(client['branchPermissions']).toBeObject(); }); it('should have validation for options', () => { expect(() => new Client()).toThrow(); expect(() => new Client(123)).toThrow(); expect(() => new Client({})).toThrow(); expect(() => new Client({ baseUrl: null, username: null, password: null })).toThrow(); expect(() => new Client({ baseUrl: '123' })).toThrow(); expect(() => new Client({ username: '123', password: '123' })).toThrow(); expect(() => new Client({ username: '123', password: '123', baseUrl: '123' })).not.toThrow(); }); });
const Client = require('../lib/client'); const options = { baseUrl: 'some value', username: 'some value', password: 'some value' }; describe('Client', () => { it('should be constructor and factory function', () => { expect(Client).toBeFunction(); expect(new Client(options)).toBeObject(); expect(Client(options)).toBeObject(); }); it('should have properties with api', () => { const client = new Client(options); const apiKeys = Object.keys(client); expect(apiKeys.length).toEqual(1); expect(client['branchPermissions']).toBeObject(); }); it('should have validation for options', () => { expect(() => new Client()).toThrow(); expect(() => new Client(123)).toThrow(); expect(() => new Client({})).toThrow(); expect(() => new Client({ baseUrl: null, username: null, password: null })).toThrow(); expect(() => new Client({ baseUrl: '123' })).toThrow(); expect(() => new Client({ username: '123', password: '123' })).toThrow(); expect(() => new Client({ username: '123', baseUrl: '123' })).toThrow(); expect(() => new Client({ username: '123', password: '123', baseUrl: '123' })).not.toThrow(); }); });
Cover one more branch in unit tests
tests: Cover one more branch in unit tests
JavaScript
mit
bponomarenko/stash-web-api
188f10af537bfdfb3e0c24c676b129efca9117f5
server.js
server.js
var http = require('http'); var fs = require('fs'); var path = require('path'); var mime = require('mime'); var cache = {}; function send404(response) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.write('Error 404: resource not found.'); response.end(); } function sendFile(response, filePath, fileContents) { response.writeHead( 200, {'Content-Type': mime.lookup(path.basename(filePath))} ); response.end(fileContents); }
var http = require('http'); var fs = require('fs'); var path = require('path'); var mime = require('mime'); var cache = {}; function send404(response) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.write('Error 404: resource not found.'); response.end(); } function sendFile(response, filePath, fileContents) { response.writeHead( 200, {'Content-Type': mime.lookup(path.basename(filePath))} ); response.end(fileContents); } function serveStatic(response, cache, absPath) { if (cache[absPath]) { sendFile(response, absPath, cache[absPath]); } else { fs.exists(absPath, function(exists) { if (exists) { fs.readFile(absPath, function(err, data) { if (err) { send404(response); } else { cache[absPath] = data; sendFile(response, absPath, data); } }); } else { send404(response); } }); } }
Add helper function for serving static files
Add helper function for serving static files
JavaScript
mit
sebsonic2o/chatrooms,sebsonic2o/chatrooms
4b14769af554c0a28817f049e75b783dc2c18f36
server.js
server.js
var koa = require('koa'); var http = require('http'); var route = require('koa-route'); var serve = require('koa-static'); var bodyParser = require('koa-bodyparser'); // Koa middleware var error = require('./api/lib/middleware/error'); // Create koa app var app = koa(); // Koa middleware app.use(error()); app.use(bodyParser()); app.use(serve('./frontend/dist')); // API routes app.use(route.post('/generate', require('./api/routes/generate'))); // Define configurable port var port = process.env.PORT || 4000; // Listen for connections app.listen(port); // Log port console.log('Server listening on http://localhost:' + port);
var koa = require('koa'); var http = require('http'); var route = require('koa-route'); var serve = require('koa-static'); var bodyParser = require('koa-bodyparser'); // Koa middleware var error = require('./api/lib/middleware/error'); // Create koa app var app = koa(); // Koa middleware app.use(error()); app.use(bodyParser()); app.use(serve('./frontend/dist')); // API routes app.use(route.post('/generate', require('./api/routes/generate'))); // Define configurable port var port = process.env.PORT || 4000; // Listen for connections app.listen(port); // Log port console.log('Server listening on port ' + port);
Improve port log message syntax
Improve port log message syntax
JavaScript
apache-2.0
eladnava/applicationize,eladnava/applicationize
0736453287987b2221129475d5c2fedfb160d8a2
gulp-tasks/link-js.js
gulp-tasks/link-js.js
'use strict'; (() => { module.exports = (gulp, plugins, config) => { return () => { return plugins.vinylFs.src([config.patternsPath + '/**/*.js', config.patternsPath + '/**/*.json', '!' + config.patternsPath + '/**/rocketbelt.slipsum-cache.json']) .pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') })) .pipe(plugins.vinylFs.symlink(config.templatesPath, { relative: true })); }; }; })();
'use strict'; (() => { module.exports = (gulp, plugins, config) => { return () => { return plugins.vinylFs.src([`${config.patternsPath}/**/*.js`, `${config.patternsPath}/**/*.json`, `!${config.patternsPath}/**/rocketbelt.slipsum-cache.json`, `!${config.patternsPath}/tools/**/*`]) .pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') })) .pipe(plugins.vinylFs.symlink(config.templatesPath, { relative: true })); }; }; })();
Exclude JS files in tools directory from symlinking.
fix(Build): Exclude JS files in tools directory from symlinking.
JavaScript
mit
Pier1/rocketbelt,Pier1/rocketbelt
8de650bcecb75087610aed4352e0a426290f690c
src/modules/common/components/App.js
src/modules/common/components/App.js
import React from 'react'; import {Provider} from 'react-redux'; import {Router, Route, IndexRoute} from 'react-router'; import HomeContainer from '../../home/components/HomeContainer'; import TranslationProvider from './translation/TranslationProvider'; import {routerPaths} from '../constants'; const routes = ( <Route path="/"> <IndexRoute component={HomeContainer}/> <Route path={routerPaths.singleUnit} component={HomeContainer}/> </Route> ); const App = ({store, history}) => ( <TranslationProvider> <Provider store={store}> <Router history={history} routes={routes} key={Math.random()}/> </Provider> </TranslationProvider> ); export default App;
import React from 'react'; import {Provider} from 'react-redux'; import {Router, Route, IndexRoute} from 'react-router'; import HomeContainer from '../../home/components/HomeContainer'; import TranslationProvider from './translation/TranslationProvider'; import {routerPaths} from '../constants'; const routes = ( <Route path="/"> <IndexRoute component={HomeContainer}/> <Route path={routerPaths.singleUnit} component={HomeContainer}/> </Route> ); const App = ({store, history}) => ( <Provider store={store}> <TranslationProvider> <Router history={history} routes={routes} key={Math.random()}/> </TranslationProvider> </Provider> ); export default App;
Change order of translation provider and store provider to allow translation provider access the storage
Change order of translation provider and store provider to allow translation provider access the storage
JavaScript
mit
nordsoftware/outdoors-sports-map,nordsoftware/outdoors-sports-map,nordsoftware/outdoors-sports-map
826d3b49a409fc658991a25f2226f67a0a00722e
src/gates/Joke_NeGate.js
src/gates/Joke_NeGate.js
import {GateBuilder} from "src/circuit/Gate.js" import {Matrix} from "src/math/Matrix.js" import {GatePainting} from "src/draw/GatePainting.js" const NeGate = new GateBuilder(). setSerializedId("NeGate"). setSymbol("-I"). setTitle("Ne-Gate"). setBlurb("Negates all amplitudes."). setDrawer(args => { GatePainting.paintLocationIndependentFrame(args); let {x, y} = args.rect.center(); args.painter.print( "-I", x, y, 'center', 'middle', 'black', '16px monospace', args.rect.w, args.rect.h); }). setKnownEffectToMatrix(Matrix.square(-1, 0, 0, -1)). gate; export {NeGate}
import {GateBuilder} from "src/circuit/Gate.js" import {Matrix} from "src/math/Matrix.js" import {Point} from "src/math/Point.js" import {GatePainting} from "src/draw/GatePainting.js" const NeGate = new GateBuilder(). setSerializedId("NeGate"). setTitle("Ne-Gate"). setBlurb("Negates all amplitudes."). setDrawer(args => { GatePainting.paintLocationIndependentFrame(args); let {x, y} = args.rect.center(); args.painter.strokeLine(new Point(x - 6, y), new Point(x + 6, y), 'black', 2); }). setKnownEffectToMatrix(Matrix.square(-1, 0, 0, -1)). gate; export {NeGate}
Update negate gate symbol to be a single thick line
Update negate gate symbol to be a single thick line
JavaScript
apache-2.0
Strilanc/Quantum-Circuit-Inspector,Strilanc/Quirk,Strilanc/Quirk,Strilanc/Quantum-Circuit-Inspector
4d49374a63ede67e58ead2fd34dc484c67efa606
assignments/javascript/anagram/anagram_test.spec.js
assignments/javascript/anagram/anagram_test.spec.js
var Anagram = require('./anagram'); describe('Anagram', function() { it("no matches",function() { var detector = new Anagram("diaper"); var matches = detector.match([ "hello", "world", "zombies", "pants"]); expect(matches).toEqual([]); }); xit("detects simple anagram",function() { var detector = new Anagram("ba"); var matches = detector.match(['ab', 'abc', 'bac']); expect(matches).toEqual(['ab']); }); xit("detects multiple anagrams",function() { var detector = new Anagram("abc"); var matches = detector.match(['ab', 'abc', 'bac']); expect(matches).toEqual(['abc', 'bac']); }); xit("detects anagram",function() { var detector = new Anagram("listen"); var matches = detector.match(['enlists', 'google', 'inlets', 'banana']); expect(matches).toEqual(['inlets']); }); xit("detects multiple anagrams",function() { var detector = new Anagram("allergy"); var matches = detector.match(['gallery', 'ballerina', 'regally', 'clergy', 'largely', 'leading']); expect(matches).toEqual(['gallery', 'regally', 'largely']); }); });
var Anagram = require('./anagram'); describe('Anagram', function() { it("no matches",function() { var detector = new Anagram("diaper"); var matches = detector.match([ "hello", "world", "zombies", "pants"]); expect(matches).toEqual([]); }); xit("detects simple anagram",function() { var detector = new Anagram("ba"); var matches = detector.match(['ab', 'abc', 'bac']); expect(matches).toEqual(['ab']); }); xit("does not detect false positives",function() { var detector = new Anagram("bba"); var matches = detector.match(["aab"]); expect(matches).toEqual([]); }); xit("detects multiple anagrams",function() { var detector = new Anagram("abc"); var matches = detector.match(['ab', 'abc', 'bac']); expect(matches).toEqual(['abc', 'bac']); }); xit("detects anagram",function() { var detector = new Anagram("listen"); var matches = detector.match(['enlists', 'google', 'inlets', 'banana']); expect(matches).toEqual(['inlets']); }); xit("detects multiple anagrams",function() { var detector = new Anagram("allergy"); var matches = detector.match(['gallery', 'ballerina', 'regally', 'clergy', 'largely', 'leading']); expect(matches).toEqual(['gallery', 'regally', 'largely']); }); });
Add test for same length, same letters, different letter instance counts
Add test for same length, same letters, different letter instance counts One possible solution to detecting an anagram might be to check to see if the words are the same length and that each letter from the first word is contained in the second word. This additional test would guard against that solution appearing to work. I wasn't sure in what position in the test sequence it ought to go, or what the exact test description should be. Feel free to suggest changes.
JavaScript
mit
wobh/xjavascript,marcCanipel/xjavascript,marcCanipel/xjavascript,nicgallardo/xjavascript,a25patel/xjavascript,cloudleo/xjavascript,schorsch3000/xjavascript,wobh/xjavascript,JenanMannette/xjavascript,Vontei/Xjavascript-Solutions,eloquence/xjavascript,exercism/xjavascript,nicgallardo/xjavascript,exercism/xjavascript,a25patel/excercismExcercises,cloudleo/xjavascript,Vontei/xjavascript,eloquence/xjavascript,schorsch3000/xjavascript,Vontei/xjavascript,a25patel/excercismExcercises,Vontei/Xjavascript-Solutions,ZacharyRSmith/xjavascript,JenanMannette/xjavascript,a25patel/xjavascript,ZacharyRSmith/xjavascript
214861a2176e4beb47802ef192927a286301fefe
packages/core/lib/commands/console.js
packages/core/lib/commands/console.js
const command = { command: "console", description: "Run a console with contract abstractions and commands available", builder: {}, help: { usage: "truffle console [--network <name>] [--verbose-rpc]", options: [ { option: "--network <name>", description: "Specify the network to use. Network name must exist in the configuration." }, { option: "--verbose-rpc", description: "Log communication between Truffle and the Ethereum client." } ] }, run: async function (options) { const { promisify } = require("util"); const Config = require("@truffle/config"); const Console = require("../console"); const { Environment } = require("@truffle/environment"); const config = Config.detect(options); // This require a smell? const commands = require("./index"); const excluded = new Set(["console", "init", "watch", "develop"]); const consoleCommands = Object.keys(commands).reduce((acc, name) => { return !excluded.has(name) ? Object.assign(acc, {[name]: commands[name]}) : acc; }, {}); await Environment.detect(config); const c = new Console(consoleCommands, config.with({noAliases: true})); return await promisify(c.start)(); } }; module.exports = command;
const { promisify } = require("util"); const command = { command: "console", description: "Run a console with contract abstractions and commands available", builder: {}, help: { usage: "truffle console [--network <name>] [--verbose-rpc]", options: [ { option: "--network <name>", description: "Specify the network to use. Network name must exist in the configuration." }, { option: "--verbose-rpc", description: "Log communication between Truffle and the Ethereum client." } ] }, run: async function (options) { const Config = require("@truffle/config"); const Console = require("../console"); const { Environment } = require("@truffle/environment"); const config = Config.detect(options); // This require a smell? const commands = require("./index"); const excluded = new Set(["console", "init", "watch", "develop"]); const consoleCommands = Object.keys(commands).reduce((acc, name) => { return !excluded.has(name) ? Object.assign(acc, {[name]: commands[name]}) : acc; }, {}); await Environment.detect(config); const c = new Console(consoleCommands, config.with({noAliases: true})); return await promisify(c.start)(); } }; module.exports = command;
Move promisify require to top of file
Move promisify require to top of file
JavaScript
mit
ConsenSys/truffle
f2ed67e33ec475506a9d5c5dfcfbd985a274b5f7
Presentation.Web/protractor.conf.js
Presentation.Web/protractor.conf.js
var paths = require('../paths.config.js'); exports.config = { // Path to the selenium server jar. Update version number accordingly! seleniumServerJar: paths.seleniumServerJar, // select all end to end tests specs: paths.e2eFiles, resultJsonOutputFile: paths.e2eReport };
var paths = require('../paths.config.js'); exports.config = { // Path to the selenium server jar. Update version number accordingly! seleniumServerJar: paths.seleniumServerJar, // select all end to end tests specs: paths.e2eFiles, resultJsonOutputFile: paths.e2eReport, // Increase timeout to allow AppVeyor to rebuild database on first instantiation. allScriptsTimeout: 30000 };
Increase protractor timeout limit to enable AppVeyor to build database on first instantiation.
Increase protractor timeout limit to enable AppVeyor to build database on first instantiation.
JavaScript
mpl-2.0
os2kitos/kitos,os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos,miracle-as/kitos,miracle-as/kitos,os2kitos/kitos
159689207deab42fbc4626d8f8b38d3e94c880ea
src/angular-ladda-lw.js
src/angular-ladda-lw.js
angular.module('ladda-lw', ['ngAnimate']).directive('ladda', function laddaDirective() { return { restrict: 'A', scope: { ladda: '=', }, compile: (element, attrs) => { const lLoading = attrs.ladda; element.addClass('ladda-lw'); const textWrap = angular.element(` <div class="ladda-lw__text" ng-class="{\'ladda-lw__text--up\': ' + lLoading + '}"> </div> `); textWrap.append(element.contents()); element.append(textWrap); const loadingWrap = angular.element('<div class="ladda-lw__loading-wrap"></div>'); const loading = angular.element('<div class="ladda-lw__loading" ng-class="{\'ladda-lw__loading--up\': ' + lLoading + '}"></div>'); loadingWrap.append(loading); element.append(loadingWrap); return function link(scope, iElement) { scope.$watch('ladda', function laddaWatch(l) { iElement.attr('disabled', l ? 'disabled' : false); }); }; }, }; });
angular.module('ladda-lw', ['ngAnimate']).directive('ladda', function laddaDirective() { return { restrict: 'A', scope: { ladda: '=', }, compile: (element, attrs) => { const lLoading = attrs.ladda; element.addClass('ladda-lw'); const textWrap = angular.element(` <div class="ladda-lw__text" ng-class="{'ladda-lw__text--up': ${lLoading}}"> </div> `); textWrap.append(element.contents()); element.append(textWrap); const loadingWrap = angular.element(`<div class="ladda-lw__loading-wrap"></div>`); const loading = angular.element(` <div class="ladda-lw__loading" ng-class="{'ladda-lw__loading--up': ${lLoading}}"> </div> `); loadingWrap.append(loading); element.append(loadingWrap); return function link(scope, iElement) { scope.$watch('ladda', function laddaWatch(l) { iElement.attr('disabled', l ? 'disabled' : false); }); }; }, }; });
Fix for templates in es6
Fix for templates in es6
JavaScript
mit
aeharding/angular-ladda-lw,aeharding/angular-ladda-lw
1600a066ccdb6cbb1b55ecfc0eb526f1854350e0
Public/Resources/Javascript/global-config.js
Public/Resources/Javascript/global-config.js
/* We have to setup the global variables which will be used for web application. As now everything comes from webframework globally so I put it here temprarily. When we completely moved back ferite webframework then we setup it to main.js file */ var scriptSrcPath = "/Cention.app/Resources/ReactSrc/"; var imageSrcPath = "/Cention.app/Resources/Images/"; var webRoot = "/web/"; var controllerPath = "/Cention/";
/* We have to setup the global variables which will be used for web application. As now everything comes from webframework globally so I put it here temprarily. When we completely moved back ferite webframework then we setup it to main.js file */ var scriptSrcPath = "/Cention.app/Resources/ReactSrc/"; var imageSrcPath = "/Cention.app/Resources/Images/"; var webRoot = "/Cention/web/"; var controllerPath = "/";
Change controllerPath and webRoot for customer server installation
Change controllerPath and webRoot for customer server installation
JavaScript
bsd-3-clause
cention/ferite-module-webframework,cention/ferite-module-webframework,cention/ferite-module-webframework
2ce7a8500f9b3ed7765a4befc070faecb87c7d4c
src/client/js/models/chatlog/index.js
src/client/js/models/chatlog/index.js
/* -*- js2-basic-offset: 2; indent-tabs-mode: nil; -*- */ /* vim: set ft=javascript ts=2 et sw=2 tw=80; */ "use strict"; require("sockjs"); let Sock = window.SockJS, {addMethod} = require("genfun"), {clone, init} = require("../../lib/proto"), _ = require("lodash"), can = require("../../shims/can"); /** * Chatlog Model */ let Chatlog = clone(); /* * Init */ addMethod(init, [Chatlog], function(log, url) { initSocket(log, url); initModelList(log); }); function initSocket(log) { log.socket = new Sock("http://localhost:8080/ws"); log.socket.onmessage = _.partial(onMessage, log); } function initModelList(log) { log.lines = new LogLine.List([]); } function onMessage(log, message) { log.lines.push(new LogLine({text: message.data})); } function addLine(log, line) { log.socket.send(line); } /* * Canjs Model */ var LogLine = can.Model.extend({},{}); module.exports.Chatlog = Chatlog; module.exports.addLine = addLine;
/* -*- js2-basic-offset: 2; indent-tabs-mode: nil; -*- */ /* vim: set ft=javascript ts=2 et sw=2 tw=80; */ "use strict"; require("sockjs"); let Sock = window.SockJS, {addMethod} = require("genfun"), {clone, init} = require("../../lib/proto"), _ = require("lodash"), can = require("../../shims/can"); /** * Chatlog Model */ let Chatlog = clone(); /* * Init */ addMethod(init, [Chatlog], function(log, url) { initSocket(log, url); initModelList(log); }); function initSocket(log) { log.socket = new Sock("http://localhost:8080/ws"); log.socket.onmessage = _.partial(onMessage, log); // TODO - this is probably a pretty naive way to go about reconnecting... log.socket.onclose = _.partial(initSocket, log); } function initModelList(log) { log.lines = new LogLine.List([]); } function onMessage(log, message) { log.lines.push(new LogLine({text: message.data})); } function addLine(log, line) { log.socket.send(line); } /* * Canjs Model */ var LogLine = can.Model.extend({},{}); module.exports.Chatlog = Chatlog; module.exports.addLine = addLine;
Reconnect if connection is lost
Reconnect if connection is lost
JavaScript
agpl-3.0
zkat/storychat
9c448e669a966c307bc1218d58300c3a46bcec43
src/js/model/refugee-constants.js
src/js/model/refugee-constants.js
var moment = require('moment'); // NOTE: month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; module.exports.DATA_START_MOMENT = moment([ module.exports.DATA_START_YEAR, module.exports.DATA_START_MONTH]).startOf('month'); module.exports.DATA_END_YEAR = 2016; module.exports.DATA_END_MONTH = 1; module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month'); module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 3, 18]); module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN']; module.exports.fullRange = [module.exports.DATA_START_MOMENT.unix(), module.exports.DATA_END_MOMENT.unix()]; module.exports.labelShowBreakPoint = 992;
var moment = require('moment'); // NOTE: month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; module.exports.DATA_START_MOMENT = moment([ module.exports.DATA_START_YEAR, module.exports.DATA_START_MONTH]).startOf('month'); module.exports.DATA_END_YEAR = 2016; module.exports.DATA_END_MONTH = 2; module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month'); module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 3, 18]); module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN']; module.exports.fullRange = [module.exports.DATA_START_MOMENT.unix(), module.exports.DATA_END_MOMENT.unix()]; module.exports.labelShowBreakPoint = 992;
Extend visualisation period to March
Extend visualisation period to March
JavaScript
mit
lucified/lucify-asylum-countries,lucified/lucify-asylum-countries,lucified/lucify-asylum-countries,lucified/lucify-asylum-countries
62ce6e6f8111497d5bee0cc3bd44c4a1902eb317
src/lib/control/typeahead/normalizer/TypeaheadNormalizer.js
src/lib/control/typeahead/normalizer/TypeaheadNormalizer.js
/** * @requires javelin-install * @provides javelin-typeahead-normalizer * @javelin */ /** * @group control */ JX.install('TypeaheadNormalizer', { statics : { normalize : function(str) { return ('' + str) .toLowerCase() .replace(/[^a-z0-9 ]/g, '') .replace(/ +/g, ' ') .replace(/^\s*|\s*$/g, ''); } } });
/** * @requires javelin-install * @provides javelin-typeahead-normalizer * @javelin */ /** * @group control */ JX.install('TypeaheadNormalizer', { statics : { /** * Normalizes a string by lowercasing it and stripping out extra spaces * and punctuation. * * @param string * @return string Normalized string. */ normalize : function(str) { return ('' + str) .toLocaleLowerCase() .replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g, '') .replace(/ +/g, ' ') .replace(/^\s*|\s*$/g, ''); } } });
Use Punctuation Blacklist for Typeahead Normalizer
Use Punctuation Blacklist for Typeahead Normalizer Summary: This changes the Typeahead normalizer to use a punctuation blacklist instead of stripping all non-alphanumeric characters. As the normalizer stands now, any international characters (e.g. Japanese characters) are stripped. Reviewers: epriestley, jg Test Plan: > JX.TypeaheadNormalizer.normalize('Get rid of the periods...') "get rid of the periods" > JX.TypeaheadNormalizer.normalize('ラジオ') "ラジオ" Differential Revision: 924
JavaScript
bsd-3-clause
phacility/javelin,phacility/javelin,phacility/javelin,phacility/javelin,phacility/javelin
23e1f61e01d8f6d8fb3760bcd01bc50b17cdeaf7
dashboard/app/scripts/collections/user-request-collection.js
dashboard/app/scripts/collections/user-request-collection.js
/*jshint -W106*/ /*global define*/ define(['underscore', 'backbone', 'models/user-request-model'], function(_, Backbone, UserRequestModel) { 'use strict'; var UserRequestCollection = Backbone.Collection.extend({ url: function() { return '/api/v2/cluster/' + this.cluster + '/request'; }, model: UserRequestModel, initialize: function(models, options) { if (options && options.cluster) { this.cluster = options.cluster; } } }); return UserRequestCollection; });
/*jshint -W106*/ /*global define*/ define(['underscore', 'backbone', 'models/user-request-model'], function(_, Backbone, UserRequestModel) { 'use strict'; var UserRequestCollection = Backbone.Collection.extend({ url: function() { return '/api/v2/cluster/' + this.cluster + '/request' + this.params; }, parse: function(resp) { return resp.results; }, model: UserRequestModel, params: '?page_size=32', initialize: function(models, options) { if (options && options.cluster) { this.cluster = options.cluster; } }, // Only grab requests with state submitted getSubmitted: function(options) { this.params = '?state=submitted&page_size=32'; var self = this; return this.fetch(options).always(function() { self.params = '?page_size=32'; }); } }); return UserRequestCollection; });
Set page_size and state on collection requests
Set page_size and state on collection requests
JavaScript
mit
SUSE/calamari-clients,ceph/calamari-clients,ceph/calamari-clients,ceph/romana,SUSE/romana,GregMeno/test,SUSE/calamari-clients,SUSE/romana,ceph/romana,SUSE/calamari-clients,SUSE/romana,GregMeno/test,ceph/romana,ceph/calamari-clients,SUSE/calamari-clients,SUSE/romana,SUSE/calamari-clients,ceph/romana,ceph/romana,ceph/calamari-clients,GregMeno/test,ceph/calamari-clients,GregMeno/test,SUSE/romana,GregMeno/test
1a9d382e09906e5b6e05ded1b391f337e9a8f69d
app/controllers/dashboard/session-manager/session/entries/new.js
app/controllers/dashboard/session-manager/session/entries/new.js
import { inject as service } from '@ember/service'; import Controller from '@ember/controller'; import { task, timeout } from 'ember-concurrency'; export default Controller.extend({ flashMessages: service(), searchGroup: task(function* (term){ yield timeout(600); let kindOptions = { 'Chorus': 32, 'Quartet': 41, }; let kindModel = this.get('model.session.kind'); let kindInt = kindOptions[kindModel]; let groups = yield this.get('store').query('group', { 'nomen__icontains': term, 'status': 10, 'page_size': 1000, 'kind': kindInt, }); return groups }), searchPerson: task(function* (term){ yield timeout(600); return this.get('store').query('person', { 'nomen__icontains': term, 'page_size': 1000 }) .then((data) => data); }), actions: { saveEntry(entry){ entry.save() .then(() => { this.get('flashMessages').success('Saved'); this.transitionToRoute('dashboard.session-manager.session.entries.entry', entry); }); }, cancelEntry(){ this.get('model').deleteRecord(); this.transitionToRoute('dashboard.session-manager.session.entries.index'); }, willTransition() { this._super(...arguments); const record = this.get('model'); record.rollbackAttributes(); }, }, });
import { inject as service } from '@ember/service'; import Controller from '@ember/controller'; import { task, timeout } from 'ember-concurrency'; export default Controller.extend({ flashMessages: service(), searchGroup: task(function* (term){ yield timeout(600); let kindOptions = { 'Chorus': 32, 'Quartet': 41, }; let kindModel = this.get('model.session.kind'); let kindInt = kindOptions[kindModel]; let groups = yield this.get('store').query('group', { 'nomen__icontains': term, 'status__gt': 0, 'page_size': 1000, 'kind': kindInt, }); return groups }), searchPerson: task(function* (term){ yield timeout(600); return this.get('store').query('person', { 'nomen__icontains': term, 'page_size': 1000 }) .then((data) => data); }), actions: { saveEntry(entry){ entry.save() .then(() => { this.get('flashMessages').success('Saved'); this.transitionToRoute('dashboard.session-manager.session.entries.entry', entry); }); }, cancelEntry(){ this.get('model').deleteRecord(); this.transitionToRoute('dashboard.session-manager.session.entries.index'); }, willTransition() { this._super(...arguments); const record = this.get('model'); record.rollbackAttributes(); }, }, });
Include exempt groups in search
Include exempt groups in search
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
9067165f7c34b397f227f76c042bbac248b55b52
app/models/experiment-schema.server.model.js
app/models/experiment-schema.server.model.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema, MediaSchema = require('./media.server.model').schema, _ = require('lodash'); /** * ExperimentSchema Schema */ var ExperimentSchemaSchema = new Schema({ trialCount: { type: Number, required: true }, mediaPool: [{ type: Schema.Types.ObjectId, ref: 'Media' }] }); // Validator that requires the value is an array and contains at least one entry function requiredArrayValidator(value) { return Object.prototype.toString.call(value) === '[object Array]' && value.length > 0; } // Use the above validator for `mediaPool` ExperimentSchemaSchema.path('mediaPool').validate(requiredArrayValidator); ExperimentSchemaSchema.methods.buildExperiment = function(callback) { // Populate mediaPool this.populate('mediaPool'); var selectedMedia = _.sample(this.mediaPool, this.trialCount); if (typeof callback === 'function') { return callback(null, {media: selectedMedia}); } else { return {media: selectedMedia}; } }; // Register schema for `ExperimentSchema` model mongoose.model('ExperimentSchema', ExperimentSchemaSchema);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema, MediaSchema = require('./media.server.model').schema, _ = require('lodash'); /** * ExperimentSchema Schema */ var ExperimentSchemaSchema = new Schema({ structure: {}, sensors: [String], trialCount: { type: Number, required: true }, mediaPool: [{ type: Schema.Types.ObjectId, ref: 'Media' }] }); // Validator that requires the value is an array and contains at least one entry function requiredArrayValidator(value) { return Object.prototype.toString.call(value) === '[object Array]' && value.length > 0; } // Use the above validator for `mediaPool` ExperimentSchemaSchema.path('mediaPool').validate(requiredArrayValidator); ExperimentSchemaSchema.methods.buildExperiment = function(callback) { // Populate mediaPool this.populate('mediaPool'); var selectedMedia = _.sample(this.mediaPool, this.trialCount); var schemaSubset = { _id: this._id, structure: this.structure, sensors: this.sensors, media: selectedMedia, }; if (typeof callback === 'function') { return callback(null, schemaSubset); } else { return schemaSubset; } }; // Register schema for `ExperimentSchema` model mongoose.model('ExperimentSchema', ExperimentSchemaSchema);
Return structure and sensors with ExperimentSchema
Return structure and sensors with ExperimentSchema
JavaScript
mit
brennon/eim,brennon/eim,brennon/eim,brennon/eim
23223ca4b00a8cab8c2afe164fa86d45e8bc5bcf
src/common/components/GroupItem.js
src/common/components/GroupItem.js
import { List } from 'material-ui/List'; import React from 'react'; import { Link } from 'react-router'; import MemberItem from './MemberItem'; export default class GroupItem extends React.Component { static propTypes = { id: React.PropTypes.string, isAdmin: React.PropTypes.bool, isMember: React.PropTypes.bool, name: React.PropTypes.string, members: React.PropTypes.array, } renderHeader() { if (this.props.isAdmin) { return <h2><Link to={`/group/${this.props.id}`}>{this.props.name}</Link></h2>; } return <h2>{this.props.name}</h2>; } render() { const members = this.props.members.filter(member => member.user); if (!members.length) { return null; } return ( <List> {this.renderHeader()} {members.sort((a, b) => a.user.name > b.user.name).map(member => <MemberItem key={member.id} isMember={this.props.isMember} {...member} />)} </List> ); } }
import { List } from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import React from 'react'; import { Link } from 'react-router'; import MemberItem from './MemberItem'; export default class GroupItem extends React.Component { static propTypes = { id: React.PropTypes.string, isAdmin: React.PropTypes.bool, isMember: React.PropTypes.bool, name: React.PropTypes.string, members: React.PropTypes.array, } renderHeader() { if (this.props.isAdmin) { return <Subheader style={{ textTransform: 'uppercase' }}><Link to={`/group/${this.props.id}`}>{this.props.name}</Link></Subheader>; } return <Subheader style={{ textTransform: 'uppercase' }}>{this.props.name}</Subheader>; } render() { const members = this.props.members.filter(member => member.user); if (!members.length) { return null; } return ( <List> {this.renderHeader()} {members.sort((a, b) => a.user.name > b.user.name).map(member => <MemberItem key={member.id} isMember={this.props.isMember} {...member} />)} </List> ); } }
Use subheaders in member list
Use subheaders in member list
JavaScript
agpl-3.0
strekmann/nidarholmjs,strekmann/nidarholmjs,strekmann/nidarholmjs,strekmann/nidarholmjs
976953f7392ac8d42105fc43a98be05dbd29d37d
src/components/MainHeader/index.js
src/components/MainHeader/index.js
import MainHeader from './MainHeader' import Logo from './Logo' import LogoText from './LogoText' import Navbar from './Navbar' import NavbarMenu from './NavbarMenu' import SidebarToggle from './SidebarToggle' import ControlSidebarToggle from './ControlSidebarToggle' import Messages from './Messages' import MessageItem from './MessageItem' import Notifications from './Notifications' import NotificationItem from './NotificationItem' import Tasks from './Tasks' import TaskItem from './TaskItem' import User from './User' import UserHeader from './UserHeader' import UserBody from './UserBody' import UserBodyItem from './UserBodyItem' import UserFooter from './UserFooter' import UserFooterItem from './UserFooterItem' export default { MainHeader, Logo, LogoText, Navbar, NavbarMenu, SidebarToggle, ControlSidebarToggle, Messages, MessageItem, Notifications, NotificationItem, Tasks, TaskItem, User, UserHeader, UserBody, UserBodyItem, UserFooter, UserFooterItem }
import MainHeader from './MainHeader' import Logo from './Logo' import LogoText from './LogoText' import Navbar from './Navbar' import NavbarMenu from './NavbarMenu' import SidebarToggle from './SidebarToggle' import ControlSidebarToggle from './ControlSidebarToggle' import Messages from './Messages' import MessageItem from './MessageItem' import Notifications from './Notifications' import NotificationItem from './NotificationItem' import Tasks from './Tasks' import TaskItem from './TaskItem' import User from './User' import UserHeader from './UserHeader' import UserBody from './UserBody' import UserBodyItem from './UserBodyItem' import UserFooter from './UserFooter' import UserFooterItem from './UserFooterItem' MainHeader.MainHeader = MainHeader MainHeader.Logo = Logo MainHeader.LogoText = LogoText MainHeader.Navbar = Navbar MainHeader.NavbarMenu = NavbarMenu MainHeader.SidebarToggle = SidebarToggle MainHeader.ControlSidebarToggle = ControlSidebarToggle MainHeader.Messages = Messages MainHeader.MessageItem = MessageItem MainHeader.Notifications = Notifications MainHeader.NotificationItem = NotificationItem MainHeader.Tasks = Tasks MainHeader.TaskItem = TaskItem MainHeader.User = User MainHeader.UserHeader = UserHeader MainHeader.UserBody = UserBody MainHeader.UserBodyItem = UserBodyItem MainHeader.UserFooter = UserFooter MainHeader.UserFooterItem = UserFooterItem export default MainHeader
Change way of exports MainHeader Components
Change way of exports MainHeader Components For: https://github.com/falmar/react-adm-lte/issues/2
JavaScript
mit
falmar/react-adm-lte
79e420facbf85e450abe75e73ab50966d3a0d8fd
app/assets/javascripts/whitehall.js
app/assets/javascripts/whitehall.js
jQuery(document).ready(function($) { $(".flash.notice, .flash.alert").flashNotice(); // This is useful for toggling CSS helpers // whilst developing.. cmd+G var cmdDown = false; $('body').keydown(function(event) { if (event.keyCode == '91') { cmdDown = true; } if (cmdDown && event.keyCode == '71') { event.preventDefault(); $(this).toggleClass('dev'); } }).keyup(function(event) { if (event.keyCode == '91') { cmdDown = false; } }); $(".chzn-select").chosen(); $("#completed_fact_check_requests").markLinkedAnchor(); $('fieldset.sortable legend').each(function () { $(this).append(' (drag up and down to re-order)'); }) });
jQuery(document).ready(function($) { $(".flash.notice, .flash.alert").flashNotice(); // This is useful for toggling CSS helpers // whilst developing.. cmd+G var cmdDown = false; $('body').keydown(function(event) { if (event.keyCode == '91') { cmdDown = true; } if (cmdDown && event.keyCode == '71') { event.preventDefault(); $(this).toggleClass('dev'); } }).keyup(function(event) { if (event.keyCode == '91') { cmdDown = false; } }); $(".chzn-select").chosen({allow_single_deselect: true}); $("#completed_fact_check_requests").markLinkedAnchor(); $('fieldset.sortable legend').each(function () { $(this).append(' (drag up and down to re-order)'); }) });
Allow de-select on single selects with a blank option.
Allow de-select on single selects with a blank option.
JavaScript
mit
ggoral/whitehall,YOTOV-LIMITED/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,robinwhittleton/whitehall,alphagov/whitehall,alphagov/whitehall,askl56/whitehall,ggoral/whitehall,ggoral/whitehall,askl56/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,robinwhittleton/whitehall,alphagov/whitehall,alphagov/whitehall,hotvulcan/whitehall,YOTOV-LIMITED/whitehall,ggoral/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall
1de53839f2cd6677b4851328727c79268ebaa278
app/feeds/new/add-operator/route.js
app/feeds/new/add-operator/route.js
import Ember from 'ember'; export default Ember.Route.extend({ createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'), beforeModel: function(transition) { var controller = this; var feedModel = this.get('createFeedFromGtfsService').feedModel; var url = feedModel.get('url'); var adapter = this.get('store').adapterFor('feeds'); var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info'; var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}}); promise.then(function(response) { if (response.status == 'complete') { feedModel.set('id', response.feed.onestop_id); feedModel.set('operators_in_feed', response.feed.operators_in_feed); response.operators.map(function(operator){feedModel.addOperator(operator)}); return feedModel; } else if (response.status == 'processing') { transition.abort(); return Ember.run.later(controller, function(){ transition.retry(); }, 1000); } }).catch(function(error) { error.errors.forEach(function(error){ feedModel.get('errors').add('url', error.message); }); }); return promise; }, model: function() { return this.get('createFeedFromGtfsService').feedModel; }, actions: { error: function(error, transition) { return this.transitionTo('feeds.new'); } } });
import Ember from 'ember'; export default Ember.Route.extend({ createFeedFromGtfsService: Ember.inject.service('create-feed-from-gtfs'), beforeModel: function(transition) { var controller = this; var feedModel = this.get('createFeedFromGtfsService').feedModel; var url = feedModel.get('url'); var adapter = this.get('store').adapterFor('feeds'); var fetch_info_url = adapter.urlPrefix()+'/feeds/fetch_info'; var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}}); promise.then(function(response) { if (response.status == 'complete') { feedModel.set('id', response.feed.onestop_id); feedModel.set('operators_in_feed', response.feed.operators_in_feed); response.operators.map(function(operator){feedModel.addOperator(operator)}); return feedModel; } else { transition.abort(); return Ember.run.later(controller, function(){ transition.retry(); }, 1000); } }).catch(function(error) { error.errors.forEach(function(error){ feedModel.get('errors').add('url', error.message); }); }); return promise; }, model: function() { return this.get('createFeedFromGtfsService').feedModel; }, actions: { error: function(error, transition) { return this.transitionTo('feeds.new'); } } });
Allow additional response states (queued, downloading, processing)
Allow additional response states (queued, downloading, processing)
JavaScript
mit
transitland/feed-registry,transitland/feed-registry
f243ee0236cc8899c1286e853603777a3940c2c3
blueprints/ember-cli-paint/index.js
blueprints/ember-cli-paint/index.js
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'liquid-fire', target: '0.15.0' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.6.10' }, { name: 'spinjs', target: '2.0.1' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner": true,', { after: '"predef": {\n' } ); }.bind(this)); }.bind(this)); } }
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'liquid-fire', target: '0.17.1' }, { name: 'ember-rl-dropdown', target: 'git+https://git@github.com/alphasights/ember-rl-dropdown.git' }, { name: 'ember-cli-tooltipster', target: '0.0.6' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.6.10' }, { name: 'spinjs', target: '2.0.1' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner": true,', { after: '"predef": {\n' } ); }.bind(this)); }.bind(this)); } }
Add rl-dropdown and tooltipster addons to afterInstall hook
Add rl-dropdown and tooltipster addons to afterInstall hook
JavaScript
mit
alphasights/ember-cli-paint,alphasights/ember-cli-paint
88a1f0ad4fe017951e6ee12d2ffd06b9faa63852
src/core/texture.js
src/core/texture.js
let gpu = null; module.exports = class Texture { /** * @desc WebGl Texture implementation in JS * @constructor Texture * @param {Object} texture * @param {Array} size * @param {Array} dimensions * @param {Object} webGl */ constructor(texture, size, dimensions, webGl) { this.texture = texture; this.size = size; this.dimensions = dimensions; this.webGl = webGl; } /** * @name toArray * @function * @memberOf Texture# * * @desc Converts the Texture into a JavaScript Array. * * @param {Object} The `gpu` Object * */ toArray(gpu) { const copy = gpu.createKernel(function(x) { return x[this.thread.z][this.thread.y][this.thread.x]; }).setDimensions(this.dimensions); return copy(this); } /** * @name delete * @desc Deletes the Texture. * @function * @memberOf Texture# * * */ delete() { return this.webGl.deleteTexture(this.texture); } };
let gpu = null; module.exports = class Texture { /** * @desc WebGl Texture implementation in JS * @constructor Texture * @param {Object} texture * @param {Array} size * @param {Array} dimensions * @param {Object} webGl */ constructor(texture, size, dimensions, webGl) { this.texture = texture; this.size = size; this.dimensions = dimensions; this.webGl = webGl; } /** * @name toArray * @function * @memberOf Texture# * * @desc Converts the Texture into a JavaScript Array. * * @param {Object} The `gpu` Object * */ toArray(gpu) { if(!gpu) throw new Error('You need to pass the GPU object for toArray to work.'); const copy = gpu.createKernel(function(x) { return x[this.thread.z][this.thread.y][this.thread.x]; }).setDimensions(this.dimensions); return copy(this); } /** * @name delete * @desc Deletes the Texture. * @function * @memberOf Texture# * * */ delete() { return this.webGl.deleteTexture(this.texture); } };
Throw error if GPU object not passed
Throw error if GPU object not passed
JavaScript
mit
abhisheksoni27/gpu.js,gpujs/gpu.js,gpujs/gpu.js
1007897ded24181fe74d7ee6e11c101afbd68bca
redux/main.js
redux/main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; // import {createStore} from 'redux'; // ReactDOM.render(<App />, document.getElementById('app')); const counter = (state = 0, action) => { switch(action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } const createStore = (render) => { let state; let listeners = []; const getState = () => state; const = (action) => { state = render(state, action); listeners.forEach(listener => listener()); }; const subscribe = (listener) => { listeners.push(listener); return () => { listeners = listeners.filter(l => l !== listener); } }; dispatch({}); return {getState, dispatch, subscribe}; } const store = createStore(counter); // This is the callback for store // whenver there is an dispatcher event. const render = () => { document.body.innerText = store.getState(); if (store.getState() === 10) { // Unsubscribe!! subsciption(); } }; var subsciption = store.subscribe(render); render(); document.addEventListener('click', () => { store.dispatch({type: 'INCREMENT'}); });
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; // import {createStore} from 'redux'; // ReactDOM.render(<App />, document.getElementById('app')); const counter = (state = 0, action) => { switch(action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } const createStore = (render) => { let state; let listeners = []; const getState = () => state; const dispatch = (action) => { state = render(state, action); listeners.forEach(listener => listener()); }; const subscribe = (listener) => { listeners.push(listener); return () => { listeners = listeners.filter(l => l !== listener); } }; dispatch({}); return {getState, dispatch, subscribe}; } const store = createStore(counter); // This is the callback for store // whenver there is an dispatcher event. const render = () => { document.body.innerText = store.getState(); if (store.getState() === 10) { // Unsubscribe!! subsciption(); } }; var subsciption = store.subscribe(render); render(); document.addEventListener('click', () => { store.dispatch({type: 'INCREMENT'}); });
Create our own createStore and fix typo
Redux: Create our own createStore and fix typo
JavaScript
mit
gongmingqm10/EggHead,gongmingqm10/EggHead,gongmingqm10/EggHead,gongmingqm10/EggHead
553838d49c22388ce2d7bffcfe5647c7ffb8c702
modes/fast.js
modes/fast.js
var VML = require('./vml'); var Canvas = require('./canvas'); //var Flash = require('./flash'); var hasCanvas = function(){ var canvas = document.createElement('canvas'); return canvas && !!canvas.getContext; }; /* var hasFlash = function(){ var flash = navigator.plugins && navigator.plugins['Shockwave Flash']; try { flash = flash ? flash.description : new ActiveXObject('ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch (x){ } return flash && flash.match(/\d+/) >= 9; }; */ var MODE = hasCanvas() ? Canvas : /*hasFlash() ? Flash :*/ VML; exports.Surface = MODE.Surface; exports.Path = MODE.Path; exports.Shape = MODE.Shape; exports.Group = MODE.Group; exports.ClippingRectangle = MODE.ClippingRectangle; exports.Text = MODE.Text; require('./current').setCurrent(exports);
var VML = require('./vml'); var Canvas = require('./canvas'); var Base = require('./canvas/base'); //var Flash = require('./flash'); /* var hasFlash = function(){ var flash = navigator.plugins && navigator.plugins['Shockwave Flash']; try { flash = flash ? flash.description : new ActiveXObject('ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch (x){ } return flash && flash.match(/\d+/) >= 9; }; */ var MODE = Base._genericContext ? Canvas : /*hasFlash() ? Flash :*/ VML; exports.Surface = MODE.Surface; exports.Path = MODE.Path; exports.Shape = MODE.Shape; exports.Group = MODE.Group; exports.ClippingRectangle = MODE.ClippingRectangle; exports.Text = MODE.Text; require('./current').setCurrent(exports);
Use an existing check for canvas capabilities
Use an existing check for canvas capabilities This results in better compatability with jsdom, allows usage in newer Jest.
JavaScript
mit
sebmarkbage/art,sebmarkbage/art
b9b4fe4916b07ddffbdb05f781dc5ba3a32812a3
test/karma.conf.js
test/karma.conf.js
module.exports = function(config){ config.set({ basePath : '../', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/js/**/*.js', 'test/unit/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['PhantomJS'], hostname: process.env.IP, port: process.env.PORT, plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-phantomjs-launcher' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' }, }); };
module.exports = function(config){ config.set({ basePath : '../', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/js/**/*.js', 'test/unit/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['PhantomJS'], hostname: process.env.IP || 'localhost', port: process.env.PORT || '9876', plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-phantomjs-launcher' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' }, }); };
Set defaults for karma server
Set defaults for karma server
JavaScript
mit
double16/switchmin-ng,double16/switchmin-ng