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
a8994cdafba3a7f550ea5507530a06a056313dd2
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); finishedLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); } $('a.close').click(function() { var qqq = $(this).closest('.modal'); $(qqq).removeClass('active'); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); }
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
JavaScript
mit
fma2/nyc-high-school-programs,fma2/nyc-high-school-programs
6da644a00f47a7bf6a238ebed701d8b8677316b9
app/assets/javascripts/rating_form.js
app/assets/javascripts/rating_form.js
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.trigger('reset'); $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
Refactor rating jquery to clear rating form on submit
Refactor rating jquery to clear rating form on submit
JavaScript
mit
AliasHendrickson/progress,AliasHendrickson/progress,AliasHendrickson/progress
c6bf12e83cdf792c986b3fc4348a0165fe569e8a
frontend/src/Lists/ListsView.js
frontend/src/Lists/ListsView.js
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <ListsContainer> {lists.map(list => <List key={list.id} list={list} user={user} />)} <Notes /> {user.isAdmin && <CreateList />} </ListsContainer> </ColumnContainer> ); } } const ListsContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <MainContainer> <ListContainer width={(lists.length - 2) * 20}> {lists.map(list => <List key={list.id} list={list} user={user} />)} </ListContainer> {user.isAdmin && <CreateList />} <Notes /> </MainContainer> </ColumnContainer> ); } } const ListContainer = Row.extend` margin-left: -${props => props.width}em; `; const MainContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
Move lists to the left
Move lists to the left
JavaScript
mit
Tejpbit/talarlista,Tejpbit/talarlista,Tejpbit/talarlista
cf530df7cebd995e5742b4be488fa3c765d267e6
te-append.js
te-append.js
#!/usr/bin/env node 'use strict'; const program = require('commander'); const addLineNumbers = require('add-line-numbers'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); const line = '\n' + program.args; fs.appendFileSync(path, line); listAndRun();
#!/usr/bin/env node 'use strict'; const program = require('commander'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); const line = program.args; const file = fs.readFileSync(path, 'utf8'); var lines = []; if (file.length) { var lines = file.split('\n'); } lines.push(line); fs.writeFileSync(path, lines.join('\n')); listAndRun();
Make sure append doesn't create an empty line when the first line of code is added
Make sure append doesn't create an empty line when the first line of code is added
JavaScript
mit
gudnm/te
9c21194c68654e2152d70a28cc9261b13a2035a4
lib/api/middlewares/last-updated-time-layergroup.js
lib/api/middlewares/last-updated-time-layergroup.js
'use strict'; module.exports = function setLastUpdatedTimeToLayergroup () { return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) { const { mapConfigProvider, analysesResults } = res.locals; const layergroup = res.body; mapConfigProvider.createAffectedTables((err, affectedTables) => { if (err) { return next(err); } if (!affectedTables) { return next(); } var lastUpdateTime = affectedTables.getLastUpdatedAt(); lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime; // last update for layergroup cache buster layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime; layergroup.last_updated = new Date(lastUpdateTime).toISOString(); res.locals.cache_buster = lastUpdateTime; next(); }); }; }; function getLastUpdatedTime (analysesResults, lastUpdateTime) { if (!Array.isArray(analysesResults)) { return lastUpdateTime; } return analysesResults.reduce(function (lastUpdateTime, analysis) { return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) { var nodeUpdatedAtDate = node.getUpdatedAt(); var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0; return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime; }, lastUpdateTime); }, lastUpdateTime); }
'use strict'; module.exports = function setLastUpdatedTimeToLayergroup () { return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) { const { mapConfigProvider, analysesResults } = res.locals; const layergroup = res.body; mapConfigProvider.createAffectedTables((err, affectedTables) => { if (err) { return next(err); } if (!affectedTables) { res.locals.cache_buster = 0; layergroup.layergroupid = `${layergroup.layergroupid}:${res.locals.cache_buster}`; layergroup.last_updated = new Date(res.locals.cache_buster).toISOString(); return next(); } var lastUpdateTime = affectedTables.getLastUpdatedAt(); lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime; // last update for layergroup cache buster layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime; layergroup.last_updated = new Date(lastUpdateTime).toISOString(); res.locals.cache_buster = lastUpdateTime; next(); }); }; }; function getLastUpdatedTime (analysesResults, lastUpdateTime) { if (!Array.isArray(analysesResults)) { return lastUpdateTime; } return analysesResults.reduce(function (lastUpdateTime, analysis) { return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) { var nodeUpdatedAtDate = node.getUpdatedAt(); var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0; return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime; }, lastUpdateTime); }, lastUpdateTime); }
Set cache buster equal to 0 when there is no affected tables in the mapconfig
Set cache buster equal to 0 when there is no affected tables in the mapconfig
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
79f3d9a6a7ca614dce7fb0444d3799d9d55f198c
assets/js/theme/global/mobile-menu.js
assets/js/theme/global/mobile-menu.js
import $ from 'jquery'; export default function() { const $mobileMenuTrigger = $('[data-mobilemenu]'); const $header = $('.header'); const headerHeight = $('.header').outerHeight(); const $mobileMenu = $('#mobile-menu'); function mobileMenu() { $mobileMenuTrigger.on('click', toggleMobileMenu); } function toggleMobileMenu(e) { e.preventDefault(); calculateMobileMenuOffset(); targetMenuItemID = $mobileMenuTrigger.data('mobilemenu'); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); $mobileMenu.toggleClass('is-open').attr('aria-hidden', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); } function calculateMobileMenuOffset() { $mobileMenu.attr('style', (i, attr) => { return attr !== `top:${headerHeight}px` ? `top:${headerHeight}px` : 'top:auto'; }); $header.attr('style', (i, attr) => { return attr === 'height:100%' ? 'height:auto' : 'height:100%'; }); } if ($mobileMenuTrigger.length) { mobileMenu(); } }
import $ from 'jquery'; export default function() { const $mobileMenuTrigger = $('[data-mobilemenu]'); const $header = $('.header'); const headerHeight = $('.header').outerHeight(); const $mobileMenu = $('#mobile-menu'); function mobileMenu() { $mobileMenuTrigger.on('click', toggleMobileMenu); } function toggleMobileMenu(e) { e.preventDefault(); calculateMobileMenuOffset(); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); $mobileMenu.toggleClass('is-open').attr('aria-hidden', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); } function calculateMobileMenuOffset() { $mobileMenu.attr('style', (i, attr) => { return attr !== `top:${headerHeight}px` ? `top:${headerHeight}px` : 'top:auto'; }); $header.attr('style', (i, attr) => { return attr === 'height:100%' ? 'height:auto' : 'height:100%'; }); } if ($mobileMenuTrigger.length) { mobileMenu(); } }
Fix mobile hamburger menu contents not appearing
Fix mobile hamburger menu contents not appearing
JavaScript
mit
aaronrodier84/flukerfarms,juancho1/bauhaus,PascalZajac/cornerstone,bigcommerce/stencil,PeteyRev/ud-revamp,aaronrodier84/rouxbrands,bigcommerce/stencil,mcampa/cornerstone,rho1140/cornerstone,ovsokolov/dashconnect-bc,mcampa/cornerstone,PeteyRev/ud-revamp,juancho1/bauhaus,bc-annavu/stencil,aaronrodier84/rouxbrands,mcampa/cornerstone,ovsokolov/dashconnect-bc,bc-annavu/stencil,aaronrodier84/flukerfarms,aaronrodier84/rouxbrands,rho1140/cornerstone,caras-ey/BST,rho1140/cornerstone,caras-ey/BST,bigcommerce/stencil,juancho1/bauhaus,PascalZajac/cornerstone,PeteyRev/ud-revamp,bc-annavu/stencil,caras-ey/BST,aaronrodier84/flukerfarms,ovsokolov/dashconnect-bc,PascalZajac/cornerstone
9557e87a24a1b6d33cef2bce1231f9d9b2a35602
app/components/Auth/Auth.js
app/components/Auth/Auth.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import Controls from '../Controls'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <Controls /> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth);
Add control buttons to auth
Add control buttons to auth
JavaScript
mit
cdiezmoran/AlphaStage-2.0,cdiezmoran/AlphaStage-2.0
1e1e1e351b3d0a9f4f824e5392de8afea93d5ffe
src/components/posts_index.js
src/components/posts_index.js
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends React.Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> {post.title} </li> ); }); } render() { return ( <div className='posts-index'> <div className='text-xs-right'> <Link className='btn btn-primary' to='/posts/new'> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> { this.renderPosts() } </ul> </div> ) } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends React.Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> <Link to={`/posts/${post.id}`}> {post.title} </Link> </li> ); }); } render() { return ( <div className='posts-index'> <div className='text-xs-right'> <Link className='btn btn-primary' to='/posts/new'> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> { this.renderPosts() } </ul> </div> ) } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
Add link to link to each page
Add link to link to each page
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
a081e1554614ac92aebe31b0dd514a12484d4ece
app/lib/collections/posts.js
app/lib/collections/posts.js
Posts = new Mongo.Collection('posts'); Posts.allow({ insert: function(userId, doc) { // only allow posting if you are logged in return !! userId; } });
Posts = new Mongo.Collection('posts'); Meteor.methods({ postInsert: function(postAttributes) { check(Meteor.userId(), String); check(postAttributes, { title: String, url: String }); var user = Meteor.user(); var post = _.extend(postAttributes, { userId: user._id, author: user.username, submitted: new Date() }); var postId = Posts.insert(post); return { _id: postId }; } });
Use Meteor.methods to set up post (including user)
Use Meteor.methods to set up post (including user)
JavaScript
mit
drainpip/music-management-system,drainpip/music-management-system
fbae2755bb25ef803cd3508448cb1646868a6618
test/mqtt.js
test/mqtt.js
/** * Testing includes */ var should = require('should'); /** * Unit under test */ var mqtt = require('../lib/mqtt'); describe('mqtt', function() { describe('#createClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); }); describe('#createSecureClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); it('should throw on incorrect args'); }); describe('#createServer', function() { it('should return an MqttServer', function() { var s = mqtt.createServer(); s.should.be.instanceOf(mqtt.MqttServer); }); }); describe('#createSecureServer', function() { it('should return an MqttSecureServer', function() { var s = mqtt.createSecureServer( __dirname + '/helpers/private-key.pem', __dirname + '/helpers/public-cert.pem' ); s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); });
/** * Testing includes */ var should = require('should'); /** * Unit under test */ var mqtt = require('../lib/mqtt'); describe('mqtt', function() { describe('#createClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); }); describe('#createSecureClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); it('should throw on incorrect args'); }); describe('#createServer', function() { it('should return an MqttServer', function() { var s = mqtt.createServer(); s.should.be.instanceOf(mqtt.MqttServer); }); }); describe('#createSecureServer', function() { it('should return an MqttSecureServer', function() { var s = mqtt.createSecureServer( __dirname + '/helpers/private-key.pem', __dirname + '/helpers/public-cert.pem' ); s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); describe('#createConnection', function() { it('should return an MqttConnection', function() { var c = mqtt.createConnection(); c.should.be.instanceOf(mqtt.MqttConnection); }); }); });
Add test for MqttConnection creation
Add test for MqttConnection creation
JavaScript
mit
itavy/MQTT.js,bqevin/MQTT.js,AdySan/MQTT.js,mcanthony/MQTT.js,yunba/MQTT.js,jaambee/MQTT.js,daliworks/MQTT.js,jdiamond/MQTT.js,wesley1001/MQTT.js,authere/MQTT.js,RangerMauve/MQTT.js,1248/MQTT.js
41db6cf165dd083d3b284c961c128db609fcad81
src/extend/getConnectivityMatrix.js
src/extend/getConnectivityMatrix.js
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options={}) { var { sdt, mass } = options; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nbAtoms; i++) { result[i]=new Array(nbAtoms).fill(0); result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1; } for (var i=0; i<nbAtoms; i++) { for (var j=0; j<this.getAllConnAtoms(i); j++) { result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1; } } return result; }
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options) { var options = options || {}; var sdt=options.sdt; var mass=options.mass; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nbAtoms; i++) { result[i]=new Array(nbAtoms).fill(0); result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1; } for (var i=0; i<nbAtoms; i++) { for (var j=0; j<this.getAllConnAtoms(i); j++) { result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1; } } return result; }
Make it compatible with node 4.0
Make it compatible with node 4.0
JavaScript
bsd-3-clause
cheminfo-js/openchemlib-extended
94bc6236e23440d4f3958e601d0ab880b17d09de
public/js/book-app/components/book-app.component.js
public/js/book-app/components/book-app.component.js
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book" class="nav-click">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
Add New Class To Link
Add New Class To Link
JavaScript
mit
fejs-levelup/angular-bookshelf,fejs-levelup/angular-bookshelf
c8b6d8adb8ae1dea1148416acfdfb99502ce281c
app/assets/javascripts/init.js
app/assets/javascripts/init.js
window.atthemovies = { init: function() { var body = document.querySelectorAll("body")[0]; var jsController = body.getAttribute("data-js-controller"); var jsAction = body.getAttribute("data-js-action"); this.pageJS("atthemovies." + jsController + ".init", window); this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, pageJS: function(functionName, context) { var namespaces = functionName.split("."); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; } else { return null; } } if(typeof context[func] === "function") { return context[func].apply(context, null); } else { return null; } } }
window.atthemovies = { init: function() { var body = document.querySelectorAll("body")[0]; var jsController = body.getAttribute("data-js-controller"); var jsAction = body.getAttribute("data-js-action"); this.pageJS("atthemovies." + jsController + ".init", window); this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, // pass a string to call a namespaced function that may not exist pageJS: function(functionString, context) { var namespaces = functionString.split("."); var functionName = namespaces.pop(); // recursively loop into existing namespaces, else return harmlessly for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; } else { return null; } } // call the function if it exists in this context, else return harmlessly if(typeof context[functionName] === "function") { return context[functionName].apply(context, null); } else { return null; } } }
Tidy up JS, add commentary
Tidy up JS, add commentary
JavaScript
agpl-3.0
andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies
d3017cbcd542cc5c310d23c0bd478eae10ceef32
src/modules/ajax/retryAjax.js
src/modules/ajax/retryAjax.js
function doAjax(options, retries, dfr) { $.ajax(options).pipe(function(data) {dfr.resolve(data);}, function(jqXhr) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { dfr.reject(jqXhr); } }); } export default function retryAjax(options) { var dfr = $.Deferred(); doAjax(options, 10, dfr); return dfr; }
function doAjax(options, retries, dfr) { $.ajax(options).pipe(function(data, textStatus, jqXHR) { dfr.resolve(data, textStatus, jqXHR); }, function(jqXhr, textStatus, errorThrown) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { dfr.reject(jqXhr, textStatus, errorThrown); } }); } export default function retryAjax(options) { var dfr = $.Deferred(); doAjax(options, 10, dfr); return dfr; }
Return all arguments from AJAX
Return all arguments from AJAX
JavaScript
mit
fallenswordhelper/fallenswordhelper,fallenswordhelper/fallenswordhelper
84c100bbd0fb6749fdcef577690d85beb7aebd34
Gruntfile.js
Gruntfile.js
/* * Copyright 2013, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Zeno Rocha <zno.rocha@gmail.com> * @author Eduardo Lundgren <zno.rocha@gmail.com> */ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-jsbeautifier'); grunt.initConfig({ jsbeautifier: { files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'], options: { config: '.jsbeautifyrc' } } }); grunt.registerTask('format', ['jsbeautifier']); };
/* * Copyright 2013, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Zeno Rocha <zno.rocha@gmail.com> * @author Eduardo Lundgren <zno.rocha@gmail.com> */ module.exports = function(grunt) { grunt.initConfig({ jsbeautifier: { files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'], options: { config: '.jsbeautifyrc' } }, jshint: { options: grunt.file.readJSON('.jshintrc'), gruntfile: 'Gruntfile.js', files: { src: [ 'bin/*.js', 'lib/**/*.js' ] }, test: { options: { globals: { describe: true, it: true, beforeEach: true, afterEach: true, before: true, after: true } }, src: 'test/**/*.js' } }, } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-jsbeautifier'); grunt.registerTask('format', ['jsbeautifier']); };
Add jshint as grunt task
Add jshint as grunt task
JavaScript
bsd-3-clause
henvic/gh,TomzxForks/gh,modulexcite/gh,oouyang/gh,oouyang/gh,TomzxForks/gh,tomzx/gh,dustinryerson/gh,modulexcite/gh,henvic/gh,tomzx/gh,dustinryerson/gh
2818b0138520fbb0e9702cddef9e5d121b8f5ad1
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON( 'package.json' ), env: { casper: { BASEURL: "http://www.google.com", PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:./node_modules/.bin", PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs" } }, casperjs: { options: { includes: ['includes/include1.js'], test: true }, files: ['tests/**/*.js'] } }); // casperJS Frontend tests grunt.loadNpmTasks( 'grunt-casperjs' ); grunt.loadNpmTasks( 'grunt-env' ); // grunt for Frontend testing grunt.registerTask('default', [ 'env:casper', 'casperjs']); };
module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON( 'package.json' ), env: { casper: { BASEURL: "http://www.google.com", PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs" } }, casperjs: { options: { includes: ['includes/include1.js'], test: true }, files: ['tests/**/*.js'] } }); // casperJS Frontend tests grunt.loadNpmTasks( 'grunt-casperjs' ); grunt.loadNpmTasks( 'grunt-env' ); grunt.registerTask('extendPATH', 'Add the npm bin dir to PATH', function() { var pathDelimiter = ':'; var extPath = 'node_modules/.bin'; var pathArray = process.env.PATH.split( pathDelimiter ); pathArray.unshift( extPath ); process.env.PATH = pathArray.join( pathDelimiter ); grunt.log.writeln('Extending PATH to be ' + process.env.PATH); }); // grunt for Frontend testing grunt.registerTask('default', [ 'env:casper', 'extendPATH', 'casperjs']); };
Extend the PATH env var instead of replacing it
Extend the PATH env var instead of replacing it
JavaScript
mit
smlgbl/grunt-casperjs-extra
b68b04de0eec208ca389f93b271a52b3db5b8ed7
Tester/src/Tester.js
Tester/src/Tester.js
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */ "use strict"; import {spawn} from 'child_process'; const EXPOSE_TEST_SCRIPT = './scripts/analyse'; class Tester { constructor(file) { this.file = file; this.out = ""; } build(done) { let env = process.env; env.EXPOSE_EXPECTED_PC = this.file.expectPaths; let prc = spawn(EXPOSE_TEST_SCRIPT, [this.file.path], { env: env }); prc.stdout.setEncoding('utf8'); prc.stderr.setEncoding('utf8'); prc.stdout.on('data', data => this.out += data.toString()); prc.stderr.on('data', data => this.out += data.toString()); prc.on('close', code => done(code)); } } export default Tester;
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */ "use strict"; import {spawn} from 'child_process'; const EXPOSE_TEST_SCRIPT = './scripts/analyse'; class Tester { constructor(file) { this.file = file; this.out = ""; } build(done) { let env = process.env; env.EXPOSE_EXPECTED_PC = this.file.expectPaths; let prc = spawn(EXPOSE_TEST_SCRIPT, [this.file.path], { env: env }); prc.stdout.setEncoding('utf8'); prc.stderr.setEncoding('utf8'); prc.stdout.on('data', data => this.out += data.toString()); prc.stderr.on('data', data => this.out += data.toString()); const SECOND = 1000; const TIME_WARNING = 30; let longRunningMessage = setTimeout(() => console.log(`\rTEST WARNING: Test case ${this.file.path} is taking an excessive amount of time to complete (over ${TIME_WARNING}s)`), TIME_WARNING * SECOND); prc.on('close', code => { clearTimeout(longRunningMessage); done(code) }); } } export default Tester;
Print warnings when tests are taking ages so we can see which ones it is
Print warnings when tests are taking ages so we can see which ones it is
JavaScript
mit
ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE
af38d84173285c9ee1203a4cb468a068ae15e2d7
src/scripts/content/visualstudio.js
src/scripts/content/visualstudio.js
/*jslint indent: 2, plusplus: true */ /*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */ 'use strict'; // Individual Work Item & Backlog page togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () { var link, description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value, project = $('.menu-item.l1-navigation-text.drop-visible .text').textContent.trim(), container = $('.work-item-form-header-controls-container'), vs_activeClassContent = $('.hub-list .menu-item.currently-selected').textContent.trim(); link = togglbutton.createTimerLink({ className: 'visual-studio-online', description: description, projectName: project }); if (vs_activeClassContent === "Work Items*" || vs_activeClassContent === "Backlogs") { container.appendChild(link); } });
/*jslint indent: 2, plusplus: true */ /*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */ 'use strict'; // Individual Work Item & Backlog page togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () { var link, description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value, project = $('.tfs-selector span').innerText, container = $('.work-item-form-header-controls-container'), vs_activeClassContent = $('.commandbar.header-bottom > .commandbar-item > .displayed').innerText; link = togglbutton.createTimerLink({ className: 'visual-studio-online', description: description, projectName: project }); if (vs_activeClassContent === "Work Items" || vs_activeClassContent === "Backlogs") { container.appendChild(link); } });
Change VSTS integration for markup change
Change VSTS integration for markup change
JavaScript
bsd-3-clause
glensc/toggl-button,glensc/toggl-button,glensc/toggl-button
d4ca275b1229942dca73b4c4ed27a50f893dd6c9
src/touch-action.js
src/touch-action.js
(function() { function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ { rule: 'none', selectors: [ 'none', 'user' ] }, 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'scroll', 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r); } else { styles += r.selectors.map(selector) + rule(r.rule); } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); })();
(function() { function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ { rule: 'none', selectors: [ 'none', 'user' ] }, 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'scroll', 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r); } else { styles += r.selectors.map(selector) + rule(r.rule); } }); var el = document.createElement('style'); el.textContent = styles; // Use querySelector instead of document.head to ensure that in // ShadowDOM Polyfill that we have a wrapped head to append to. var h = document.querySelector('head'); // document.write + document.head.appendChild = crazytown // use insertBefore instead for correctness in ShadowDOM Polyfill h.insertBefore(el, h.firstChild); })();
Fix inserting touch action stylesheet for Shadow DOM Polyfill
Fix inserting touch action stylesheet for Shadow DOM Polyfill
JavaScript
bsd-3-clause
roblarsen/pointer-events.js
e0a5f7e093df4ec140a6cc7828633bb6949e0475
client/models/areaOfStudy.js
client/models/areaOfStudy.js
var _ = require('lodash'); var React = require('react'); var RequirementSet = require("./requirementSet"); var AreaOfStudy = React.createClass({ render: function() { console.log('area-of-study render') var areaDetails = []//getAreaOfStudy(this.props.name, this.props.type); var requirementSets = _.map(areaDetails.sets, function(reqset) { return RequirementSet( {key:reqset.description, name: reqset.description, needs: reqset.needs, count: reqset.count, requirements: reqset.reqs, courses: this.props.courses}); }, this); return React.DOM.article( {id:areaDetails.id, className:"area-of-study"}, React.DOM.details(null, React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)), requirementSets ) ); } }); module.exports = AreaOfStudy
var _ = require('lodash'); var React = require('react'); var RequirementSet = require("./requirementSet"); var AreaOfStudy = React.createClass({ render: function() { console.log('area-of-study render') var areaDetails = this.props;//getAreaOfStudy(this.props.name, this.props.type); var requirementSets = _.map(areaDetails.sets, function(reqset) { return RequirementSet({ key:reqset.description, name: reqset.description, needs: reqset.needs, count: reqset.count, requirements: reqset.reqs, courses: this.props.courses }); }, this); return React.DOM.article( {id:areaDetails.id, className:"area-of-study"}, React.DOM.details(null, React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)), requirementSets ) ); } }); module.exports = AreaOfStudy
Clean up the area of study headings
Clean up the area of study headings
JavaScript
agpl-3.0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
c40d33e07a2e835f67bbe10e0bad9ceb66bbbf67
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const WebpackNotifierPlugin = require('webpack-notifier'); const styleLintPlugin = require('stylelint-webpack-plugin'); const autoprefixer = require('autoprefixer'); const env = process.env.NODE_ENV; module.exports = { devtool: env === 'production' ? 'source-map' : 'eval', entry: './src', output: { path: path.join(__dirname, 'dist'), filename: 'app.js', publicPath: '/', }, plugins: env === 'production' ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { // dead_code: true, }, }), ] : [ new styleLintPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new WebpackNotifierPlugin({ title: 'Next-gen Build' }), ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' }, { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' }, ], // noParse: /babel/, }, postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], };
const path = require('path'); const webpack = require('webpack'); const WebpackNotifierPlugin = require('webpack-notifier'); const styleLintPlugin = require('stylelint-webpack-plugin'); const env = process.env.NODE_ENV; module.exports = { devtool: env === 'production' ? 'source-map' : 'eval', entry: './src', output: { path: path.join(__dirname, 'dist'), filename: 'app.js', }, plugins: env === 'production' ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin() ] : [ new styleLintPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new WebpackNotifierPlugin({ title: 'Next-gen Build' }), ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' }, { test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' }, ], }, };
Simplify webpack, unsuccessfull at fixing sourcemap output
Simplify webpack, unsuccessfull at fixing sourcemap output
JavaScript
mit
nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen
a7a6a8b5ea4a82660bb0ac7ed290e3d7a6b5c89b
src/store/checkout-store.js
src/store/checkout-store.js
import { Store } from 'consus-core/flux'; import StudentStore from './student-store'; let checkouts = []; let checkoutsByActionId = new Object(null); class CheckoutStore extends Store { getCheckoutByActionId(actionId) { return checkoutsByActionId[actionId]; } } const store = new CheckoutStore(); store.registerHandler('NEW_CHECKOUT', data => { let checkout = { studentId: data.studentId, itemAddresses: data.itemAddresses }; if (StudentStore.hasOverdueItem(data.studentId)){ throw new Error('Student has overdue item'); }else { checkoutsByActionId[data.actionId] = checkout; checkouts.push(checkout); } }); export default store;
import { Store } from 'consus-core/flux'; import StudentStore from './student-store'; import ItemStore from './item-store'; let checkouts = []; let checkoutsByActionId = new Object(null); class CheckoutStore extends Store { getCheckoutByActionId(actionId) { return checkoutsByActionId[actionId]; } } const store = new CheckoutStore(); store.registerHandler('NEW_CHECKOUT', data => { let checkout = { studentId: data.studentId, itemAddresses: data.itemAddresses }; data.itemAddresses.forEach(itemAddress => { if (ItemStore.getItemByAddress(itemAddress).status !== 'AVAILABLE') { throw new Error('An item in the cart is not available for checkout.'); } }); if (StudentStore.hasOverdueItem(data.studentId)) { throw new Error('Student has overdue item'); } else { checkoutsByActionId[data.actionId] = checkout; checkouts.push(checkout); } }); export default store;
Verify that the cart does not contain an unavailable item
Verify that the cart does not contain an unavailable item
JavaScript
unlicense
TheFourFifths/consus,TheFourFifths/consus
49b7b66ac4c3c40893e53e244a2cba7d915d235d
gulp/unit-tests.js
gulp/unit-tests.js
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var wiredep = require('wiredep'); gulp.task('test', function () { var bowerDeps = wiredep({ directory: 'app/bower_components', exclude: ['bootstrap-sass-official'], dependencies: true, devDependencies: true }); var testFiles = bowerDeps.js.concat([ 'app/scripts/**/*.js', 'test/unit/**/*.js' ]); return gulp.src(testFiles) .pipe($.karma({ configFile: 'test/karma.conf.js', action: 'run' })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }); });
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var wiredep = require('wiredep'); var bowerDeps = wiredep({ directory: 'app/bower_components', exclude: ['bootstrap-sass-official'], dependencies: true, devDependencies: true }); var testFiles = bowerDeps.js.concat([ 'app/scripts/**/*.js', 'test/unit/**/*.js' ]); gulp.task('test', function () { return gulp.src(testFiles) .pipe($.karma({ configFile: 'test/karma.conf.js', action: 'run' })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }); }); gulp.task('watch:test', function () { return gulp.src(testFiles) .pipe($.karma({ configFile: 'test/karma.conf.js', action: 'watch' })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }); });
Refactor unit tests, add watch task.
Refactor unit tests, add watch task.
JavaScript
mit
tvararu/angular-famous-playground
92e0b46c931e5aa3189db50ad758d5db00cbda9f
server/src/services/scripts/scripts-model.js
server/src/services/scripts/scripts-model.js
'use strict'; // scripts-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const Schema = mongoose.Schema; const scriptsSchema = new Schema({ text: { type: String, required: true }, createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now } }); const scriptsModel = mongoose.model('scripts', scriptsSchema); module.exports = scriptsModel;
'use strict'; // scripts-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const Schema = mongoose.Schema; const scriptsSchema = new Schema({ issue: { type: String, required: true }, title: { type: String, required: true }, text: { type: String, required: true }, createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now } }); const scriptsModel = mongoose.model('scripts', scriptsSchema); module.exports = scriptsModel;
Add script issue and title fields
Add script issue and title fields
JavaScript
mit
andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps
feabc4db34f6a1b15972f1c77306e83a53d61914
src/AsyncCreatable.js
src/AsyncCreatable.js
import React from 'react'; import Select from './Select'; function reduce(obj, props = {}){ return Object.keys(obj) .reduce((props, key) => { const value = obj[key]; if (value !== undefined) props[key] = value; return props; }, props); } const AsyncCreatable = React.createClass({ displayName: 'AsyncCreatableSelect', focus () { this.select.focus(); }, render () { return ( <Select.Async {...this.props}> {(asyncProps) => ( <Select.Creatable {...this.props}> {(creatableProps) => ( <Select {...reduce(asyncProps, reduce(creatableProps, {}))} onInputChange={(input) => { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); }} ref={(ref) => { this.select = ref; creatableProps.ref(ref); asyncProps.ref(ref); }} /> )} </Select.Creatable> )} </Select.Async> ); } }); module.exports = AsyncCreatable;
import React from 'react'; import createClass from 'create-react-class'; import Select from './Select'; function reduce(obj, props = {}){ return Object.keys(obj) .reduce((props, key) => { const value = obj[key]; if (value !== undefined) props[key] = value; return props; }, props); } const AsyncCreatable = createClass({ displayName: 'AsyncCreatableSelect', focus () { this.select.focus(); }, render () { return ( <Select.Async {...this.props}> {(asyncProps) => ( <Select.Creatable {...this.props}> {(creatableProps) => ( <Select {...reduce(asyncProps, reduce(creatableProps, {}))} onInputChange={(input) => { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); }} ref={(ref) => { this.select = ref; creatableProps.ref(ref); asyncProps.ref(ref); }} /> )} </Select.Creatable> )} </Select.Async> ); } }); module.exports = AsyncCreatable;
Migrate rest of src overto createClass pkg
Migrate rest of src overto createClass pkg
JavaScript
mit
submittable/react-select,serkanozer/react-select,OpenGov/react-select,mmpro/react-select,f-camacho/react-select,JedWatson/react-select,mobile5dev/react-select,JedWatson/react-select
3a1ea1dce763b04c46d2e13e39782d3249aa493f
example/src/main.js
example/src/main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Router from 'vue-router' import App from './App' import Home from './Home' import Eagle from 'eagle.js' import slideshows from './slideshows/slideshows.js' /* eslint-disable no-new */ Vue.use(Eagle) Vue.use(Router) var routes = [] slideshows.list.forEach(function (slideshow) { routes.push({ path: '/' + slideshow.infos.path, component: slideshow }) }) routes.push({ path: '*', component: Home }) routes.push({ path: '/', name: 'Home', component: Home }) console.log(routes) var router = new Router({ routes // hashbang: true // mode: 'history' }) new Vue({ el: '#app', router, template: '<App/>', components: { App } })
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Router from 'vue-router' import App from './App' import Home from './Home' import Eagle from 'eagle.js' import 'eagle.js/dist/eagle.css' import slideshows from './slideshows/slideshows.js' /* eslint-disable no-new */ Vue.use(Eagle) Vue.use(Router) var routes = [] slideshows.list.forEach(function (slideshow) { routes.push({ path: '/' + slideshow.infos.path, component: slideshow }) }) routes.push({ path: '*', component: Home }) routes.push({ path: '/', name: 'Home', component: Home }) console.log(routes) var router = new Router({ routes // hashbang: true // mode: 'history' }) new Vue({ el: '#app', router, template: '<App/>', components: { App } })
Load dist css file in example
Load dist css file in example
JavaScript
isc
Zulko/eagle.js
9bb7d328e9e64eead6af6bb0ff06dc147ceed2d0
js/responsive-overlay-menu.js
js/responsive-overlay-menu.js
$(document).ready(function () { $(".menu-btn a").click(function () { $(".overlay").fadeToggle(200); $(this).toggleClass('btn-open').toggleClass('btn-close'); }); $('.overlay').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); $('.menu a').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); });
(function ($) { $(".menu-btn a").click(function () { event.preventDefault(); $(".overlay").fadeToggle(200); $(this).toggleClass('btn-open').toggleClass('btn-close'); }); $('.overlay').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); $('.menu a').on('click', function () { event.preventDefault(); $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); }(jQuery));
Fix js to preventDefault and work more places
Fix js to preventDefault and work more places
JavaScript
mit
marioloncarek/responsive-overlay-menu,marioloncarek/responsive-overlay-menu
1e615e33dc380729cfcf7ab52177c6a38dcf8b36
lib/frame.js
lib/frame.js
/* requestFrame / cancelFrame */"use strict" var array = require("prime/es5/array") var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function(callback){ return setTimeout(callback, 1e3 / 60) } var callbacks = [] var iterator = function(time){ var split = callbacks.splice(0) for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date))) } var cancel = function(callback){ var io = array.indexOf(callbacks, callback) if (io > -1) callbacks.splice(io, 1) } var request = function(callback){ var i = callbacks.push(callback) if (i === 1) requestFrame(iterator) return function(){ cancel(callback) } } exports.request = request exports.cancel = cancel
/* requestFrame / cancelFrame */"use strict" var array = require("prime/es5/array") var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function(callback){ return setTimeout(callback, 1e3 / 60) } var callbacks = [] var iterator = function(time){ var split = callbacks.splice(0, callbacks.length) for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date))) } var cancel = function(callback){ var io = array.indexOf(callbacks, callback) if (io > -1) callbacks.splice(io, 1) } var request = function(callback){ var i = callbacks.push(callback) if (i === 1) requestFrame(iterator) return function(){ cancel(callback) } } exports.request = request exports.cancel = cancel
Fix requestFrame in IE, where splice requires the deleteCount argument.
Fix requestFrame in IE, where splice requires the deleteCount argument.
JavaScript
mit
dehenne/moofx,dehenne/moofx,kamicane/moofx
2ee1a0be3b01cc2a3cfbf8d6bc0f17f12dffbecc
eloquent_js/chapter04/ch04_ex04.js
eloquent_js/chapter04/ch04_ex04.js
function deepEqual(obj1, obj2) { if (typeof obj1 != "object" || obj1 == null || typeof obj2 != "object" || obj2 == null) return obj1 === obj2; let keys1 = Object.keys(obj1), keys2 = Object.keys(obj2); if (keys1.length != keys2.length) return false; for (let key of keys1) { if (!(keys2.includes(key) && deepEqual(obj1[key], obj2[key]))) return false; } return true; }
function deepEqual(a, b) { if (!(isObject(a) && isObject(b))) return a === b; for (let key of Object.keys(a)) { if (!(key in b)) return false; if (!deepEqual(a[key], b[key])) return false; } return true; } function isObject(a) { return typeof a == "object" && a != null; }
Add chapter 4, exercise 4
Add chapter 4, exercise 4
JavaScript
mit
bewuethr/ctci
1ab6ab7f1e72bad5f39c55110ba65991f23c9df8
examples/ruleset.js
examples/ruleset.js
var EchoRule = require('../lib/rules/echo.js'), Heartbeat = require('../lib/rules/heartbeat.js') ; var rules = []; rules.push(new EchoRule()); rules.push(new Heartbeat()); module.exports = rules;
var EchoRule = require('../lib/rules/echo.js'), Heartbeat = require('../lib/rules/heartbeat.js'), LoadAverage = require('../lib/rules/load-average.js') ; var rules = []; rules.push(new EchoRule()); rules.push(new Heartbeat()); rules.push(new LoadAverage({ warn: { 1: 1.5, 5: 0.9, 15: 0.7 }, critical: { 1: 1.5, 5: 1.5, 15: 1.5 } })); module.exports = rules;
Add the `LoadAverage` rule to the example
Add the `LoadAverage` rule to the example
JavaScript
isc
ceejbot/numbat-analyzer,npm/numbat-analyzer,numbat-metrics/numbat-analyzer
36b78042d3f5d38bb7ca96adb6cb1c0ae40deb49
main.js
main.js
var electron = require('electron'); // Module to control application life. var process = require('process'); const {app} = electron; const {BrowserWindow} = electron; let win; // Ensure that our win isn't garbage collected app.on('ready', function() { // Create the browser window. if (process.platform == 'win32') win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false}); else win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false}); // Load the main interface win.loadURL('file://' + __dirname + '/index.html'); // Uncomment this line to open the DevTools upon launch. //win.webContents.openDevTools({'mode':'undocked'}); win.on('closed', function() { // Dereference the window object so our app exits win = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function() { app.quit(); });
var electron = require('electron'); // Module to control application life. var process = require('process'); const {app} = electron; const {BrowserWindow} = electron; let win; // Ensure that our win isn't garbage collected app.on('ready', function() { // Create the browser window. if (process.platform == 'win32') win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false}); else win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false}); // Load the main interface win.loadURL('file://' + __dirname + '/index.html'); // Uncomment this line to open the DevTools upon launch. //win.webContents.openDevTools({'mode':'undocked'}); //Disable the menubar for dev versions win.setMenu(null); win.on('closed', function() { // Dereference the window object so our app exits win = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function() { app.quit(); });
Disable the menubar when running from source
Disable the menubar when running from source
JavaScript
mit
NoahAndrews/qmk_firmware_flasher,NoahAndrews/qmk_firmware_flasher,NoahAndrews/qmk_firmware_flasher
e8f93882daad04d6a74c864ac2c32d301c199254
lib/index.js
lib/index.js
var browserify = require('browserify-middleware') var babelify = require('babelify') module.exports = function (entries, brOptions, baOptions) { brOptions = brOptions || {} brOptions.transform = brOptions.transform || [] baOptions = baOptions || {} baOptions.stage = baOptions.stage || 1 brOptions.transform.unshift(babelify.configure(baOptions)) return browserify(entries, brOptions) }
var browserify = require('browserify-middleware') var babelify = require('babelify') function babelifyMiddleware(entries, brOptions, baOptions) { brOptions = brOptions || {} brOptions.transform = brOptions.transform || [] baOptions = baOptions || {} baOptions.stage = baOptions.stage || 1 brOptions.transform.unshift(babelify.configure(baOptions)) return browserify(entries, brOptions) } babelifyMiddleware.browserifySettings = browserify.settings module.exports = babelifyMiddleware
Make browserify default settings accessible
Make browserify default settings accessible
JavaScript
mit
luisfarzati/express-babelify-middleware,luisfarzati/express-babelify-middleware
649c9c09c9a66e085b33346f5062976801543423
examples/routing/src/reducers/user.js
examples/routing/src/reducers/user.js
/* Define your initial state here. * * If you change the type from object to something else, do not forget to update * src/container/App.js accordingly. */ const initialState = {}; module.exports = function(state = initialState, action) { /* Keep the reducer clean - do not mutate the original state. */ //let nextState = Object.assign({}, state); switch(action.type) { /* case 'YOUR_ACTION': { // Modify next state depending on the action and return it return nextState; } break; */ default: { /* Return original state if no actions were consumed. */ return state; } } }
import {LOGIN} from '../actions/const'; /* Define your initial state here. * * If you change the type from object to something else, do not forget to update * src/container/App.js accordingly. */ const initialState = { login: false }; module.exports = function(state = initialState, action) { /* Keep the reducer clean - do not mutate the original state. */ let nextState = Object.assign({}, state); switch(action.type) { case LOGIN: { nextState.login = true; return nextState; } default: { /* Return original state if no actions were consumed. */ return state; } } }
Change login state When LOGIN action was triggered.
Change login state When LOGIN action was triggered.
JavaScript
mit
stylesuxx/generator-react-webpack-redux,stylesuxx/generator-react-webpack-redux
e3e031e4634522e0764a722ad37791c9913ce1cd
domStorage.js
domStorage.js
function DomStorage() { var cache = {}; function getFromCache(selector){ if(!cache[selector]){ cache[selector] = $(selector); } return cache[selector]; } function updateInCache(selector){ if(!cache[selector]){ throw new TypeError("The selector you want to update does not exist in cache"); } else{ cache[selector] = $(selector); } } function getCache(){ return cache; } function flushCache(){ cache = {}; } return { get:getFromCache, update:updateInCache, getCache:getCache, flush:flushCache }; }
function DomStorage() { var cache = {}; function getFromCache(selector){ if(!selector) throw new TypeError("Please provide a selector"); if(!cache[selector]){ cache[selector] = $(selector); } return cache[selector]; } function updateInCache(selector){ if(!selector) throw new TypeError("Please provide a selector"); if(!cache[selector]){ throw new TypeError("The selector you want to update does not exist in cache"); } else{ cache[selector] = $(selector); } } function getCache(){ return cache; } function flushCache(){ cache = {}; } return { get:getFromCache, update:updateInCache, getCache:getCache, flush:flushCache }; } class DomCache{ constructor{ } }
Check if a user has given a valid selector when trying to get or update
Check if a user has given a valid selector when trying to get or update
JavaScript
mit
kounelios13/Dom-Storage,kounelios13/Dom-Storage
e1ee7a46a12715ce5d8bcfc7bf3180a6b254f228
client/common/layout/layout.js
client/common/layout/layout.js
'use strict'; var _ = require('lodash'); // // Observe quicksearch focus to tweak icon style // N.wire.once('navigate.done', function () { $('.navbar-search .search-query') .focus(function () { $(this).next('div').addClass('focused'); }) .blur(function () { $(this).next('div').removeClass('focused'); }); }); // // Update "active" tab of the navbar_menu when moving to another page. // N.wire.on('navigate.done', function navbar_menu_change_active(target) { var apiPath = target.apiPath, tabs, active; function matchLengthOf(subject) { var index = 0 , length = Math.min(apiPath.length, subject.length); while (index < length && subject.charCodeAt(index) === apiPath.charCodeAt(index)) { index += 1; } return index; } tabs = $('#navbar_menu').find('[data-api-path]'); tabs.removeClass('active'); // Select the most specific tab - with the longest API path match. active = _.max(tabs, function (tab) { return matchLengthOf($(tab).attr('data-api-path')); }); $(active).addClass('active'); });
'use strict'; var _ = require('lodash'); // // Observe quicksearch focus to tweak icon style // N.wire.once('navigate.done', function () { $('.navbar-search .search-query') .focus(function () { $(this).next('div').addClass('focused'); }) .blur(function () { $(this).next('div').removeClass('focused'); }); }); // // Update "active" tab of the navbar_menu when moving to another page. // N.wire.on('navigate.done', function navbar_menu_change_active(target) { var targetPath = target.apiPath.split('.'), tabs, active; tabs = $('#navbar_menu').find('[data-api-path]'); tabs.removeClass('active'); // Select the most specific tab - with the longest API path match. active = _.max(tabs, function (tab) { var tabPath = $(tab).data('apiPath').split('.') , index = -1 , length = Math.min(tabPath.length, targetPath.length); do { index += 1; } while (index < length && tabPath[index] === targetPath[index]); return index; }); $(active).addClass('active'); });
Fix tab selection on the navbar.
Fix tab selection on the navbar. Split API paths by dots to prevent matching of the dots.
JavaScript
mit
nodeca/nodeca.core,nodeca/nodeca.core
fc1a61eb29f6cd38f1694fda155a8173432d1999
tasks/help/index.js
tasks/help/index.js
module.exports = function(target) { if (tasks[target]) console.log(tasks[target].help) else console.log("No help documentation exists for " + target + ".") }
var fs = require('fs') module.exports = function(target) { fs.readFile('doc/' + target + '.md', function(err, data) { if (err) console.log("No help documentation exists for " + target + ".") else console.log(data) }) }
Load markdown docs in help command
Load markdown docs in help command Signed-off-by: Nathan Stier <013f9af474b4ba6f842b41368c6f02c1ee9e9e08@gmail.com>
JavaScript
mit
YWebCA/ywca-cli
88a4ce42993665dba7eef5798334419954f55a67
lib/gulp-index-file-stream.js
lib/gulp-index-file-stream.js
var Readable = require('stream').Readable; var path = require('path-posix'); var util = require('util'); var File = require('vinyl'); // Because the index.html files in our site don't necessarily // come from individual files, it's easiest for us to just // create a stream that emits Vinyl File objects rather than // using gulp.src(). function IndexFileStream(indexStatic) { Readable.call(this, { objectMode: true }); this._baseDir = __dirname; this._indexStatic = indexStatic; this._urls = indexStatic.URLS.slice(); } util.inherits(IndexFileStream, Readable); IndexFileStream.prototype._read = function() { if (this._urls.length == 0) return this.push(null); var url = this._urls.pop(); var indexFile = path.join( this._baseDir, path.join.apply(path, url.split('/').slice(1, -1)), 'index.html' ); this.push(new File({ cwd: this._baseDir, base: this._baseDir, path: indexFile, contents: new Buffer(this._indexStatic.generate(url, { baseURL: path.relative(url, '/') })) })); }; module.exports = IndexFileStream;
var Readable = require('stream').Readable; var posixPath = require('path-posix'); var util = require('util'); var File = require('vinyl'); // Because the index.html files in our site don't necessarily // come from individual files, it's easiest for us to just // create a stream that emits Vinyl File objects rather than // using gulp.src(). function IndexFileStream(indexStatic) { Readable.call(this, { objectMode: true }); this._baseDir = __dirname; this._indexStatic = indexStatic; this._urls = indexStatic.URLS.slice(); } util.inherits(IndexFileStream, Readable); IndexFileStream.prototype._read = function() { if (this._urls.length == 0) return this.push(null); var url = this._urls.pop(); var indexFile = posixPath.join( this._baseDir, posixPath.join.apply(posixPath, url.split('/').slice(1, -1)), 'index.html' ); this.push(new File({ cwd: this._baseDir, base: this._baseDir, path: indexFile, contents: new Buffer(this._indexStatic.generate(url, { baseURL: posixPath.relative(url, '/') })) })); }; module.exports = IndexFileStream;
Change path name to posixPath
Change path name to posixPath
JavaScript
mpl-2.0
Pomax/teach.mozilla.org,fredericksilva/teach.webmaker.org,PaulaPaul/teach.mozilla.org,toolness/teach.webmaker.org,alicoding/teach.mozilla.org,AnthonyBobsin/teach.webmaker.org,cadecairos/teach.mozilla.org,fredericksilva/teach.webmaker.org,emmairwin/teach.webmaker.org,mozilla/teach.webmaker.org,ScottDowne/teach.webmaker.org,asdofindia/teach.webmaker.org,alicoding/teach.webmaker.org,Pomax/teach.webmaker.org,emmairwin/teach.webmaker.org,mmmavis/teach.webmaker.org,mozilla/learning.mozilla.org,mrinaljain/teach.webmaker.org,Pomax/teach.mozilla.org,mmmavis/teach.webmaker.org,alicoding/teach.webmaker.org,ScottDowne/teach.webmaker.org,mozilla/teach.mozilla.org,mmmavis/teach.mozilla.org,PaulaPaul/teach.mozilla.org,mozilla/teach.webmaker.org,mozilla/teach.mozilla.org,mmmavis/teach.mozilla.org,asdofindia/teach.webmaker.org,Pomax/teach.webmaker.org,toolness/teach.webmaker.org,alicoding/teach.mozilla.org,cadecairos/teach.mozilla.org,mrinaljain/teach.webmaker.org,AnthonyBobsin/teach.webmaker.org
d77f875ffaf501002c30c49ab7c433730a8fce8e
src/modules/lists/components/connector/jsomConnector.service.js
src/modules/lists/components/connector/jsomConnector.service.js
angular .module('ngSharepoint.Lists') .factory('JSOMConnector', function($q, $sp) { return ({ getLists: function() { return $q(function(resolve, reject) { var context = $sp.getContext(); var lists = context.get_web().get_lists(); context.load(lists); context.executeQueryAsync(function(sender, args) { var result = []; var listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = lists.get_current(); result.push(list); } resolve(result); }, reject); }); } }); });
angular .module('ngSharepoint.Lists') .factory('JSOMConnector', function($q, $sp) { return ({ getLists: function() { return $q(function(resolve, reject) { var context = $sp.getContext(); var lists = context.get_web().get_lists(); context.load(lists); context.executeQueryAsync(function() { var result = []; var listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = listEnumerator.get_current(); result.push(list); } resolve(result); }, reject); }); } }); });
Use enumerator instead of lists
Use enumerator instead of lists
JavaScript
apache-2.0
maxjoehnk/ngSharepoint
6e73dbf020236063f8db213f2459c4d56fa2f661
lib/components/Application.js
lib/components/Application.js
import React, { Component } from 'react' import firebase, { reference, signIn } from '../firebase'; import { pick, map, extend } from 'lodash'; import Input from './Input'; import MessageContainer from './MessageContainer'; // import Search from './Search'; // import Users from './Users'; export default class Application extends Component { constructor() { super(); this.state = { messages: [], } } // componentDidMount() { // firebase.database().ref('messages').on('value', (snapshot) => { // }); // } storeMessage(message) { firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() })); this.state.messages.push(Object.assign(message, { id: Date.now() })) this.setState({ messages: this.state.messages }) } render() { return ( <div className="application"> <header className="headerSection"> {/* <Search /> */} </header> <div className="messageSection"> <MessageContainer messages={this.state.messages}/> </div> <aside className="usersSection"> {/* <Users /> */} </aside> <div> <Input sendMessage={this.storeMessage.bind(this)}/> </div> </div> ) } }
import React, { Component } from 'react' import firebase, { reference, signIn } from '../firebase'; import { pick, map, extend } from 'lodash'; import Input from './Input'; import MessageContainer from './MessageContainer'; // import Search from './Search'; // import Users from './Users'; export default class Application extends Component { constructor() { super(); this.state = { messages: [], } } componentDidMount() { firebase.database().ref('messages').on('value', (snapshot) => { const itemsFromFirebase = this.createArrayFromFB(snapshot.val()); this.setState({ messages: itemsFromFirebase ? itemsFromFirebase : [] }) }); } createArrayFromFB(object) { const firebaseKeys = object ? Object.keys(object) : []; const messages = []; firebaseKeys.map((key) => { let singleMessage = object[key] singleMessage['firebaseId'] = key messages.push(singleMessage); }); return messages } storeMessage(message) { firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() })); this.state.messages.push(Object.assign(message, { id: Date.now() })) this.setState({ messages: this.state.messages }) } render() { return ( <div className="application"> <header className="headerSection"> {/* <Search /> */} </header> <div className="messageSection"> <MessageContainer messages={this.state.messages}/> </div> <aside className="usersSection"> {/* <Users /> */} </aside> <div> <Input sendMessage={this.storeMessage.bind(this)}/> </div> </div> ) } }
Add items to firebase and repopulate on page load or refresh
Add items to firebase and repopulate on page load or refresh
JavaScript
mit
mlimberg/shoot-the-breeze,mlimberg/shoot-the-breeze
521eed5e6a64f1bf28210d03372cdbb353bb019e
scripts/script.js
scripts/script.js
(function(document, MazeGenerator, MazePainter, MazeInteraction) { 'use strict'; // DOM Elements var canvas = document.getElementById('maze'); var bGenerate = document.getElementById('bGenerate'); var bSolve = document.getElementById('bSolve'); // Start painting loop MazePainter.startPainting(); bGenerate.addEventListener('click', function() { // Initialize modules MazeGenerator.init(canvas.width, canvas.height, 20); MazePainter.init(canvas, 20, '#fff', '#f00', '#000', '#0f0', '#0f0', '#0f0', '#00f'); MazeGenerator.generate(); MazeGenerator.selectEntry(); MazeGenerator.selectExit(); MazeInteraction.init(canvas, 20, MazeGenerator.getMaze()); MazeInteraction.startListeningUserEvents(); }); bSolve.addEventListener('click', function() { if (MazePainter.isMazePainted()) { MazeGenerator.solve(); } }); }(document, MazeGenerator, MazePainter, MazeInteraction));
(function(document, MazeGenerator, MazePainter, MazeInteraction) { 'use strict'; // DOM Elements var canvas = document.getElementById('maze'); var bGenerate = document.getElementById('bGenerate'); var bSolve = document.getElementById('bSolve'); // Initialization variables var cellSize = 20; var cellColor = '#fff'; var frontierColor = '#f00'; var wallColor = '#000'; var entryColor = '#0f0'; var exitColor = '#0f0'; var solutionColor = '#0f0'; var userSolutionColor = '#00f'; // Start painting loop MazePainter.startPainting(); bGenerate.addEventListener('click', function() { // Initialize modules MazeGenerator.init(canvas.width, canvas.height, cellSize); MazePainter.init(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor); MazeGenerator.generate(); MazeGenerator.selectEntry(); MazeGenerator.selectExit(); MazeInteraction.init(canvas, cellSize, MazeGenerator.getMaze()); MazeInteraction.startListeningUserEvents(); }); bSolve.addEventListener('click', function() { if (MazePainter.isMazePainted()) { MazeGenerator.solve(); } }); }(document, MazeGenerator, MazePainter, MazeInteraction));
Use variables to initialize the maze
Use variables to initialize the maze
JavaScript
mit
jghinestrosa/maze-generator,jghinestrosa/maze-generator
c3da45397839ff6e5857b6413471ca64fac99b54
src/article/models/Heading.js
src/article/models/Heading.js
import { TextNode, TEXT } from 'substance' export default class Heading extends TextNode {} Heading.schema = { type: 'heading', level: { type: 'number', default: 1 }, content: TEXT() }
import { TextNode, TEXT } from 'substance' import { RICH_TEXT_ANNOS, EXTENDED_FORMATTING, LINKS_AND_XREFS, INLINE_NODES } from './modelConstants' export default class Heading extends TextNode {} Heading.schema = { type: 'heading', level: { type: 'number', default: 1 }, content: TEXT(RICH_TEXT_ANNOS.concat(EXTENDED_FORMATTING).concat(LINKS_AND_XREFS).concat(INLINE_NODES).concat(['break'])) }
Allow annotations and line-breaks in headings.
Allow annotations and line-breaks in headings.
JavaScript
mit
substance/texture,substance/texture
ee3544448dc1755c99b10e0afe52d295deffbdd8
script/postinstall.js
script/postinstall.js
#!/usr/bin/env node var cp = require('child_process') var fs = require('fs') var path = require('path') var script = path.join(__dirname, 'postinstall') if (process.platform === 'win32') { script += '.cmd' } else { script += '.sh' } // Read + execute permission fs.chmodSync(script, fs.constants.S_IRUSR | fs.constants.S_IXUSR) fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR) fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR) fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), fs.constants.S_IRUSR | fs.constants.S_IXUSR) var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true }) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
#!/usr/bin/env node var cp = require('child_process') var fs = require('fs') var path = require('path') var script = path.join(__dirname, 'postinstall') if (process.platform === 'win32') { script += '.cmd' } else { script += '.sh' } // Make sure all the scripts have the necessary permissions when we execute them // (npm does not preserve permissions when publishing packages on Windows, // so this is especially needed to allow apm to be published successfully on Windows) fs.chmodSync(script, 0o755) fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), 0o755) fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), 0o755) fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), 0o755) var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true }) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
Mark all scripts as 0o755
Mark all scripts as 0o755 This gives execute permission for everyone even if Atom is installed as root: https://github.com/atom/atom/issues/19367
JavaScript
mit
atom/apm,atom/apm,atom/apm,atom/apm
36d7c61c7d6f7c6dc4e9bb9191f20890ab148e8c
lib/support/browser_script.js
lib/support/browser_script.js
'use strict'; let fs = require('fs'), path = require('path'), Promise = require('bluebird'), filters = require('./filters'); Promise.promisifyAll(fs); /* Find and parse any browser scripts in rootFolder. Returns a Promise that resolves to an array of scripts. Each script is represented by an object with the following keys: - default: true if script is bundled with Browsertime. - path: the path to the script file on disk - source: the javascript source */ function parseBrowserScripts(rootFolder, isDefault) { function toFullPath(filename) { return path.join(rootFolder, filename); } function fileToScriptObject(filepath) { return fs.readFileAsync(filepath, 'utf8') .then((contents) => { return { default: isDefault, path: filepath, source: contents }; }); } return fs.readdirAsync(rootFolder) .map(toFullPath) .filter(filters.onlyFiles) .filter(filters.onlyWithExtension('.js')) .map(fileToScriptObject); } module.exports = { parseBrowserScripts: parseBrowserScripts, defaultScripts: parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts')) };
'use strict'; let fs = require('fs'), path = require('path'), Promise = require('bluebird'), filters = require('./filters'); Promise.promisifyAll(fs); /* Find and parse any browser scripts in rootFolder. Returns a Promise that resolves to an array of scripts. Each script is represented by an object with the following keys: - default: true if script is bundled with Browsertime. - path: the path to the script file on disk - source: the javascript source */ function parseBrowserScripts(rootFolder, isDefault) { function toFullPath(filename) { return path.join(rootFolder, filename); } function fileToScriptObject(filepath) { return fs.readFileAsync(filepath, 'utf8') .then((contents) => { return { default: isDefault, path: filepath, source: contents }; }); } return fs.readdirAsync(rootFolder) .map(toFullPath) .filter(filters.onlyFiles) .filter(filters.onlyWithExtension('.js')) .map(fileToScriptObject); } module.exports = { parseBrowserScripts: parseBrowserScripts, get defaultScripts() { return parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts')); } };
Configure Bluebird before first use of Promise.
Configure Bluebird before first use of Promise. Turn browser_scripts#defaultScripts into a get property, so it's not executed when the file is being required. This to avoid: Error: cannot enable long stack traces after promises have been created
JavaScript
apache-2.0
sitespeedio/browsertime,tobli/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime
83d2edc294966aa1c5d29ef16ddf623f6983cce7
index.js
index.js
"use strict"; /** * Properties to prefix. */ var postcss = require("postcss"), props = [ "hyphens", "line-break", "text-align-last", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "word-break", // writing modes "writing-mode", "text-orientation", "text-combine-upright" ]; /** * PostCSS plugin to prefix ePub3 properties. * @param {Object} style */ function plugin(style) { style.eachDecl(function(decl) { if (decl.value) { if (props.indexOf(decl.prop) >= 0) { decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop})); } } }); } /* * ...and export for use... */ module.exports = { postcss: plugin, process: function(css, opts) { return postcss(plugin).process(css, opts).css; } };
"use strict"; /** * Properties to prefix. */ var postcss = require("postcss"), props = [ // text "hyphens", "line-break", "text-align-last", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "word-break", // writing modes "writing-mode", "text-orientation", "text-combine-upright", // text to speech "cue", "cue-before", "cue-after", "pause", "rest", "speak", "speak-as", "voice-family" ]; /** * PostCSS plugin to prefix ePub3 properties. * @param {Object} style */ function plugin(style) { style.eachDecl(function(decl) { if (decl.value) { if (props.indexOf(decl.prop) >= 0) { decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop})); } } }); } /* * ...and export for use... */ module.exports = { postcss: plugin, process: function(css, opts) { return postcss(plugin).process(css, opts).css; } };
Add speech prefixes - still required in 2012, so should be left in due to reader issues
Add speech prefixes - still required in 2012, so should be left in due to reader issues
JavaScript
mit
Rycochet/postcss-epub,antyakushev/postcss-epub
92b28424a9d10ded0ebf59ef2a044596d99627cd
index.js
index.js
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const webpackConfig = require('./webpack.config.local'); new WebpackDevServer(webpack(webpackConfig), { publicPath: '/dist/', hot: true, historyApiFallback: true }).listen(3000, 'localhost', (err) => { if (err) { console.log(err); } console.log(`Webpack dev server listening at localhost:3000`); });
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const args = process.argv; const webpackConfig = require(`./webpack.config.${args[2].substring(2)}`); new WebpackDevServer(webpack(webpackConfig), { publicPath: '/dist/', hot: true, historyApiFallback: true }).listen(3000, 'localhost', (err) => { if (err) { console.log(err); } console.log(`Webpack dev server listening at localhost:3000`); });
Add option to choose between local and npm
[server] Add option to choose between local and npm
JavaScript
mit
KleeGroup/focus-showcase
9579909492ac9d80cfec0d9c9858ce7d89760aa1
examples/flux-chat/js/app.js
examples/flux-chat/js/app.js
/** * This file is provided by Facebook for testing and evaluation purposes * only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @jsx React.DOM */ // This file bootstraps the entire application. var ChatApp = require('./components/ChatApp.react'); var ChatExampleData = require('./ChatExampleData'); var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils'); var React = require('react'); ChatExampleData.init(); // load example data into localstorage ChatWebAPIUtils.getAllMessages(); React.renderComponent( <ChatApp />, document.getElementById('react') );
/** * This file is provided by Facebook for testing and evaluation purposes * only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @jsx React.DOM */ // This file bootstraps the entire application. var ChatApp = require('./components/ChatApp.react'); var ChatExampleData = require('./ChatExampleData'); var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils'); var React = require('react'); window.React = React; // export for http://fb.me/react-devtools ChatExampleData.init(); // load example data into localstorage ChatWebAPIUtils.getAllMessages(); React.renderComponent( <ChatApp />, document.getElementById('react') );
Enable React devtools by exposing React (setting window.React)
Enable React devtools by exposing React (setting window.React)
JavaScript
bsd-3-clause
eclectriq/flux,ludiculous/flux,ayarulin/flux,nikhyl/flux,debbas/ChatV2,JanChw/flux,crsr/flux,keikun17/flux,jmandel/flux,gfogle/elm-todomvc,Chen-Han/flux,ephetic/flux,ayarulin/flux,superphung/flux,prabhash1785/flux,rstefek/flux,UIKit0/flux-1,Demian-Moschin/flux,avinnakota/flux,mircle/flux,viviancpy/flux,alexeybondarenko/flux,vl-lapikov/flux,cold-brew-coding/flux,bilboJ/flux,JanChw/flux,wandrejevic/flux,thebergamo/flux,gnoesiboe/flux,zshift/flux,vl-lapikov/flux,ludiculous/flux,oopchoi/flux,Binzzzz/flux,dingdingvsjj/flux,glitch100/flux,Eric-Vandenberg/flux,maximvl/flux,knrm/flux,kris1226/flux,viviancpy/flux,amoskyler/flux,MykolaBova/flux,jinkea/flux,maksymshtyria/flux,cjmanetta/flux,thadiggitystank/flux,yanarchy/flux,Zagorakiss/flux,zhanglingkang/flux,steveleec/flux,cgack/flux,tungmv7/flux,bilboJ/flux,jeremyhu9/flux,ayarulin/flux,rohannair/flux,bertomartin/flux,dmlinn/flux,prabhash1785/flux,pj8063/flux,noahlt/flux,lifebeyondfife/flux-todomvc,usufruct/flux,ksivam/flux,alemontree/flux,fauzan182/flux,hokennethk/flux,slapheadted/flux-nukebox,bartcharbon/flux,alexeygusak/flux,ataker/flux,zhanglingkang/flux,chenrui2014/flux,keikun17/flux,maksymshtyria/flux,Jonekee/flux,haruair/flux,birendra-ideas2it/flux,thewarpaint/flux,kiopl/flux,aaron-goshine/flux,jeremyhu9/flux,ShannonStoner/flux,MykolaBova/flux,danielchatfield/flux,kiopl/flux,fauzan182/flux,harrykiselev/flux,danielchatfield/flux,hoozi/flux,akhilxavierm/flux,pj8063/flux,crzidea/flux,chrismoulton/flux,DimitarRuskov/flux,andela-cijeomah/flux,alexeybondarenko/flux,JunyaOnishi/flux,stevemao/flux,jeffj/flux,bartcharbon/flux,tungmv7/flux,hanan198501/flux,justin3737/flux,gaurav1981/flux,sibinx7/flux,kwangkim/flux,rkho/flux,lilien1010/flux,haruair/flux,micahlmartin/flux,kwangkim/flux,rstefek/flux,alucas/flux,harrykiselev/flux,harrykiselev/flux,djfm/flux,andela-cijeomah/flux,thewarpaint/flux,cold-brew-coding/flux,chienchienchen/flux,garylgh/flux,runn1ng/flux,tinygrasshopper/flux,nvoron23/flux,jarl-alejandro/flux,mcanthony/flux,tcxq42aa/flux,kris1226/flux,bartcharbon/flux,crsr/flux,crzidea/flux,tungmv7/flux,jarl-alejandro/flux,dingdingvsjj/flux,noahlt/flux,latkins/flux,mandaltapesh/flux,keikun17/flux,jdholdren/flux,ShannonStoner/flux,crsgypin/flux,Chen-Han/flux,Eric-Vandenberg/flux,davidgbe/flux,chienchienchen/flux,jugend/flux,venkateshdaram434/flux,noahlt/flux,steveleec/flux,djfm/flux,gnoesiboe/flux,sahat/flux,prabhash1785/flux,james4388/flux,kangkot/flux,mzbac/flux,magus0219/flux,zhzenghui/flux,nvoron23/flux,baiwyc119/flux,siddhartharay007/flux,Eric-Vandenberg/flux,mandaltapesh/flux,mzbac/flux,RomanTsopin/flux,baijuachari/flux,chenckang/flux,crsgypin/flux,oopchoi/flux,rtfeldman/flux,Zagorakiss/flux,knrm/flux,gaurav1981/flux,Zagorakiss/flux,reinaldo13/flux,hoozi/flux,unidevel/flux,roshow/flux,RomanTsopin/flux,fauzan182/flux,lishengzxc/flux,gfogle/elm-todomvc,Aweary/flux,cgack/flux,ksivam/flux,cgack/flux,latkins/flux,rkho/flux,yanarchy/flux,ephetic/flux,gnoesiboe/flux,unidevel/flux,thewarpaint/flux,tom-mats/flux,soulcm/flux,bertomartin/flux,DimitarRuskov/flux,knrm/flux,lishengzxc/flux,chrismoulton/flux,avinnakota/flux,nikhyl/flux,gajus/flux,stevemao/flux,lgvalle/flux,latkins/flux,kaushik94/flux,YakovAvramenko/flux,tinygrasshopper/flux,magus0219/flux,Aweary/flux,DimitarRuskov/flux,tbutman/flux,nikhyl/flux,baiwyc119/flux,venkateshdaram434/flux,lgvalle/flux,georgetoothman/flux-todo,CedarLogic/flux,lifebeyondfife/flux-todomvc,rtfeldman/flux,alexeygusak/flux,Aweary/flux,doron2402/flux,thebergamo/flux,runn1ng/flux,yejodido/flux,ataker/flux,taylorhxu/flux,taylorhxu/flux,juliangamble/flux,lauramoore/flux,zshift/flux,usufruct/flux,gaurav1981/flux,briantopping/flux,aaron-goshine/flux,robhogfeldt-fron15/flux,lauramoore/flux,shunyitian/flux,mattvanhorn/flux,jonathanpeterwu/flux,amoskyler/flux,jarl-alejandro/flux,davidgbe/flux,songguangyu/flux,tcxq42aa/flux,gajus/flux,tom-mats/flux,albi34/flux,unidevel/flux,djfm/flux,doxiaodong/flux,nvoron23/flux,thadiggitystank/flux,hokennethk/flux,grandsong/flux,aecca/flux,wrrnwng/flux,birendra-ideas2it/flux,blazenko/flux,kaushik94/flux,lyip1992/flux,ruistime/flux,lifebeyondfife/flux-todomvc,dmlinn/flux,viviancpy/flux,lishengzxc/flux,baijuachari/flux,tcat/flux,james4388/flux,bilboJ/flux,UIKit0/flux-1,oopchoi/flux,crsgypin/flux,gold3bear/flux,maksymshtyria/flux,jmandel/flux,0rangeT1ger/flux,doron2402/flux,tom-mats/flux,0rangeT1ger/flux,lilien1010/flux,alexeybondarenko/flux,UIKit0/flux-1,dbenson24/flux,micahlmartin/flux,tcxq42aa/flux,tcat/flux,robhogfeldt-fron15/flux,superphung/flux,danielchatfield/flux,monkeyFeathers/flux,wrrnwng/flux,rachidmrad/flux,haruair/flux,vijayasingh523/flux,alemontree/flux,ruistime/flux,justin3737/flux,chikamichi/flux,jugend/flux,dbenson24/flux,gajus/flux,juliangamble/flux,alucas/flux,steveleec/flux,Binzzzz/flux,MjAbuz/flux,doxiaodong/flux,zshift/flux,aijiekj/flux,ruistime/flux,debbas/ChatV2,johan/flux,jinkea/flux,eclectriq/flux,icefoggy/flux,crzidea/flux,garylgh/flux,lgvalle/flux,reinaldo13/flux,kangkot/flux,topogigiovanni/flux,Chen-Han/flux,vijayasingh523/flux,rkho/flux,songguangyu/flux,mircle/flux,jonathanpeterwu/flux,zachwooddoughty/flux,slapheadted/flux-nukebox,Lhuihui/flux,hanan198501/flux,sibinx7/flux,chenckang/flux,v2018z/flux,alemontree/flux,rachidmrad/flux,debbas/ChatV2,gougouGet/flux,ephetic/flux,JunyaOnishi/flux,mcanthony/flux,siddhartharay007/flux,zhzenghui/flux,sahat/flux,v2018z/flux,micahlmartin/flux,CedarLogic/flux,juliangamble/flux,grandsong/flux,akhilxavierm/flux,jeffj/flux,YakovAvramenko/flux,LeeChSien/flux,kris1226/flux,maximvl/flux,soulcm/flux,albi34/flux,Lhuihui/flux,avinnakota/flux,icefoggy/flux,ataker/flux,lyip1992/flux,chikamichi/flux,zachwooddoughty/flux,johan/flux,rohannair/flux,shunyitian/flux,rtfeldman/flux,chenrui2014/flux,roshow/flux,topogigiovanni/flux,Jonekee/flux,gougouGet/flux,blazenko/flux,mattvanhorn/flux,LeeChSien/flux,monkeyFeathers/flux,tbutman/flux,wandrejevic/flux,chenckang/flux,georgetoothman/flux-todo,MjAbuz/flux,glitch100/flux,amoskyler/flux,slapheadted/flux-nukebox,jdholdren/flux,chienchienchen/flux,Demian-Moschin/flux,aijiekj/flux,yejodido/flux,tcat/flux,reinaldo13/flux,cjmanetta/flux,briantopping/flux,aecca/flux,gold3bear/flux,crsr/flux
5bc3d461c0837f1300baeb39c47062d15b2676d7
client/app/bundles/Index/containers/TableHeadCell.js
client/app/bundles/Index/containers/TableHeadCell.js
import { connect } from 'react-redux' import merge from 'lodash/merge' import clone from 'lodash/clone' import pickBy from 'lodash/pickBy' import { encode } from 'querystring' import TableHeadCell from '../components/TableHeadCell' const mapStateToProps = (state, ownProps) => { const { params, field } = ownProps const currentDirection = params.sort_direction const isCurrentSortField = ( params.sort_field == field.field && params.sort_model == field.model ) let linkParams = merge(clone(params), { sort_field: field.field, sort_model: field.model }) if (isCurrentSortField) { linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC' } let href = `/${ownProps.model}?${encode(pickBy(linkParams))}` const displayName = field.name.split('_').join(' ') return { href, isCurrentSortField, currentDirection, displayName, } } const mapDispatchToProps = (dispatch, ownProps) => ({}) export default connect(mapStateToProps, mapDispatchToProps)(TableHeadCell)
import { connect } from 'react-redux' import merge from 'lodash/merge' import clone from 'lodash/clone' import pickBy from 'lodash/pickBy' import { encode } from 'querystring' import TableHeadCell from '../components/TableHeadCell' const mapStateToProps = (state, ownProps) => { const { params, field } = ownProps const currentDirection = params.sort_direction const isCurrentSortField = ( params.sort_field == field.field && (field.relation == 'own' || params.sort_model == field.model) ) let linkParams = merge(clone(params), { sort_field: field.field, sort_model: (field.relation == 'own' ? null : field.model) }) if (isCurrentSortField) { linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC' } let href = `/${ownProps.model}?${encode(pickBy(linkParams))}` const displayName = field.name.split('_').join(' ') return { href, isCurrentSortField, currentDirection, displayName, } } const mapDispatchToProps = (dispatch, ownProps) => ({}) export default connect(mapStateToProps, mapDispatchToProps)(TableHeadCell)
Fix for broken sorting on own fields: remove sort_model from params if the field relation is own
Fix for broken sorting on own fields: remove sort_model from params if the field relation is own
JavaScript
mit
clarat-org/claradmin,clarat-org/claradmin,clarat-org/claradmin,clarat-org/claradmin
fb845792abc681eb600b9a17da11120c8064bd07
packages/strapi-plugin-users-permissions/config/layout.js
packages/strapi-plugin-users-permissions/config/layout.js
module.exports = { user: { actions: { create: 'User.create', // Use the User plugin's controller. update: 'User.update', destroy: 'User.destroy', deleteall: 'User.destroyAll', }, attributes: { username: { className: 'col-md-6' }, email: { className: 'col-md-6' }, provider: { className: 'd-none' }, resetPasswordToken: { className: 'd-none' }, role: { className: 'd-none' } } } };
module.exports = { user: { actions: { create: 'User.create', // Use the User plugin's controller. update: 'User.update', destroy: 'User.destroy', deleteall: 'User.destroyAll', }, attributes: { username: { className: 'col-md-6' }, email: { className: 'col-md-6' }, resetPasswordToken: { className: 'd-none' }, role: { className: 'd-none' } } } };
Fix to allow provider to be shown in the content manager
Fix to allow provider to be shown in the content manager
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
0c2e09addecb2384efe3bc310c0afee033586d86
index.js
index.js
'use strict'; var execFile = require('child_process').execFile; module.exports = function (str, cb) { execFile('osascript', ['-e', str], function (err, stdout) { if (err) { cb(err); return; } cb(err, stdout.trim()); }); };
'use strict'; var execFile = require('child_process').execFile; module.exports = function (str, cb) { if (process.platform !== 'darwin') { throw new Error('Only OS X systems are supported'); } execFile('osascript', ['-e', str], function (err, stdout) { if (err) { cb(err); return; } cb(err, stdout.trim()); }); };
Throw error if used on another OS than OS X
Throw error if used on another OS than OS X
JavaScript
mit
sindresorhus/run-applescript
032243593b312553e384dc068255abc5aea77473
index.js
index.js
"use strict"; var util = require('util'); var minimist = require('minimist'); /** * Parse arguments and return command object * @param {array} argv Command line arguments * @param {object} opts Argument parsing options and commands * @return {object} Command object */ module.exports = function(argv, opts) { if (!argv) argv = process.argv.slice(2); opts = opts || {}; opts.commands = opts.commands || {}; opts.stopEarly = true; var global_args = minimist(argv, opts); var command = global_args._[0]; var options = opts.commands[command] || {}; var callback = options.callback || options.cb; if (opts.inheritCommon) { options = util._extend(opts, options); } var args = minimist(global_args._.slice(1), options); function execCommand() { if (typeof callback === 'function') { return callback.apply(null, [args].concat(arguments)); } return false; }; return { name: command, common: global_args, args: args, exec: execCommand, }; };
"use strict"; var util = require('util'); var minimist = require('minimist'); /** * Parse arguments and return command object * @param {array} argv Command line arguments * @param {object} opts Argument parsing options and commands * @return {object} Command object */ module.exports = function(argv, opts) { if (!argv) argv = process.argv.slice(2); opts = opts || {}; opts.commands = opts.commands || {}; opts.stopEarly = true; var global_args = minimist(argv, opts); var command = global_args._[0]; var options = opts.commands[command] || {}; var callback = options.callback || options.cb; if (opts.inheritCommon) { options = util._extend(opts, options); } var args = minimist(global_args._.slice(1), options); return { name: command, common: global_args, args: args, exec: callback && callback.bind(null, args), }; };
Use bind instead of intermediate function
Use bind instead of intermediate function Exec method is 'undefined' if no command callback were defined. Signed-off-by: Harri Kovalainen <2ecf1d4f49b9d136d53b819dc389c152487e9e18@gmail.com>
JavaScript
mit
hakovala/node-simpleton
d49e5b628ef3c352e6664ab290b831b68bd65e3b
notifications/SiteDownNotification.js
notifications/SiteDownNotification.js
"use strict"; var Mail = require('./channels/Mail'); var Console = require('./channels/Console'); class SiteDownNotification { constructor(site) { this.site = site; this.message = site.getAttribute('url') + ' is down!'; } toMail() { return new Mail().setBody(this.message); } toConsole() { return new Console().setBody(this.message); } via() { return ['mail', 'console']; } } module.exports = SiteDownNotification;
"use strict"; var Mail = require('./channels/Mail'); var Console = require('./channels/Console'); class SiteDownNotification { constructor(site) { this.site = site; this.message = site.getAttribute('url') + ' is down!'; } toMail() { return new Mail().setBody(this.message); } toConsole() { return new Console().setBody(this.message); } via() { return (this.site.notifications) ? this.site.notifications : ['console']; } } module.exports = SiteDownNotification;
Send notification based on the sites settings
Send notification based on the sites settings
JavaScript
mit
jonathandey/uptime-monitor,jonathandey/uptime-monitor
7c39d6c44216d85785e064c724f1b11ce0b46745
index.js
index.js
#!/usr/bin/env node var cli = require('cli').enable('version'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ 'append': ['a', 'append to the given FILEs, do not overwrite'], 'ignore-interrupts': ['i', 'ignore interrupt signals'], 'suppress': ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } function interceptInt () { if (!options['ignore-interrupts']) { process.exit(); } } process.on('SIGINT', interceptInt); cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
#!/usr/bin/env node var cli = require('cli').enable('version').setApp('./package.json'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ 'append': ['a', 'append to the given FILEs, do not overwrite'], 'ignore-interrupts': ['i', 'ignore interrupt signals'], 'suppress': ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } function interceptInt () { if (!options['ignore-interrupts']) { process.exit(); } } process.on('SIGINT', interceptInt); cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
Fix ntee -h/--help not showing right name and version and showing cli's ones instead
Fix ntee -h/--help not showing right name and version and showing cli's ones instead
JavaScript
mit
stefanmaric/ntee
cfe3214bc9f571c7e428c85dcd4fcb4845ad5832
index.js
index.js
module.exports = Storage function Storage () { if (!(this instanceof Storage)) return new Storage() this.chunks = [] } Storage.prototype.put = function (index, buf, cb) { this.chunks[index] = buf if (cb) process.nextTick(cb) } function nextTick (cb, err, val) { process.nextTick(function () { cb(err, val) }) } Storage.prototype.get = function (index, opts, cb) { if (typeof opts === 'function') return this.get(index, null, opts) var buf = this.chunks[index] if (!buf) return nextTick(cb, new Error('Chunk not found')) if (!opts) return nextTick(cb, null, buf) var offset = opts.offset || 0 var len = opts.length || (buf.length - offset) nextTick(cb, null, buf.slice(offset, len + offset)) }
module.exports = Storage function Storage (chunkLength) { if (!(this instanceof Storage)) return new Storage() this.chunks = [] this.chunkLength = Number(chunkLength) this.closed = false if (!this.chunkLength) throw new Error('First argument must be a chunk length') } Storage.prototype.put = function (index, buf, cb) { if (this.closed) return nextTick(cb, new Error('Storage is closed')) if (buf.length !== this.chunkLength) { return nextTick(cb, new Error('Chunk length must be ' + this.chunkLength)) } this.chunks[index] = buf if (cb) process.nextTick(cb) } Storage.prototype.get = function (index, opts, cb) { if (typeof opts === 'function') return this.get(index, null, opts) if (this.closed) return nextTick(cb, new Error('Storage is closed')) var buf = this.chunks[index] if (!buf) return nextTick(cb, new Error('Chunk not found')) if (!opts) return nextTick(cb, null, buf) var offset = opts.offset || 0 var len = opts.length || (buf.length - offset) nextTick(cb, null, buf.slice(offset, len + offset)) } Storage.prototype.close = Storage.prototype.destroy = function (cb) { if (this.closed) return nextTick(cb, new Error('Storage is closed')) this.closed = true this.chunks = null nextTick(cb, null) } function nextTick (cb, err, val) { process.nextTick(function () { if (cb) cb(err, val) }) }
Add close and destroy; force fixed chunk length
Add close and destroy; force fixed chunk length
JavaScript
mit
mafintosh/memory-chunk-store
eea34dcd016c2b497ff5af29c149d3e97530e566
index.js
index.js
'use strict'; var consecutiveSlash = /(:)?\/+/g; var endsWithExtension = /[^\/]*\.[^\/]+$/g; var fn = function(match, c) { return c ? '://' : '/'; }; var pppath = function(parts, filename) { if (typeof parts === 'string') { parts = [parts]; } if (filename && !endsWithExtension.test(parts[parts.length-1])) { parts.push(filename); } return parts.join('/').replace(consecutiveSlash, fn); }; module.exports = exports = pppath;
'use strict'; var consecutiveSlash = /(:)?\/+/g; var endsWithExtension = /[^\/]*\.[^\/]+$/g; var fn = function(match, c) { return c ? '://' : '/'; }; var pppath = function(parts, filename) { if (typeof parts === 'string') { parts = [parts]; } if (filename && parts[parts.length-1].search(endsWithExtension) === -1) { parts.push(filename); } return parts.join('/').replace(consecutiveSlash, fn); }; module.exports = exports = pppath;
Use `String.search` instead of `RegExp.test`
Use `String.search` instead of `RegExp.test`
JavaScript
mit
yuanqing/pppath
869ba7c3b24aa0d8b3d15481df4a7de5327a64e9
lib/white.js
lib/white.js
var generatePairs = function(string) { var pairs = []; string = string.toLowerCase(); for (var i = 0; i < string.length - 1; i++) { pair = string.substr(i, 2); if (!/\s/.test(pair)) { pairs.push(pair); } } return pairs; } var whiteSimilarity = function(string1, string2) { string1 = string1.toUpperCase() .replace(/[^A-Z]+/g, ''); string2 = string1.toUpperCase() .replace(/[^A-Z]+/g, ''); var pairs1 = generatePairs(string1); var pairs2 = generatePairs(string2); var union = pairs1.length + pairs2.length; var hitCount = 0; for (x in pairs1) { for (y in pairs2) { if (pairs1[x] == pairs2[y]) { hitCount++; } } } score = ((2.0 * hitCount) / union).toFixed(2); return score; } module.exports = whiteSimilarity;
var generatePairs = function(string) { superPairs = string.toUpperCase() .replace(/[^A-Z ]+/g, '') .split(/\s+/); superPairs = superPairs .map(function(word) { breaks = []; for (var i = 0; i < word.length - 1; i++) { breaks.push(word.slice(i, i + 2)); } return breaks; }); pairs = [].concat.apply([], superPairs); return pairs; } var whiteSimilarity = function(string1, string2) { var pairs1 = generatePairs(string1); var pairs2 = generatePairs(string2); var union = pairs1.length + pairs2.length; var hitCount = 0; for (x in pairs1) { for (y in pairs2) { if (pairs1[x] == pairs2[y]) { hitCount++; pairs2[y] = ''; } } } score = ((2.0 * hitCount) / union).toFixed(2); return score; } module.exports = whiteSimilarity;
Make pair generation extensible to multiple words
Make pair generation extensible to multiple words
JavaScript
mit
sanchitgera/Lingual
62c1b14f0e0da04c0952865a74ede42b21ae864b
index.js
index.js
module.exports = function (paths, ignores) { let result = [] let edge = String.prototype for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) { let ignore = ignores[i] if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) { edge = edge.endsWith } else { edge = edge.startsWith } for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) { let path = paths[j] if (!edge.call(path, ignore)) { result[result.length] = path } } } return result }
function startsWith (value, start) { return value.slice(0, start.length) === start } function endsWith (value, end) { return value.slice(value.length - end.length) === end } module.exports = function (paths, ignores) { let result = [] let edge for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) { let ignore = ignores[i] if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) { edge = endsWith } else { edge = startsWith } for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) { let path = paths[j] if (!edge(path, ignore)) { result[result.length] = path } } } return result }
Use startsWith and endsWith functions
Use startsWith and endsWith functions
JavaScript
mit
whaaaley/path-ignore
5b057575255fc56845c37bae3289da0a72fe93a4
src/routerViewPort.js
src/routerViewPort.js
import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating'; import {Injector, Inject} from 'di'; @TemplateDirective({selector: 'router-view-port'}) export class RouterViewPort { @Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs) constructor(viewFactory, viewPort, executionContext, attrs) { this.viewFactory = viewFactory; this.viewPort = viewPort; this.executionContext = executionContext; this.view = null; if ('router' in this.executionContext) { this.executionContext.router.registerViewPort(this, attrs.name); } } createComponentView(directive, providers){ return this.viewFactory.createComponentView({ component: directive, providers: providers, viewPort: this.viewPort }); } process(viewPortInstruction) { this.tryRemoveView(); this.view = viewPortInstruction.component; this.viewPort.append(this.view); } tryRemoveView() { if (this.view) { this.view.remove(); this.view = null; } } }
import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating'; import {Injector, Inject} from 'di'; @TemplateDirective({selector: 'router-view-port'}) export class RouterViewPort { @Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs) constructor(viewFactory, viewPort, executionContext, attrs) { this.viewFactory = viewFactory; this.viewPort = viewPort; this.executionContext = executionContext; this.view = null; if ('router' in this.executionContext) { this.executionContext.router.registerViewPort(this, attrs.name); } } createComponentView(directive, providers){ return this.viewFactory.createComponentView({ component: directive, providers: providers, viewPort: this.viewPort }); } process(viewPortInstruction) { this.tryRemoveView(); this.view = viewPortInstruction.component; this.view.appendTo(this.viewPort); } tryRemoveView() { if (this.view) { this.view.remove(); this.view = null; } } }
Update the newest templating API
chore(templating): Update the newest templating API
JavaScript
apache-2.0
shangyilim/router,JanPietrzyk/router,rakeshbhavsar/router,excellalabs/router,shangyilim/router,loomio/router,kyroskoh/router,angular/router,excellalabs/router,JanPietrzyk/router,kyroskoh/router,IgorMinar/router,AyogoHealth/router,rakeshbhavsar/router,AyogoHealth/router,shangyilim/router,IgorMinar/router,IgorMinar/router,loomio/router
02b11e3eef293f87a32bae4ff747dcf4f66d436b
index.js
index.js
var path = require('path'), servestatic = require('serve-static'); var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json')); module.exports = { setup: function (app, options) { options = options || {}; options.path = options.path || '/govuk-assets'; app.use(options.path, servestatic(path.join(basedir, './assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = options.path + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
var path = require('path'), servestatic = require('serve-static'); var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json')); module.exports = { setup: function (app, options) { options = options || {}; options.path = options.path || '/govuk-assets'; app.use(options.path, servestatic(path.join(basedir, './assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = req.baseUrl + options.path + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
Include req.baseUrl is asset path
Include req.baseUrl is asset path If app is namespaced under another route then this needs to be taken into account when importing assets
JavaScript
mit
UKHomeOffice/govuk-template-compiler,UKHomeOffice/govuk-template-compiler
288b361b388a23e4b4ea9aef10f659e5ba65a6ca
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select' };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select', contentFor: function(type /*, config */) { if (type === 'body-footer') { return `<div id="ember-power-select-wormhole"></div>` } } };
Add the wormhole destination in the {{content-for “body-footer”}}
Add the wormhole destination in the {{content-for “body-footer”}}
JavaScript
mit
cibernox/ember-power-select,Dremora/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,esbanarango/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,Dremora/ember-power-select
068ce6d6a58dceb64c32173c37483f821ae8c31e
index.js
index.js
'use strict'; var cheerio = require('cheerio'); var _ = require('underscore'); var multiline = require('multiline'); var template = _.template(multiline(function() { /* <a href="<%= url %>" title="<%= title %>" class="fancybox"> <img src="<%= url %>" alt="<%= title %>"></img> </a> */ })); module.exports = { book: { assets: './assets', js: [ 'jquery.min.js', 'jquery.fancybox.pack.js', 'jquery.fancybox-buttons.js', 'plugin.js' ], css: [ 'jquery.fancybox.css', 'jquery.fancybox-buttons.css' ] }, hooks: { page: function(page) { var $ = cheerio.load(page.content); $('img').each(function(index, img) { var $img = $(img); $img.replaceWith(template({ url: $img.attr('src'), title: $img.attr('alt') })); }); page.content = $.html(); return page; } } };
'use strict'; var cheerio = require('cheerio'); var _ = require('underscore'); var multiline = require('multiline'); var template = _.template(multiline(function() { /* <a href="<%= url %>" title="<%= title %>" target="_self" class="fancybox"> <img src="<%= url %>" alt="<%= title %>"></img> </a> */ })); module.exports = { book: { assets: './assets', js: [ 'jquery.min.js', 'jquery.fancybox.pack.js', 'jquery.fancybox-buttons.js', 'plugin.js' ], css: [ 'jquery.fancybox.css', 'jquery.fancybox-buttons.css' ] }, hooks: { page: function(page) { var $ = cheerio.load(page.content); $('img').each(function(index, img) { var $img = $(img); $img.replaceWith(template({ url: $img.attr('src'), title: $img.attr('alt') })); }); page.content = $.html(); return page; } } };
Add target attribute to a.fancybox to prevent default theme's links following
Add target attribute to a.fancybox to prevent default theme's links following
JavaScript
mit
ly-tools/gitbook-plugin-fancybox,LingyuCoder/gitbook-plugin-fancybox
203d8265d7410a3a8c65366db265569c516f3f12
index.js
index.js
'use strict'; const got = require('got'); const awaitUrl = (url, option) => { const config = Object.assign({}, option, { interval : 1000, tries : 60 }); return new Promise((resolve, reject) => { const attempt = async (tries) => { const res = await got(url, { followRedirect : false, timeout : 5000 }); if (res.statusCode === 200) { resolve(); } else if (Math.max(1, tries) > 1) { setTimeout(attempt, config.interval, tries - 1); } else { reject(new RangeError(`Expected 200 response but got ${res.statusCode}`)); } }; attempt(config.tries).catch(reject); }); }; module.exports = awaitUrl;
'use strict'; const got = require('got'); const awaitUrl = (url, option) => { const config = Object.assign({}, option, { interval : 1000, tries : 60 }); return new Promise((resolve, reject) => { const attempt = async (tries) => { const res = await got(url, { followRedirect : false, timeout : { connect : 10000, socket : 10000, request : 10000 } }); if (res.statusCode === 200) { resolve(); } else if (Math.max(1, tries) > 1) { setTimeout(attempt, config.interval, tries - 1); } else { reject(new RangeError(`Expected 200 response but got ${res.statusCode}`)); } }; attempt(config.tries).catch(reject); }); }; module.exports = awaitUrl;
Increase timeouts for very slow servers
Increase timeouts for very slow servers
JavaScript
mpl-2.0
sholladay/await-url
3651031dc09ea89f35ffc67363af07f444f2caf7
index.js
index.js
'use strict'; var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); var emitThen = function (event) { var args = Array.prototype.slice.call(arguments, 1); return Promise .bind(this) .return(this) .call('listeners', event) .map(function (listener) { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1) case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }) .return(null); }; emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
'use strict'; var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); function emitThen (event) { var args = Array.prototype.slice.call(arguments, 1); /* jshint validthis:true */ return Promise .bind(this) .return(this) .call('listeners', event) .map(function (listener) { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1) case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }) .return(null); } emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
Use a named function instead of anon
Use a named function instead of anon
JavaScript
mit
bendrucker/emit-then
8fd6bc21784da5a9cb1bb22ba515b85fb9f8f1a3
index.js
index.js
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'access-control-max-age': '86400', 'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }; var proxy = httpProxy.createProxyServer(); http.createServer(function(req, res) { if (req.method === 'OPTIONS') { // Respond to OPTIONS requests advertising we support full CORS for * res.writeHead(200, CORS_HEADERS); res.end(); return } // Remove our original host so it doesn't mess up Google's header parsing. delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); // Add CORS headers to every other request also. proxy.on('proxyRes', function(proxyRes, req, res) { for (var key in CORS_HEADERS) { proxyRes.headers[key] = CORS_HEADERS[key]; } }); }).listen(process.env.PORT || 5000);
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'access-control-max-age': '86400', 'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }; var proxy = httpProxy.createProxyServer(); // Add CORS headers to every other request also. proxy.on('proxyRes', function(proxyRes, req, res) { for (var key in CORS_HEADERS) { proxyRes.headers[key] = CORS_HEADERS[key]; } }); proxy.on('error', function(err, req, res) { console.log(err); var json = { error: 'proxy_error', reason: err.message }; if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } res.end(JSON.stringify(json)); }); http.createServer(function(req, res) { if (req.method === 'OPTIONS') { // Respond to OPTIONS requests advertising we support full CORS for * res.writeHead(200, CORS_HEADERS); res.end(); return } // Remove our original host so it doesn't mess up Google's header parsing. delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); }).listen(process.env.PORT || 5000);
Move proxyRes out of request handler; trap errors
Move proxyRes out of request handler; trap errors
JavaScript
mpl-2.0
yourcelf/gspreadsheets-cors-proxy
10280069a4c1ecf5cbaebd8b0f9b67f3d9c219d2
index.js
index.js
'use strict'; var execFile = require('child_process').execFile; var wifiName = require('wifi-name'); function getPassword(ssid, cb) { var cmd = 'sudo'; var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid]; var ret; execFile(cmd, args, function (err, stdout) { if (err) { cb(err); return; } ret = /^\s*psk=(.+)\s*$/gm.exec(stdout); ret = ret && ret.length ? ret[1] : null; if (!ret) { cb(new Error('Could not get password')); return; } cb(null, ret); }); } module.exports = function (ssid, cb) { if (process.platform !== 'linux') { throw new Error('Only Linux systems are supported'); } if (ssid && typeof ssid !== 'function') { getPassword(ssid, cb); return; } else if (ssid && !cb) { cb = ssid; } wifiName(function (err, name) { if (err) { cb(err); return; } getPassword(name, cb); }); };
'use strict'; var execFile = require('child_process').execFile; var wifiName = require('wifi-name'); function getPassword(ssid, cb) { var cmd = 'sudo'; var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid]; var ret; execFile(cmd, args, function (err, stdout) { if (err) { cb(err); return; } ret = /^\s*(?:psk|password)=(.+)\s*$/gm.exec(stdout); ret = ret && ret.length ? ret[1] : null; if (!ret) { cb(new Error('Could not get password')); return; } cb(null, ret); }); } module.exports = function (ssid, cb) { if (process.platform !== 'linux') { throw new Error('Only Linux systems are supported'); } if (ssid && typeof ssid !== 'function') { getPassword(ssid, cb); return; } else if (ssid && !cb) { cb = ssid; } wifiName(function (err, name) { if (err) { cb(err); return; } getPassword(name, cb); }); };
Add support for WPA2 Enterprise
Add support for WPA2 Enterprise Fixes #1.
JavaScript
mit
kevva/linux-wifi-password
4683e61d4d3eb6fb696f5e5672831b1f0de0d3db
index.js
index.js
'use strict'; const EventEmitter = require('events'); const devtools = require('./lib/devtools.js'); const Chrome = require('./lib/chrome.js'); function CDP(options, callback) { if (typeof options === 'function') { callback = options; options = undefined; } const notifier = new EventEmitter(); if (typeof callback === 'function') { // allow to register the error callback later process.nextTick(() => { new Chrome(options, notifier); }); return notifier.once('connect', callback); } else { return new Promise((fulfill, reject) => { notifier.once('connect', fulfill); notifier.once('error', reject); new Chrome(options, notifier); }); } } module.exports = CDP; module.exports.Protocol = devtools.Protocol; module.exports.List = devtools.List; module.exports.New = devtools.New; module.exports.Activate = devtools.Activate; module.exports.Close = devtools.Close; module.exports.Version = devtools.Version;
'use strict'; const EventEmitter = require('events'); const dns = require('dns'); const devtools = require('./lib/devtools.js'); const Chrome = require('./lib/chrome.js'); // XXX reset the default that has been changed in // (https://github.com/nodejs/node/pull/39987) to prefer IPv4. since // implementations alway bind on 127.0.0.1 this solution should be fairly safe // (see #467) dns.setDefaultResultOrder('ipv4first'); function CDP(options, callback) { if (typeof options === 'function') { callback = options; options = undefined; } const notifier = new EventEmitter(); if (typeof callback === 'function') { // allow to register the error callback later process.nextTick(() => { new Chrome(options, notifier); }); return notifier.once('connect', callback); } else { return new Promise((fulfill, reject) => { notifier.once('connect', fulfill); notifier.once('error', reject); new Chrome(options, notifier); }); } } module.exports = CDP; module.exports.Protocol = devtools.Protocol; module.exports.List = devtools.List; module.exports.New = devtools.New; module.exports.Activate = devtools.Activate; module.exports.Close = devtools.Close; module.exports.Version = devtools.Version;
Revert the default DNS lookup order to IPv4-first
Revert the default DNS lookup order to IPv4-first Fix #467
JavaScript
mit
cyrus-and/chrome-remote-interface,cyrus-and/chrome-remote-interface
864ce5aa89a99b17051bb41ce243490b8be0d4a1
index.js
index.js
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = {}; } var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : []; if (ignore === false) { throw TypeError("options.ignore must be an array") } for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (typeof value === "string") { value = new RegExp(value + "$", "i") } else if (value instanceof RegExp) { } else { throw TypeError("options.ignore values can either be a string or a regular expression") } ignore[i] = value; } return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = { ignore: [] } } if (!Array.isArray(options.ignore)) { throw TypeError("options.ignore must be an array") } var ignore = options.ignore.map(function (value) { if (typeof value === 'string') { return new RegExp(value + '$', 'i') } else if (value instanceof RegExp) { return value } else { throw TypeError('options.ignore values can either be a string or a regular expression') } }) return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
Change code as per @johnotander's suggestion
Change code as per @johnotander's suggestion
JavaScript
mit
johnotander/postcss-remove-prefixes
48db09838c934b349250efbada6aadcc95fece9c
index.js
index.js
/* jshint node: true */ 'use strict'; var path = require('path'); var filterInitializers = require('fastboot-filter-initializers'); var VersionChecker = require('ember-cli-version-checker'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-head', treeForApp: function(defaultTree) { var checker = new VersionChecker(this); var emberVersion = checker.for('ember', 'bower'); var trees = [defaultTree]; // 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not) // 2.10.0-beta.1+ includes glimmer2 if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) { trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10'))); } var tree = mergeTrees(trees, { overwrite: true }); return filterInitializers(tree); } };
/* jshint node: true */ 'use strict'; var path = require('path'); var filterInitializers = require('fastboot-filter-initializers'); var VersionChecker = require('ember-cli-version-checker'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-head', treeForApp: function(defaultTree) { var checker = new VersionChecker(this); var emberVersion = checker.for('ember-source', 'npm'); if (!emberVersion.version) { emberVersion = checker.for('ember', 'bower'); } var trees = [defaultTree]; // 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not) // 2.10.0-beta.1+ includes glimmer2 if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) { trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10'))); } var tree = mergeTrees(trees, { overwrite: true }); return filterInitializers(tree); } };
Check ember-source version from NPM, if not found use ember from bower
Check ember-source version from NPM, if not found use ember from bower
JavaScript
mit
ronco/ember-cli-head,ronco/ember-cli-head
28e666a0419b17cfa85a8e340927fd9cd691d045
index.js
index.js
module.exports = function (path) { var req = require; return function (module_name) { try { return req(module_name); } catch (err) { var resolve = null; req.main.paths.some(function (item) { if (resolve) return true; item = item.replace('node_modules', path); try { var main = req(item + '/' + module_name + '/package.json').main; main = item + '/' + module_name + '/' + main; req(main); resolve = main; } catch (e) {} // do nothing }); if (!resolve) throw err; return req(resolve) } }; };
var path = require('path'); module.exports = function (pathname) { var req = require; return function (module_name) { try { return req(module_name); } catch (err) { var resolve = null; req.main.paths.some(function (item) { if (resolve) return true; item = item.replace('node_modules', pathname); try { var main = path.join(item, module_name, 'package.json'); main = req(main).main; main = path.join(item, module_name, main); req(main); resolve = main; } catch (e) {} // do nothing }); if (!resolve) throw err; return req(resolve) } }; };
Add path for supporting Windows
Add path for supporting Windows
JavaScript
mit
watilde/graceful-require
955c5abe4bc2843df9c88124776207e83292d157
index.js
index.js
import bluebird from 'bluebird' import consoleStamp from 'console-stamp' import 'newrelic'; import { getSingleton as initApp } from './app/app' global.Promise = bluebird global.Promise.onPossiblyUnhandledRejection((e) => { throw e; }); consoleStamp(console, 'yyyy/mm/dd HH:MM:ss.l') initApp() .then((app) => { app.logger.info(`Server initialization is complete`) }) .catch((e) => { process.stderr.write(`FATAL ERROR\n`) process.stderr.write(`${e.message}\n`) process.stderr.write(`${e.stack}\n`) process.exit(1) })
import { statSync } from 'fs'; import bluebird from 'bluebird' import consoleStamp from 'console-stamp' import { getSingleton as initApp } from './app/app' try { statSync(`${__dirname}/newrelic.js`); require('newrelic'); } catch (e) { // No newrelic's config found. Won't report stats to them } global.Promise = bluebird global.Promise.onPossiblyUnhandledRejection((e) => { throw e; }); consoleStamp(console, 'yyyy/mm/dd HH:MM:ss.l') initApp() .then((app) => { app.logger.info(`Server initialization is complete`) }) .catch((e) => { process.stderr.write(`FATAL ERROR\n`) process.stderr.write(`${e.message}\n`) process.stderr.write(`${e.stack}\n`) process.exit(1) })
Enable newrelic only if config exists
Enable newrelic only if config exists
JavaScript
mit
FreeFeed/freefeed-server,SiTLar/freefeed-server,SiTLar/freefeed-server,golozubov/freefeed-server,golozubov/freefeed-server,FreeFeed/freefeed-server
346b58a0e4693f9bb25ca4271e7518a3a027983d
index.js
index.js
var loaderUtils = require('loader-utils'); var postcss = require('postcss'); module.exports = function (source) { if ( this.cacheable ) this.cacheable(); var file = loaderUtils.getRemainingRequest(this); var params = loaderUtils.parseQuery(this.query); var opts = { from: file, to: file }; if ( params.safe ) opts.safe = true; var processors = this.options.postcss; if ( params.pack ) { processors = processors[params.pack]; } else if ( !Array.isArray(processors) ) { processors = processors.defaults; } var processed = postcss.apply(postcss, processors).process(source, opts); this.callback(null, processed.css, processed.map); };
var loaderUtils = require('loader-utils'); var postcss = require('postcss'); module.exports = function (source, map) { if ( this.cacheable ) this.cacheable(); var file = loaderUtils.getRemainingRequest(this); var params = loaderUtils.parseQuery(this.query); var opts = { from: file, to: file, map: { prev: map, inline: false } }; if ( params.safe ) opts.safe = true; var processors = this.options.postcss; if ( params.pack ) { processors = processors[params.pack]; } else if ( !Array.isArray(processors) ) { processors = processors.defaults; } var processed = postcss.apply(postcss, processors).process(source, opts); this.callback(null, processed.css, processed.map); };
Use previous source map and don't inline the source maps.
Use previous source map and don't inline the source maps. This fixes source mapping when used with sass-loader. Also, we don't want to map to the postcss generated source, we want to map to the pre-postcss source.
JavaScript
mit
mokevnin/postcss-loader
2b8f476de5049d3d0933ca1712f1c22190a250cf
index.js
index.js
var toc = require('markdown-toc'); module.exports = { book: {}, hooks: { "page:before": function (page) { page.content = toc.insert(page.content, { slugify: function (str) { return encodeURI(str.toLowerCase()).replace(/%20/g, '-').replace(/[\.,\-\(\)]/g,''); } }); if (this.options.pluginsConfig.atoc.addClass) { var className = this.options.pluginsConfig.atoc.className || 'atoc'; page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>'; } return page; } } };
var toc = require('markdown-toc'); module.exports = { book: {}, hooks: { "page:before": function (page) { page.content = toc.insert(page.content, { slugify: function (str) { return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-]/g,'')).replace(/%20/g, '-'); } }); if (this.options.pluginsConfig.atoc.addClass) { var className = this.options.pluginsConfig.atoc.className || 'atoc'; page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>'; } return page; } } };
Fix every case a special character is suppressed
Fix every case a special character is suppressed I refer to https://github.com/jonschlinkert/remarkable/blob/dev/lib/common/utils.js#L45 for regex writing.
JavaScript
mit
willin/gitbook-plugin-atoc
9fc664fcacbd8149b06a6b80e62f7a1d4e8609e4
index.js
index.js
var DtsCreator = require('typed-css-modules'); var loaderUtils = require('loader-utils'); var objectAssign = require('object-assign'); module.exports = function(source, map) { this.cacheable && this.cacheable(); var callback = this.async(); // Pass on query parameters as an options object to the DtsCreator. This lets // you change the default options of the DtsCreator and e.g. use a different // output folder. var queryOptions = loaderUtils.parseQuery(this.query); var options; if (queryOptions) { options = objectAssign({}, queryOptions); } var creator = new DtsCreator(options); // creator.create(..., source) tells the module to operate on the // source variable. Check API for more details. creator.create(this.resourcePath, source).then(content => { // Emit the created content as well this.emitFile(this.resourcePath + '.d.ts', content.contents || ['']); content.writeFile().then(_ => { callback(null, source, map); }); }); };
var DtsCreator = require('typed-css-modules'); var loaderUtils = require('loader-utils'); var objectAssign = require('object-assign'); module.exports = function(source, map) { this.cacheable && this.cacheable(); var callback = this.async(); // Pass on query parameters as an options object to the DtsCreator. This lets // you change the default options of the DtsCreator and e.g. use a different // output folder. var queryOptions = loaderUtils.parseQuery(this.query); var options; if (queryOptions) { options = objectAssign({}, queryOptions); } var creator = new DtsCreator(options); // creator.create(..., source) tells the module to operate on the // source variable. Check API for more details. creator.create(this.resourcePath, source).then(content => { // Emit the created content as well this.emitFile(content.outputFilePath, content.contents || [''], map); content.writeFile().then(_ => { callback(null, source, map); }); }); };
Use content.outputFilePath and use pass sourcemap
Use content.outputFilePath and use pass sourcemap
JavaScript
mit
olegstepura/typed-css-modules-loader
185c90d862bccb2061f00bf2f4e6858cbb0eb660
index.js
index.js
'use strict' var express = require('express'), app = express(), bodyParser = require('body-parser'), config = require('./libs/config'), email = require('./libs/email') app.use(bodyParser.json()) app.post('/subscribe', email.subscribe) app.listen(config.port)
'use strict' var express = require('express'), app = express(), bodyParser = require('body-parser'), config = require('./libs/config'), email = require('./libs/email') app.use(bodyParser.json()) app.post('/subscribe', email.subscribe) app.listen(process.env.PORT || config.port)
Allow PORT to be set from cli
Allow PORT to be set from cli
JavaScript
mit
MakerFaireOrlando/mfo-server
0d62962e33a670ae3459d936ea7b95d2782eb340
index.js
index.js
/* Uses the slack button feature to offer a real time bot to multiple teams */ var Botkit = require('botkit'); if (!process.env.TOKEN || !process.env.PORT) { console.log('Error: Specify token and port in environment'); process.exit(1); } var config = {} if(process.env.MONGOLAB_URI) { var BotkitStorage = require('botkit-storage-mongo'); config = { storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}), }; } else { config = { json_file_store: './db_slackbutton_bot/', }; } var controller = Botkit.slackbot(config); controller.spawn({ token: process.env.TOKEN }).startRTM(function(err) { if (err) { throw new Error(err); } }); // BEGIN EDITING HERE! controller.hears('hello','direct_message',function(bot,message) { bot.reply(message,'Hello!'); }); controller.hears('^stop','direct_message',function(bot,message) { bot.reply(message,'Goodbye'); bot.rtm.close(); }); controller.on('direct_message,mention,direct_mention',function(bot,message) { bot.api.reactions.add({ timestamp: message.ts, channel: message.channel, name: 'robot_face', },function(err) { if (err) { console.log(err) } bot.reply(message,'I heard you loud and clear boss.'); }); });
/* Uses the slack button feature to offer a real time bot to multiple teams */ var Botkit = require('botkit'); if (!process.env.TOKEN) { console.log('Error: Missing environment variable TOKEN. Please Specify your Slack token in environment'); process.exit(1); } var config = {} if(process.env.MONGOLAB_URI) { var BotkitStorage = require('botkit-storage-mongo'); config = { storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}), }; } else { config = { json_file_store: './db_slackbutton_bot/', }; } var controller = Botkit.slackbot(config); controller.spawn({ token: process.env.TOKEN }).startRTM(function(err) { if (err) { throw new Error(err); } }); // BEGIN EDITING HERE! controller.hears('hello','direct_message',function(bot,message) { bot.reply(message,'Hello!'); }); // An example of what could be... // //controller.on('direct_message,mention,direct_mention',function(bot,message) { // bot.api.reactions.add({ // timestamp: message.ts, // channel: message.channel, // name: 'robot_face', // },function(err) { // if (err) { console.log(err) } // bot.reply(message,'I heard you loud and clear boss.'); // }); //});
Tidy things up, remove requirement for PORT env var
Tidy things up, remove requirement for PORT env var
JavaScript
mit
slackhq/easy-peasy-bot-custom-integration
8b2da192dbc26d7354ec1db9d101ae4c927b1bc6
src/state/middleware.js
src/state/middleware.js
import dataComplete from './actions/dataComplete'; import preprocessData from './actions/preprocessData'; import readFile from '../functions/file/readFile'; import preprocessFile from '../functions/file/preprocessFile'; import { PREPROCESSDATA, READDATA } from './constants'; const middleware = store => next => action => { const state = store.getState(); switch (action.type) { case READDATA: if (!state.coordIn || !state.fileIn) { console.error('Input fields not filled properly!'); break; } next(action); readFile(state.fileInList) .then(data => { store.dispatch(preprocessData(data)); }).catch(error => { console.error(error.message); }); break; case PREPROCESSDATA: preprocessFile(action.payload) .then(data => { store.dispatch(dataComplete(data)); }).catch(error => { console.error(error.message); }); break; default: next(action); } }; export default middleware;
import dataComplete from './actions/dataComplete'; import preprocessData from './actions/preprocessData'; import readFile from '../functions/file/readFile'; import preprocessFile from '../functions/file/preprocessFile'; import parseCoordinates from '../functions/parseCoordinates'; import issetCoordinates from '../functions/issetCoordinates'; import { PREPROCESSDATA, READDATA } from './constants'; const checkCoordinates = coordinates => issetCoordinates(parseCoordinates(coordinates)); const middleware = store => next => action => { const state = store.getState(); switch (action.type) { case READDATA: if (!state.coordIn || !state.fileIn || !checkCoordinates(state.coordIn)) { console.error('Input fields not filled properly!'); break; } next(action); readFile(state.fileInList) .then(data => { store.dispatch(preprocessData(data)); }).catch(error => { console.error(error.message); }); break; case PREPROCESSDATA: preprocessFile(action.payload) .then(data => { store.dispatch(dataComplete(data)); }).catch(error => { console.error(error.message); }); break; default: next(action); } }; export default middleware;
Check passed coordinates to be correct
Check passed coordinates to be correct
JavaScript
mit
krajvy/nearest-coordinates,krajvy/nearest-coordinates,krajvy/nearest-coordinates
c2c4730b4554357f394c3ecb9bae3e465cc4a154
lib/middleware/campaign-keyword.js
lib/middleware/campaign-keyword.js
'use strict'; const Campaigns = require('../../app/models/Campaign'); module.exports = function getCampaignForKeyword() { return (req, res, next) => { if (req.reply.template) { return next(); } return Campaigns.findByKeyword(req.userCommand) .then((campaign) => { if (! campaign) { return next(); } req.campaign = campaign; req.keyword = req.userCommand; return next(); }); }; };
'use strict'; const Campaigns = require('../../app/models/Campaign'); module.exports = function getCampaignForKeyword() { return (req, res, next) => { if (req.reply.template) { return next(); } // Did User send a Campaign keyword? return Campaigns.findByKeyword(req.userCommand) .then((campaign) => { if (! campaign) { return next(); } req.campaign = campaign; req.keyword = req.userCommand; // Gambit to handle the Confirmation/Continue reply. req.reply.template = 'gambit'; return next(); }); }; };
Fix Campaign keyword, send Gambit reply
Fix Campaign keyword, send Gambit reply
JavaScript
mit
DoSomething/gambit,DoSomething/gambit
823ecb6eb0f78d51b950fbe382b73769c8502c58
build-prod.js
build-prod.js
({ mainConfigFile: './requirejs.conf.js', paths: { jquery: 'lib/jquery/jquery.min', almond: 'lib/almond/almond' }, baseUrl: '.', name: "streamhub-map", exclude: ['streamhub-sdk', 'almond'], stubModules: ['text', 'hgn', 'json'], out: "./dist/streamhub-map.min.js", namespace: 'Livefyre', pragmasOnSave: { excludeHogan: true }, optimize: "uglify2", uglify2: { compress: { unsafe: true }, mangle: true }, onBuildRead: function(moduleName, path, contents) { if (moduleName == "jquery") { contents = "define([], function(require, exports, module) {" + contents + "});"; } return contents; } })
({ mainConfigFile: './requirejs.conf.js', paths: { jquery: 'lib/jquery/jquery.min', almond: 'lib/almond/almond' }, baseUrl: '.', name: "streamhub-map", exclude: ['streamhub-sdk', 'almond'], stubModules: ['text', 'hgn', 'json'], out: "./dist/streamhub-map.min.js", namespace: 'Livefyre', pragmasOnSave: { excludeHogan: true }, cjsTranslate: true, optimize: "uglify2", uglify2: { compress: { unsafe: true }, mangle: true }, onBuildRead: function(moduleName, path, contents) { if (moduleName == "jquery") { contents = "define([], function(require, exports, module) {" + contents + "});"; } return contents; } })
Add 'cjsTranslate' config option to build profile
Add 'cjsTranslate' config option to build profile
JavaScript
mit
cheung31/streamhub-map,Livefyre/streamhub-map,Livefyre/streamhub-map
af0c5f7cbbfb29a962477160976f8a048eb493d1
cache-bust.js
cache-bust.js
/** @license MIT License (c) copyright 2014 original authors */ /** @author Brian Cavalier */ /** @author John Hann */ define(['curl/_privileged'], function (priv) { var loadScript = priv['core'].loadScript; priv['core'].loadScript = function (def, success, failure) { var urlArgs = priv['config']()['urlArgs']; if (urlArgs) { def.url += (def.url.indexOf('?') >= 0 ? '&' : '?') + urlArgs; } return loadScript(def, success, failure); }; });
/** @license MIT License (c) copyright 2014 original authors */ /** @author John Hann */ define(/*==='curl-cache-bust/cache-bust',===*/ ['curl/_privileged'], function (priv) { var loadScript = priv['core'].loadScript; priv['core'].loadScript = function (def, success, failure) { var urlArgs = priv['config']()['urlArgs']; if (urlArgs) { def.url += (def.url.indexOf('?') >= 0 ? '&' : '?') + urlArgs; } return loadScript(def, success, failure); }; });
Add replaceable module id for curl's make utility.
Add replaceable module id for curl's make utility.
JavaScript
mit
unscriptable/curl-cache-bust
9493463612fae494ee5f1f644e379b876b8c5655
app/routes.js
app/routes.js
import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import store from 'lib/store'; import App from 'components/app'; import AdminDashboard from 'components/admin-dashboard'; import ImportPanel from 'components/import'; import ExportPanel from 'components/export'; import LoggedIn from 'components/logged-in'; export default ( <Provider store={ store }> <Router history={ browserHistory }> <Route path="/" component={ App }> <IndexRoute component={ LoggedIn } /> <Route path="/admin" component={ AdminDashboard } /> <Route path="/import" component={ ImportPanel } /> <Route path="/export" component={ ExportPanel } /> </Route> </Router> </Provider> );
import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import store from 'lib/store'; import App from 'components/app'; import ImportPanel from 'components/import'; import ExportPanel from 'components/export'; import LoggedIn from 'components/logged-in'; export default ( <Provider store={ store }> <Router history={ browserHistory }> <Route path="/" component={ App }> <IndexRoute component={ LoggedIn } /> <Route path="/import" component={ ImportPanel } /> <Route path="/export" component={ ExportPanel } /> </Route> </Router> </Provider> );
Remove admin dashboard for now
Remove admin dashboard for now
JavaScript
mit
sirbrillig/voyageur-js-client,sirbrillig/voyageur-js-client
91266e20e67cb920c86c014202a906af55b387bd
src/renderer/reducers/connections.js
src/renderer/reducers/connections.js
import * as types from '../actions/connections'; export default function(state = {}, action) { switch (action.type) { case types.CONNECTION_REQUEST: { const { server, database } = action; return { connected: false, connecting: true, server, database }; } case types.CONNECTION_SUCCESS: { if (!_isSameConnection(state, action)) return state; return { ...state, connected: true, connecting: false }; } case types.CONNECTION_FAILURE: { if (!_isSameConnection(state, action)) return state; return { ...state, connected: false, connecting: false, error: action.error }; } default : return state; } } function _isSameConnection (state, action) { return state.server === action.server && state.database === action.database; }
import * as types from '../actions/connections'; const INITIAL_STATE = {}; export default function(state = INITIAL_STATE, action) { switch (action.type) { case types.CONNECTION_REQUEST: { const { server, database } = action; return { connected: false, connecting: true, server, database }; } case types.CONNECTION_SUCCESS: { if (!_isSameConnection(state, action)) return state; return { ...state, connected: true, connecting: false }; } case types.CONNECTION_FAILURE: { if (!_isSameConnection(state, action)) return state; return { ...state, connected: false, connecting: false, error: action.error }; } default : return state; } } function _isSameConnection (state, action) { return state.server === action.server && state.database === action.database; }
Move connection initial state to variable
Move connection initial state to variable
JavaScript
mit
sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui
5c3cc5bce58b5c5b0dd7861b993b25d865e95aee
src/scripts/common/utils/platform.js
src/scripts/common/utils/platform.js
export default { isDarwin: process.platform === 'darwin', isNonDarwin: process.platform !== 'darwin', isWindows: process.platform === 'win32', isLinux: process.platform === 'linux', isWindows7: process.platform === 'win32' && navigator && !!navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/) };
export default { isDarwin: process.platform === 'darwin', isNonDarwin: process.platform !== 'darwin', isWindows: process.platform === 'win32', isLinux: process.platform === 'linux', isWindows7: process.platform === 'win32' && window.navigator && !!window.navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/) };
Fix detection of Windows 7
Fix detection of Windows 7
JavaScript
mit
Aluxian/Messenger-for-Desktop,Aluxian/Messenger-for-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp
f841fdaa19aeb5e35251af3c709f9893fc83cc68
routes2/api/auth.js
routes2/api/auth.js
const _ = require("lodash"); const express = require("express"); const router = express.Router(); const session = require("express-session"); const connect = require("../../utils/database.js"); const restrict = require("../../utils/middlewares/restrict.js"); const auth = require("../../utils/auth.js"); const jwt = require('jsonwebtoken'); const CharError = require("../../utils/charError.js"); const Promise = require("bluebird"); Promise.promisifyAll(jwt); require('dotenv').config(); const secret = "secret_key_PLEASE_CHANGE"; // Catch all for authentication (temporary) router.use(function(req, res, next){ // Anonymous access to API if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){ req.user = { username: "Anonymous", role: "anonymous" }; next(); return; } // Authenticate here and also set the logged in users role accordingly // Verify auth token jwt.verifyAsync(req.token, secret).then(function(payload){ req.user = { username: payload.username, role: payload.role }; next(); }).catch(function(err){ next(new CharError("Auth Token Invalid", err.message, 403)); }); }); module.exports = router;
const _ = require("lodash"); const express = require("express"); const router = express.Router(); const session = require("express-session"); const connect = require("../../utils/database.js"); const restrict = require("../../utils/middlewares/restrict.js"); const auth = require("../../utils/auth.js"); const jwt = require('jsonwebtoken'); const CharError = require("../../utils/charError.js"); const Promise = require("bluebird"); Promise.promisifyAll(jwt); require('dotenv').config(); const secret = process.env.JWT_SECRET; // Catch all for authentication (temporary) router.use(function(req, res, next){ // Anonymous access to API if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){ req.user = { username: "Anonymous", role: "anonymous" }; next(); return; } // Authenticate here and also set the logged in users role accordingly // Verify auth token jwt.verifyAsync(req.token, secret).then(function(payload){ req.user = { username: payload.username, role: payload.role }; next(); }).catch(function(err){ next(new CharError("Auth Token Invalid", err.message, 403)); }); }); module.exports = router;
Use .env to store secret
Use .env to store secret
JavaScript
bsd-3-clause
limzykenneth/char,limzykenneth/char
3f463786c52254f353e5bb9c22155441146f8eef
docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js
docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import ActionAndroid from 'material-ui/svg-icons/action/android'; import FontIcon from 'material-ui/FontIcon'; const styles = { button: { margin: 12, }, exampleImageInput: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0, }, }; const RaisedButtonExampleComplex = () => ( <div> <RaisedButton label="Choose an Image" labelPosition="before" style={styles.button} > <input type="file" style={styles.exampleImageInput} /> </RaisedButton> <RaisedButton label="Label before" labelPosition="before" primary={true} icon={<ActionAndroid />} style={styles.button} /> <RaisedButton label="Github Link" href="https://github.com/callemall/material-ui" secondary={true} style={styles.button} icon={<FontIcon className="muidocs-icon-custom-github" />} /> </div> ); export default RaisedButtonExampleComplex;
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import ActionAndroid from 'material-ui/svg-icons/action/android'; import FontIcon from 'material-ui/FontIcon'; const styles = { button: { margin: 12, }, exampleImageInput: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0, }, }; const RaisedButtonExampleComplex = () => ( <div> <RaisedButton label="Choose an Image" labelPosition="before" style={styles.button} containerElement="label" > <input type="file" style={styles.exampleImageInput} /> </RaisedButton> <RaisedButton label="Label before" labelPosition="before" primary={true} icon={<ActionAndroid />} style={styles.button} /> <RaisedButton label="Github Link" href="https://github.com/callemall/material-ui" secondary={true} style={styles.button} icon={<FontIcon className="muidocs-icon-custom-github" />} /> </div> ); export default RaisedButtonExampleComplex;
Update file input RaisedButton example
Update file input RaisedButton example This shows how to correctly embed a file input file into a RaisedButton ensuring that the file input remains clickable cross browser #3689 #4983 #1178
JavaScript
mit
janmarsicek/material-ui,mit-cml/iot-website-source,hwo411/material-ui,ichiohta/material-ui,w01fgang/material-ui,igorbt/material-ui,hwo411/material-ui,mtsandeep/material-ui,pancho111203/material-ui,manchesergit/material-ui,lawrence-yu/material-ui,frnk94/material-ui,ichiohta/material-ui,hai-cea/material-ui,mtsandeep/material-ui,ArcanisCz/material-ui,mmrtnz/material-ui,ArcanisCz/material-ui,janmarsicek/material-ui,pancho111203/material-ui,frnk94/material-ui,kittyjumbalaya/material-components-web,mmrtnz/material-ui,manchesergit/material-ui,janmarsicek/material-ui,janmarsicek/material-ui,lawrence-yu/material-ui,w01fgang/material-ui,igorbt/material-ui,hai-cea/material-ui,mit-cml/iot-website-source,verdan/material-ui,verdan/material-ui,mit-cml/iot-website-source,kittyjumbalaya/material-components-web
915acf8a0b9012f04825846b91c68c1ac0ed9df1
packages/storybook/jest.config.js
packages/storybook/jest.config.js
module.exports = { collectCoverageFrom: [ "**/src/**/*.{js,jsx}", "!**/index.js", ], coverageDirectory: "<rootDir>/packages/storybook/coverage", coveragePathIgnorePatterns: [ "node_modules", "packages\/vanilla", "src\/playground", "examples\/redux", "__stories__", "__gemini__" ], coverageThreshold: { global: { branches: 60, functions: 60, lines: 60, statements: 60 } }, moduleNameMapper: { "\\.(css|scss|svg)$": "<rootDir>/packages/storybook/support/jest/fileMock.js" }, modulePaths: ["node_modules"], moduleFileExtensions: ["js", "jsx", "json"], rootDir: "../../", setupFiles: ["raf/polyfill"], setupTestFrameworkScriptFile: "<rootDir>/packages/storybook/support/jest/setupTests.js", testPathIgnorePatterns: ["<rootDir>/packages/vanilla"], unmockedModulePathPatterns: ["node_modules"] };
module.exports = { collectCoverageFrom: [ "**/src/**/*.{js,jsx}" ], coverageDirectory: "<rootDir>/packages/storybook/coverage", coveragePathIgnorePatterns: [ "node_modules", "packages\/vanilla", "src\/playground", "examples\/redux", "__stories__", "__gemini__" ], coverageThreshold: { global: { branches: 60, functions: 60, lines: 60, statements: 60 } }, moduleNameMapper: { "\\.(css|scss|svg)$": "<rootDir>/packages/storybook/support/jest/fileMock.js" }, modulePaths: ["node_modules"], moduleFileExtensions: ["js", "jsx", "json"], rootDir: "../../", setupFiles: ["raf/polyfill"], setupTestFrameworkScriptFile: "<rootDir>/packages/storybook/support/jest/setupTests.js", testPathIgnorePatterns: ["<rootDir>/packages/vanilla"], unmockedModulePathPatterns: ["node_modules"] };
Include coverage for index files
Include coverage for index files
JavaScript
apache-2.0
Autodesk/hig,Autodesk/hig,Autodesk/hig
94ae410220b3006290526484c25ae18405cb5f1e
frontend/src/state/store.js
frontend/src/state/store.js
const createLogger = require('redux-logger'); const enableBatching = require('redux-batched-actions').enableBatching; const promiseMiddleware = require('redux-promise-middleware').default; const redux = require('redux'); const thunk = require('redux-thunk').default; const createReducer = require('@state/reducers'); const { createStore, compose, applyMiddleware } = redux; module.exports = (state = Object.freeze({})) => { return createStore( enableBatching(createReducer()), state, compose( applyMiddleware( createLogger(), promiseMiddleware(), thunk ) ) ); };
const createLogger = require('redux-logger'); const enableBatching = require('redux-batched-actions').enableBatching; const promiseMiddleware = require('redux-promise-middleware').default; const redux = require('redux'); const thunk = require('redux-thunk').default; const createReducer = require('@state/reducers'); const { createStore, compose, applyMiddleware } = redux; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; module.exports = (state = Object.freeze({})) => { return createStore( enableBatching(createReducer()), state, composeEnhancers( applyMiddleware( createLogger(), promiseMiddleware(), thunk ) ) ); };
Add Redux devtool extension connection - will need to only be available in dev in the future
Add Redux devtool extension connection - will need to only be available in dev in the future
JavaScript
mpl-2.0
yldio/joyent-portal,yldio/copilot,geek/joyent-portal,yldio/copilot,yldio/joyent-portal,yldio/copilot,geek/joyent-portal
b7af36180873e1bb8bf201ae3dd7a2d765519ce0
dev/app/components/main/projects/projects.controller.js
dev/app/components/main/projects/projects.controller.js
ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ]; function ProjectsController(TbUtils, projects, $rootScope) { const vm = this; vm.searchObj = term => { return { Name: term }; }; vm.searchResults = []; vm.pageSize = 9; vm.get = projects.getProjectsWithPagination; vm.getAll = projects.getProjects; vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length; vm.projects = []; vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); }; vm.goToNewProject = project => { TbUtils.go('main.addproject'); }; vm.goToEdit = project => { TbUtils.go('main.editproject', { project: JSON.stringify(project) }); }; vm.loading = true; vm.removeProjectClicked = removeProjectClicked; vm.toTitleCase = TbUtils.toTitleCase; TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize); function removeProjectClicked(project) { TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`, resolve => { if (resolve) { vm.loading = true; TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects, () => { vm.loading = false; }); } }); } } module.exports = { name: 'ProjectsController', ctrl: ProjectsController };
ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ]; function ProjectsController(TbUtils, projects, $rootScope) { const vm = this; vm.searchObj = term => { return { Name: term }; }; vm.searchResults = []; vm.pageSize = 9; vm.get = projects.getProjectsWithPagination; vm.getAll = projects.getProjects; vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length; vm.projects = []; vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); }; vm.goToNewProject = project => { TbUtils.go('main.new-project'); }; vm.goToEdit = project => { TbUtils.go('main.edit-project', { project: btoa(JSON.stringify(project)) }); }; vm.loading = true; vm.removeProjectClicked = removeProjectClicked; vm.toTitleCase = TbUtils.toTitleCase; TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize); function removeProjectClicked(project) { TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`, resolve => { if (resolve) { vm.loading = true; TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects, () => { vm.loading = false; }); } }); } } module.exports = { name: 'ProjectsController', ctrl: ProjectsController };
Change redirects to project form
Change redirects to project form
JavaScript
mit
Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC
3b7f243a6e663129e98d2551163e2ac01248cbf3
public/javascripts/application.js
public/javascripts/application.js
$(document).ready(function() { if (window.location.href.search(/query=/) == -1) { $('#query').one('click, focus', function() { $(this).val(''); }); } $(document).bind('keyup', function(event) { if ($(event.target).is(':input')) { return; } if (event.which == 83) { $('#query').focus(); } }); $('#version_for_stats').change(function() { window.location.href = $(this).val(); }); });
$(document).ready(function() { $('#version_for_stats').change(function() { window.location.href = $(this).val(); }); });
Remove JS that handled not-quite-placeholder.
Remove JS that handled not-quite-placeholder.
JavaScript
mit
sonalkr132/rubygems.org,hrs113355/rubygems.org,spk/rubygems.org,polamjag/rubygems.org,farukaydin/rubygems.org,iSC-Labs/rubygems.org,polamjag/rubygems.org,jamelablack/rubygems.org,childbamboo/rubygems.org,krainboltgreene/rubygems.org,davydovanton/rubygems.org,iRoxxDotOrg/rubygems.org,spk/rubygems.org,farukaydin/rubygems.org,wallin/rubygems.org,sonalkr132/rubygems.org,iRoxxDotOrg/rubygems.org,maclover7/rubygems.org,jamelablack/rubygems.org,sonalkr132/rubygems.org,davydovanton/rubygems.org,algolia/rubygems.org,huacnlee/rubygems.org,rubygems/rubygems.org,algolia/rubygems.org,huacnlee/rubygems.org,Ch4s3/rubygems.org,kbrock/rubygems.org,andrew/rubygems.org,JuanitoFatas/rubygems.org,hrs113355/rubygems.org,childbamboo/rubygems.org,Ch4s3/rubygems.org,olivierlacan/rubygems.org,rubygems/rubygems.org,davydovanton/rubygems.org,Ch4s3/rubygems.org,rubygems/rubygems.org,krainboltgreene/rubygems.org,arthurnn/rubygems.org,spk/rubygems.org,polamjag/rubygems.org,arthurnn/rubygems.org,iRoxxDotOrg/rubygems.org,andrew/rubygems.org,Elffers/rubygems.org,olivierlacan/rubygems.org,iSC-Labs/rubygems.org,algolia/rubygems.org,wallin/rubygems.org,iRoxxDotOrg/rubygems.org,davydovanton/rubygems.org,farukaydin/rubygems.org,childbamboo/rubygems.org,polamjag/rubygems.org,jamelablack/rubygems.org,Elffers/rubygems.org,fotanus/rubygems.org,fotanus/rubygems.org,kbrock/rubygems.org,fotanus/rubygems.org,knappe/rubygems.org,JuanitoFatas/rubygems.org,krainboltgreene/rubygems.org,rubygems/rubygems.org,hrs113355/rubygems.org,huacnlee/rubygems.org,JuanitoFatas/rubygems.org,iSC-Labs/rubygems.org,iSC-Labs/rubygems.org,knappe/rubygems.org,Ch4s3/rubygems.org,andrew/rubygems.org,arthurnn/rubygems.org,Exeia/rubygems.org,JuanitoFatas/rubygems.org,spk/rubygems.org,hrs113355/rubygems.org,olivierlacan/rubygems.org,Exeia/rubygems.org,knappe/rubygems.org,childbamboo/rubygems.org,wallin/rubygems.org,wallin/rubygems.org,fotanus/rubygems.org,huacnlee/rubygems.org,jamelablack/rubygems.org,sonalkr132/rubygems.org,olivierlacan/rubygems.org,Exeia/rubygems.org,Exeia/rubygems.org,kbrock/rubygems.org,krainboltgreene/rubygems.org,knappe/rubygems.org,kbrock/rubygems.org,andrew/rubygems.org,maclover7/rubygems.org,maclover7/rubygems.org,maclover7/rubygems.org,Elffers/rubygems.org,algolia/rubygems.org,farukaydin/rubygems.org,Elffers/rubygems.org
fbd4d6a6a34a13f7d3b506baf6e7687364707a5e
src/test/resources/positive/i205-ref-disambiguation-II.js
src/test/resources/positive/i205-ref-disambiguation-II.js
defaultScope(4); intRange(-8, 7); c10_Car = Clafer("c10_Car").withCard(4, 4); c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1); c21_Person = Clafer("c21_Person").withCard(4, 4); c11_owner.refToUnique(c21_Person); Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(join(c1, c11_owner), join(c2, c11_owner))));
defaultScope(4); intRange(-8, 7); c10_Car = Clafer("c10_Car").withCard(4, 4); c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1); c21_Person = Clafer("c21_Person").withCard(4, 4); c11_owner.refToUnique(c21_Person); Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(joinRef(join(c1, c11_owner)), joinRef(join(c2, c11_owner)))));
Add explicit refs to test case.
Add explicit refs to test case.
JavaScript
mit
gsdlab/chocosolver,gsdlab/chocosolver
987a064c7ee618788b74709d49ea9727a4bfa2e2
src/views/HomeView/RoomChart.js
src/views/HomeView/RoomChart.js
import React, { PropTypes } from 'react' import {LineChart} from 'react-d3-basic' import classes from './RoomChart.scss' class RoomChart extends React.Component { static propTypes = { data: PropTypes.object }; render () { const {data} = this.props let activity = [] if (data && data.activity) { activity = data.activity } const chartData = activity.map((chunk) => { return { timestamp: new Date(chunk[0] * 1000), messages: chunk[1] } }) const width = 550 return ( <LineChart data={chartData} width={width} height={300} margins={{ top: 25, bottom: 60, right: 25, left: 50 }} chartSeries={[ { field: 'messages', name: 'Messages', color: '#ff7600', style: { 'stroke-width': 2.5 } } ]} x={(d) => d.timestamp} xScale='time' innerTickSize={20} /> ) } } export default RoomChart
import React, { PropTypes } from 'react' import {LineChart} from 'react-d3-basic' class RoomChart extends React.Component { static propTypes = { data: PropTypes.object }; render () { const {data} = this.props let activity = [] if (data && data.activity) { activity = data.activity } const chartData = activity.map((chunk) => { return { timestamp: new Date(chunk[0] * 1000), messages: chunk[1] } }) const width = 550 return ( <LineChart data={chartData} width={width} height={300} margins={{ top: 25, bottom: 60, right: 25, left: 50 }} chartSeries={[ { field: 'messages', name: 'Messages', color: '#ff7600', style: { 'stroke-width': 2.5 } } ]} x={(d) => d.timestamp} xScale='time' innerTickSize={20} /> ) } } export default RoomChart
Remove unused var to fix lint error
Remove unused var to fix lint error
JavaScript
mit
seriallos/hubot-stats-web,seriallos/hubot-stats-web
5b5df02c9120d9d13616f9dcabda1a959191ee19
packages/truffle-box/test/unbox.js
packages/truffle-box/test/unbox.js
var path = require("path"); var fs = require("fs-extra"); var assert = require("assert"); var Box = require("../"); var TRUFFLE_BOX_DEFAULT = "git@github.com:trufflesuite/truffle-init-default.git"; describe("Unbox", function() { var destination = path.join(__dirname, ".truffle_test_tmp"); before("mkdir", function(done) { fs.ensureDir(destination, done); }); before("remove tmp dir", function(done) { fs.remove(destination, done); }); it("unboxes truffle box from github", function() { this.timeout(5000); return Box.unbox(TRUFFLE_BOX_DEFAULT, destination) .then(function (truffleConfig) { assert.ok(truffleConfig); assert( fs.existsSync(path.join(destination, "truffle.js")), "Unboxed project should have truffle config." ); }); }); });
var path = require("path"); var fs = require("fs-extra"); var assert = require("assert"); var Box = require("../"); var TRUFFLE_BOX_DEFAULT = "git@github.com:trufflesuite/truffle-init-default.git"; describe("Unbox", function() { var destination = path.join(__dirname, ".truffle_test_tmp"); before("mkdir", function(done) { fs.ensureDir(destination, done); }); after("remove tmp dir", function(done) { fs.remove(destination, done); }); it("unboxes truffle box from github", function() { this.timeout(5000); return Box.unbox(TRUFFLE_BOX_DEFAULT, destination) .then(function (truffleConfig) { assert.ok(truffleConfig); assert( fs.existsSync(path.join(destination, "truffle.js")), "Unboxed project should have truffle config." ); }); }); it("won't re-init if truffle.js file exists", function(done) { this.timeout(5000); var contracts_directory = path.join(destination, "contracts"); // Assert our precondition assert(fs.existsSync(contracts_directory), "contracts directory should exist for this test to be meaningful"); fs.remove(contracts_directory, function(err) { if (err) return done(err); Box.unbox(TRUFFLE_BOX_DEFAULT, destination) .then(function(boxConfig) { assert( fs.existsSync(contracts_directory) == false, "Contracts directory got recreated when it shouldn't have" ); done(); }) .catch(function(e) { if (e.message.indexOf("A Truffle project already exists at the destination.") >= 0) { done(); } else { done(new Error("Unknown error received: " + e.stack)); } }); }); }); });
Add project collision test from truffle-init
Add project collision test from truffle-init
JavaScript
mit
ConsenSys/truffle
761c016727331da4a252f4936390c2fd11097bc0
src/overrides/HasMany.js
src/overrides/HasMany.js
Ext.define('Densa.overrides.HasMany', { override: 'Ext.data.association.HasMany', /** * Allow filters in storeConfig * * Original overrides filters with filter */ createStore: function() { var that = this, associatedModel = that.associatedModel, storeName = that.storeName, foreignKey = that.foreignKey, primaryKey = that.primaryKey, filterProperty = that.filterProperty, autoLoad = that.autoLoad, storeConfig = that.storeConfig || {}; return function() { var me = this, config, filter, modelDefaults = {}; if (me[storeName] === undefined) { if (filterProperty) { filter = { property : filterProperty, value : me.get(filterProperty), exactMatch: true }; } else { filter = { property : foreignKey, value : me.get(primaryKey), exactMatch: true }; } if (!storeConfig.filters) storeConfig.filters = []; storeConfig.filters.push(filter); modelDefaults[foreignKey] = me.get(primaryKey); config = Ext.apply({}, storeConfig, { model : associatedModel, remoteFilter : false, modelDefaults: modelDefaults, disableMetaChangeEvent: true }); me[storeName] = Ext.data.AbstractStore.create(config); if (autoLoad) { me[storeName].load(); } } return me[storeName]; }; } });
Ext.define('Densa.overrides.HasMany', { override: 'Ext.data.association.HasMany', /** * Allow filters in storeConfig * * Original overrides filters with filter */ createStore: function() { var that = this, associatedModel = that.associatedModel, storeName = that.storeName, foreignKey = that.foreignKey, primaryKey = that.primaryKey, filterProperty = that.filterProperty, autoLoad = that.autoLoad, storeConfig = that.storeConfig || {}; return function() { var me = this, config, filter, modelDefaults = {}; if (me[storeName] === undefined) { if (filterProperty) { filter = { property : filterProperty, value : me.get(filterProperty), exactMatch: true }; } else { filter = { property : foreignKey, value : me.get(primaryKey), exactMatch: true }; } var localStoreConfig = Ext.clone(storeConfig); if (!localStoreConfig.filters) localStoreConfig.filters = []; localStoreConfig.filters.push(filter); modelDefaults[foreignKey] = me.get(primaryKey); config = Ext.apply({}, localStoreConfig, { model : associatedModel, remoteFilter : false, modelDefaults: modelDefaults, disableMetaChangeEvent: true }); me[storeName] = Ext.data.AbstractStore.create(config); if (autoLoad) { me[storeName].load(); } } return me[storeName]; }; } });
Fix filters in storeConfig: they where shared across multiple stores
Fix filters in storeConfig: they where shared across multiple stores Problem was that storeConfig is an object and thus modified by reference
JavaScript
bsd-2-clause
koala-framework/densajs,Ben-Ho/densajs
e6f6f94480582504c4ff1293e9c5b00e8b450000
js/scripts.js
js/scripts.js
var pingPongOutput = function(inputNumber) { if(inputNumber % 3 === 0) { return "ping"; } else { return inputNumber; } };
var pingPongOutput = function(inputNumber) { if(inputNumber % 3 === 0) { return "ping"; } else if (inputNumber % 5 === 0) { return "pong"; } else { return inputNumber; } };
Implement numbers divisible by 5
Implement numbers divisible by 5
JavaScript
mit
JeffreyRuder/ping-pong-app,JeffreyRuder/ping-pong-app
84639f7c85a9ae4109dee5b042e44fecc16c02dd
js/scripts.js
js/scripts.js
var pingPong = function(i) { if (isPingPong(i)) { return pingPongType(i) } else { return false; } } var pingPongType = function(i) { if ((i % 3 === 0) && (i % 5 != 0)) { return "ping"; } else if ((i % 5 === 0) && (i % 3 !=0)) { return "pong"; } else if (i % 15 === 0){ return "pingpong"; } } var isPingPong = function(i) { if ((i % 5 === 0) || (i % 3 === 0)){ return true; } else { return false; } } $(function() { $("#game").submit(function(event) { $('#outputList').empty(); var number = parseInt($("#userNumber").val()); var whichPingPong = pingPongType(i) for (var i = 1; i <= number; i += 1) { if (pingPong(i)) { $('#outputList').append("<li>" + whichPingPong + "</li>"); } else { $('#outputList').append("<li>" + i + "</li>"); } } event.preventDefault(); }); });
var pingPongType = function(i) { if (i % 15 === 0) { return "pingpong"; } else if (i % 5 === 0) { return "pong"; } else { return "ping"; } } var isPingPong = function(i) { if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) { return pingPongType(i); } else { return false; } } $(function() { $("#game").submit(function(event) { $('#outputList').empty(); var number = parseInt($("#userNumber").val()); var whichPingPong = pingPongType(i) for (var i = 1; i <= number; i += 1) { if (isPingPong(i)) { $('#outputList').append("<li>" + whichPingPong + "</li>"); } else { $('#outputList').append("<li>" + i + "</li>"); } } event.preventDefault(); }); });
Remove code for pingPong, leaving pingPongType and isPingPong as functions
Remove code for pingPong, leaving pingPongType and isPingPong as functions
JavaScript
mit
kcmdouglas/pingpong,kcmdouglas/pingpong
2fadeb3eaf5c182bd29380edc7b7c5666b37177e
lib/extend.js
lib/extend.js
'use strict'; var _ = require('underscore'); module.exports = function extend (Superclass, prototypeFragment) { prototypeFragment = prototypeFragment || {}; var Subclass = function () { if (_.isFunction(prototypeFragment.initialize)) { prototypeFragment.initialize.apply(this, arguments); } else { Superclass.apply(this, arguments); } }; Subclass.prototype = Object.create(Superclass.prototype); _.extend(Subclass.prototype, prototypeFragment); return Subclass; };
'use strict'; var _ = require('underscore'); module.exports = function extend (Superclass, prototypeFragment) { prototypeFragment = prototypeFragment || {}; var Subclass = function () { Superclass.apply(this, arguments); if (_.isFunction(prototypeFragment.initialize)) { prototypeFragment.initialize.apply(this, arguments); } }; Subclass.prototype = Object.create(Superclass.prototype); _.extend(Subclass.prototype, prototypeFragment); return Subclass; };
Fix the issue by calling constructor and checking for initialize
[Green] Fix the issue by calling constructor and checking for initialize
JavaScript
mit
ImpactFlow/flow
cb7b7847c3324bb5dbbea5b9e185cece8eaf2b96
lib/mincer.js
lib/mincer.js
'use strict'; // internal var mixin = require('./mincer/common'); module.exports = { VERSION: '0.0.0', EngineTemplate: require('./mincer/engine_template'), Environment: require('./mincer/environment'), Manifest: require('./mincer/manifest') }; mixin(module.exports, require('./mincer/engines')); mixin(module.exports, require('./mincer/paths'));
'use strict'; // internal var mixin = require('./mincer/common').mixin; var prop = require('./mincer/common').prop; module.exports = { VERSION: '0.0.0', EngineTemplate: require('./mincer/engine_template'), Environment: require('./mincer/environment'), Manifest: require('./mincer/manifest') }; prop(module.exports, '__engines__', {}); mixin(module.exports, require('./mincer/engines')); mixin(module.exports, require('./mincer/paths'));
Add some mixins to main lib
Add some mixins to main lib
JavaScript
mit
rhyzx/mincer,mcanthony/mincer,nodeca/mincer,inukshuk/mincer
d968bcfd42463bcbc4cddf891ae76df85c45d6f2
src/redux/createStore.js
src/redux/createStore.js
import { createStore as _createStore, applyMiddleware } from 'redux'; import fetchMiddleware from './middleware/fetchMiddleware'; import reducer from './modules/reducer'; export default function createStore(client, data) { const middlewares = [fetchMiddleware(client)]; const finalCreateStore = applyMiddleware(...middlewares)(_createStore); const store = finalCreateStore(reducer, data); /* global module, require */ if (module.hot) { module.hot.accept('./modules/reducer', () => { store.replaceReducer(require('./modules/reducer')); }); } return store; }
import { createStore as _createStore, applyMiddleware } from 'redux'; import { browserHistory } from 'react-router'; import { routerMiddleware, } from 'react-router-redux'; import fetchMiddleware from './middleware/fetchMiddleware'; import reducer from './modules/reducer'; export default function createStore(client, data) { const middlewares = [ fetchMiddleware(client), routerMiddleware(browserHistory), ]; const finalCreateStore = applyMiddleware(...middlewares)(_createStore); const store = finalCreateStore(reducer, data); /* global module, require */ if (module.hot) { module.hot.accept('./modules/reducer', () => { store.replaceReducer(require('./modules/reducer')); }); } return store; }
Connect router history to redux.
Connect router history to redux.
JavaScript
agpl-3.0
ahoereth/lawly,ahoereth/lawly,ahoereth/lawly
58dd0255dc16aea48eedc2bee64da922a9e8d394
src/server/action/Executor.js
src/server/action/Executor.js
import ExecutorBase from '../../action/Executor'; import types from '../../action/types'; export default class Executor extends ExecutorBase { _onAttack(action, world) { } }
import ExecutorBase from '../../action/Executor'; export default class Executor extends ExecutorBase { }
Remove empty code to prevent jslint errors
Remove empty code to prevent jslint errors
JavaScript
mit
DirtyHairy/mayrogue-deathmatch,DirtyHairy/mayrogue-deathmatch
571376913b7b8c9d8ea329c6865cd8869c954b25
karma.conf.js
karma.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ clearContext: false, // leave Jasmine Spec Runner output visible in browser jasmine: { random: false } }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ clearContext: false, // leave Jasmine Spec Runner output visible in browser jasmine: { random: false } }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, browserNoActivityTimeout: 30000 }); };
Increase browser inactivity timeout for test runs.
Increase browser inactivity timeout for test runs.
JavaScript
mpl-2.0
thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear,thehyve/glowing-bear
050359c7399b9e8905d114a2438fa7e374da9811
tests/collect.test.js
tests/collect.test.js
'use strict'; (function () { var expect = require('chai').expect; var collect = require('../src/collect'); describe('collect.js', function () { it('should exist', function () { expect(collect).to.be.ok; expect(typeof collect).to.equal('function'); }); }); })();
'use strict'; (function () { var expect = require('chai').expect; var collect = require('../src/collect'); var Jarg = require('../src/jarg'); var Command = require('../src/command'); describe('collect.js', function () { it('should exist', function () { expect(collect).to.be.ok; expect(typeof collect).to.equal('function'); }); it('should return a Jarg instance', function () { var boundCollect = collect.bind(null, 'node', 'npm', ['install', 'jargs', '--save']); var result = boundCollect( Command( 'npm' ) ); expect(result instanceof Jarg).to.be.true; }); }); })();
Test that collect returns a Jarg instance
Test that collect returns a Jarg instance
JavaScript
mit
JakeSidSmith/jargs
ebdaf4dd46279ee1650fd4fc1a5128f0c404ee79
tests/compile/main.js
tests/compile/main.js
goog.provide('Main'); // Core // Either require 'Blockly.requires', or just the components you use: goog.require('Blockly'); goog.require('Blockly.FieldDropdown'); goog.require('Blockly.FieldImage'); goog.require('Blockly.FieldNumber'); goog.require('Blockly.FieldTextInput'); goog.require('Blockly.FieldVariable'); goog.require('Blockly.geras.Renderer'); // Blocks goog.require('Blockly.Constants.Logic'); goog.require('Blockly.Constants.Loops'); goog.require('Blockly.Constants.Math'); goog.require('Blockly.Constants.Text'); goog.require('Blockly.Constants.Lists'); goog.require('Blockly.Constants.Colour'); goog.require('Blockly.Constants.Variables'); goog.require('Blockly.Constants.VariablesDynamic'); goog.require('Blockly.Blocks.procedures'); Main.init = function() { Blockly.inject('blocklyDiv', { 'toolbox': document.getElementById('toolbox') }); }; window.addEventListener('load', Main.init);
goog.provide('Main'); // Core // Either require 'Blockly.requires', or just the components you use: goog.require('Blockly'); goog.require('Blockly.geras.Renderer'); // Blocks goog.require('Blockly.Constants.Logic'); goog.require('Blockly.Constants.Loops'); goog.require('Blockly.Constants.Math'); goog.require('Blockly.Constants.Text'); goog.require('Blockly.Constants.Lists'); goog.require('Blockly.Constants.Colour'); goog.require('Blockly.Constants.Variables'); goog.require('Blockly.Constants.VariablesDynamic'); goog.require('Blockly.Blocks.procedures'); Main.init = function() { Blockly.inject('blocklyDiv', { 'toolbox': document.getElementById('toolbox') }); }; window.addEventListener('load', Main.init);
Remove now unneeded requires from compile test.
Remove now unneeded requires from compile test.
JavaScript
apache-2.0
mark-friedman/blockly,picklesrus/blockly,google/blockly,picklesrus/blockly,mark-friedman/blockly,mark-friedman/blockly,google/blockly,mark-friedman/blockly,mark-friedman/blockly,mark-friedman/blockly,google/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly,google/blockly,rachel-fenichel/blockly,google/blockly,rachel-fenichel/blockly,google/blockly,google/blockly,rachel-fenichel/blockly,picklesrus/blockly,rachel-fenichel/blockly,rachel-fenichel/blockly