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
f84d03b1bec6f30fd3c906a8add346d6c1de0586
lib/pkgcloud/amazon/client.js
lib/pkgcloud/amazon/client.js
/* * client.js: Base client from which all AWS clients inherit from * * (C) 2012 Nodejitsu Inc. * */ var utile = require('utile'), request = require('request'), base = require('../core/base'); var Client = exports.Client = function (options) { base.Client.call(this, options); // Allow overriding serversUrl in child classes this.provider = 'amazon'; this.version = (options || {}).version || '2012-04-01'; this.serversUrl = (options || {}).serversUrl || this.serversUrl || 'ec2.amazonaws.com'; if (!this.before) { this.before = []; } }; utile.inherits(Client, base.Client); Client.prototype._toArray = function toArray(obj) { return Array.isArray(obj) ? obj : [obj]; }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
/* * client.js: Base client from which all AWS clients inherit from * * (C) 2012 Nodejitsu Inc. * */ var utile = require('utile'), request = require('request'), base = require('../core/base'); var Client = exports.Client = function (options) { base.Client.call(this, options); // Allow overriding serversUrl in child classes this.provider = 'amazon'; this.version = (options || {}).version || '2012-04-01'; this.serversUrl = (options || {}).serversUrl || this.serversUrl || 'ec2.amazonaws.com'; if (!this.before) { this.before = []; } }; utile.inherits(Client, base.Client); Client.prototype._toArray = function toArray(obj) { if (typeof obj === 'undefined') { return []; } return Array.isArray(obj) ? obj : [obj]; }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
Return empty array when passed `undefined` or `null` in amazon.Client.prototype._toArray
[fix] Return empty array when passed `undefined` or `null` in amazon.Client.prototype._toArray
JavaScript
mit
songanbui/pkgcloud,DonSchenck/pkgcloud,mdsummers/pkgcloud,Hopebaytech/pkgcloud,hacor/pkgcloud,Phanatic/pkgcloud,bunglestink/pkgcloud,apla/pkgcloud,andrewsomething/pkgcloud,dionjwa/pkgcloud,Phanatic/pkgcloud,pkgcloud/pkgcloud,mcanthony/pkgcloud,temka1234/pkgcloud
02b7610b6acc81a911e1bdb055be830f955ad6da
client.js
client.js
Wizard.registerRouter('iron:router', { go: function(name, stepId) { Router.go(name, this.getParams(stepId)); }, getParams: function(stepId) { return Tracker.nonreactive(function() { var route = Router.current() , params = route.params || {}; return _.extend(params, {step: stepId}); }); }, getStep: function() { var current = Router.current(); return current && current.params.step; }, path: function(name, stepId) { return Router.path(name, this.getParams(stepId)); } });
Wizard.registerRouter('iron:router', { go: function(name, stepId) { var p = {}; if( !!this.getParams(stepId).query && $.param(this.getParams(stepId).query) != "" ) p.query = $.param(this.getParams(stepId).query); if( !!this.getParams(stepId).hash ) p.hash = this.getParams(stepId).hash; Router.go(name, this.getParams(stepId), p); }, getParams: function(stepId) { return Tracker.nonreactive(function() { var route = Router.current() , params = route.params || {}; return _.extend(params, {step: stepId}); }); }, getStep: function() { var current = Router.current(); return current && current.params.step; }, path: function(name, stepId) { return Router.path(name, this.getParams(stepId)); } });
Fix for query and hash string consistency in url
Fix for query and hash string consistency in url
JavaScript
mit
forwarder/autoform-wizard-iron-router
df5a7e0a5eaba7e6d49a4507a2763ca4a634b3e8
app/controllers/resources.js
app/controllers/resources.js
import { Controller } from "controllers/controller.js"; import { mapName } from "utils.js"; import { Ajax } from "ajax.js"; export class ResourcesController extends Controller { constructor(base) { super(base); this.model = { selected: "0" }; } /** * Retrieves the list of available resources from the API, then gets columns for each when done */ load(after) { this.ajax.call("") .then(response => { this.model.store = Object.keys(response).map((x, i) => { let out = mapName(x, i); out.columns = []; out.selected = false; return out; }); this.viewModel = new Vue({ el: "#resources", data: this.model, methods: { selectResource: this.selectResource } }); if (after) after(); }); } /** * Returns the resource currently selected by the select#resources element */ getSelected() { return this.model.store[this.model.selected]; } selectResource (i) { $("#table").remove(); $("#btnPrev, #btnNext").prop("disabled", true); $VueDemo.page = 1; } }
import { Controller } from "controllers/controller.js"; import { mapName } from "utils.js"; import { Ajax } from "ajax.js"; export class ResourcesController extends Controller { constructor(base) { super(base); this.model = { selected: "0" }; } /** * Retrieves the list of available resources from the API, then gets columns for each when done */ load(after) { this.ajax.call("") .then(response => { this.model.store = Object.keys(response).map((x, i) => { let out = mapName(x, i); out.columns = []; out.selected = false; return out; }); this.viewModel = new Vue({ el: "#resources", data: this.model, methods: { selectResource: this.selectResource } }); if (after) after(); }); } /** * Returns the resource currently selected by the select#resources element */ getSelected() { return this.model.store[this.model.selected]; } /** * Resets search results when selecting a different resource. */ selectResource (i) { $("#table").remove(); $("#btnPrev, #btnNext").prop("disabled", true); $VueDemo.default.table.page = 1; } }
Reset page number when selecting a different resource
Reset page number when selecting a different resource
JavaScript
mit
marriola/SWAPI-demo,marriola/SWAPI-demo
40004498a04d8e7e87faa69a63b2b69741159045
src/js/select.js
src/js/select.js
'use strict'; import $ from 'jquery'; export default class BasisSelect { constructor() { this.select = $('[data-c="select"]'); this.select.each((i, e) => { const selectWrapper = $(e); const select = selectWrapper.find('select'); const label = selectWrapper.find('[data-c="select__label"]'); label.text(select.children('option:selected').val()); select.on('change', (event) => { label.text(select.val()); }); select.on('focusin', (event) => { selectWrapper.attr('aria-selected', 'true'); }); select.on('focusout', (event) => { selectWrapper.attr('aria-selected', 'false'); }); }); } }
'use strict'; import $ from 'jquery'; export default class BasisSelect { constructor() { this.select = $('[data-c="select"]'); this.select.each((i, e) => { const selectWrapper = $(e); const select = selectWrapper.find('select'); const label = selectWrapper.find('[data-c="select__label"]'); label.text(select.children('option:selected').text()); select.on('change', (event) => { label.text($(select[0].selectedOptions).text()); }); select.on('focusin', (event) => { selectWrapper.attr('aria-selected', 'true'); }); select.on('focusout', (event) => { selectWrapper.attr('aria-selected', 'false'); }); }); } }
Set text of option tag
Set text of option tag When value attribute is set, display after selection becomes value value
JavaScript
mit
sass-basis/basis
8918b858a8d8ab583756bdae3f6ccf2d010a7c8c
src/adjustArgs/extractFromDOM.js
src/adjustArgs/extractFromDOM.js
const numberRegex = /_number$/ export default function extractFromDOM(args) { const targetProperty = 'currentTarget' // If being passed an event with DOM element that has a dataset if (args[0] && args[0][targetProperty] && args[0][targetProperty].dataset) { const event = args[0] const element = event[targetProperty] let values = { value: element.value, checked: element.checked, name: element.name } const { dataset } = element const dataKeys = Object.keys(dataset) // Read values from data- attributes dataKeys.forEach(dataKey => { let value if (numberRegex.test(dataKey)) { // Read and convert value value = parseFloat(dataset[dataKey]) // Strip off _number suffix from final key dataKey = dataKey.replace(numberRegex, '') } else { // Use string value value = dataset[dataKey] } values[dataKey] = value }) // If submitting a form and data-extract is present on the <form> if (event.type === 'submit' && dataset.extract) { event.preventDefault() const { elements } = element // Loop through form elements https://stackoverflow.com/a/19978872 for (let i = 0, element; element = elements[i++];) { // Read value from <input> let value = element.value // Handle <input type='number'> if (element.type != null && element.type.toLowerCase() === 'number') { value = parseFloat(value) } values[element.name] = value } const reset = !!dataset.reset // data-reset if (reset && element.reset) { element.reset() } } // Place extracted dataset values first, followed by original arguments args = [values].concat(args) } return args }
import extractValuesFromDOMEvent from 'awareness/es/extractValuesFromDOMEvent' export default function extractFromDOM(args) { if (args[0]) { const values = extractValuesFromDOMEvent(args[0]) // Place extracted dataset values first, followed by original arguments args = [values].concat(args) } return args }
Use awareness’s event values extraction
Use awareness’s event values extraction
JavaScript
mit
RoyalIcing/react-organism
26e0dfeeb66076d33c83336e4c701417a2e11c35
client/src/components/ArticleCard.js
client/src/components/ArticleCard.js
import React from 'react' import {Link} from 'react-router-dom' function setArticleLink(title) { return encodeURIComponent(title) } const ArticleCard = ({channel, article}) => { return ( <div className="card"> <Link to={`/newsfeed/${channel.source_id}/${setArticleLink(article.title)}`} className="article-link"> <h3>{article.title}</h3> <img src={article.urlToImage} className="image"/> </Link> </div> ) } export default ArticleCard
import React from 'react' import {Link} from 'react-router-dom' function setArticleLink(title) { return encodeURIComponent(title) } const ArticleCard = ({channel, article}) => { return ( <Link to={`/newsfeed/${channel.source_id}/${setArticleLink(article.title)}`} className="article-link"> <div className="card"> <h3>{article.title}</h3> <img src={article.urlToImage} className="image"/> </div> </Link> ) } export default ArticleCard
Refactor link to cover entire card
Refactor link to cover entire card
JavaScript
mit
kevinladkins/newsfeed,kevinladkins/newsfeed,kevinladkins/newsfeed
1a1096598fa72fb308965e4a9854418710038621
src/apiRoutes.js
src/apiRoutes.js
/** * API routes for interacting with the database */ import express from 'express'; const router = express.Router(); router.get("/", function(req, res) { // res.sendFile(__dirname + "/public/index.html"); res.send('API Routes'); }); export default router;
/** * API routes for interacting with the database */ import express from 'express'; import bodyParser from 'body-parser'; import mongoose from 'mongoose'; import User from './data/models/User'; const router = express.Router(); router.get('/', function(req, res) { // res.sendFile(__dirname + "/public/index.html"); res.send('API Routes'); }); // // Dashboard routes for viewing and modifying profile // ----------------------------------------------------------------------------- router.get('/userDetails', (req, res) => { res.send('This is some data'); }); /** * POST to /signup * Creates a user */ router.post('/signup', (req, res) => { console.log(req.body); User.create({ email: req.body.email, password: req.body.password }, (err) => { if (err) { res.send({ status: 'failure' }); } else { res.send({ status: 'success' }); } }) }); export default router;
Set up signup post express route
Set up signup post express route
JavaScript
mit
Keitarokido/tiles,Keitarokido/tiles
e8a0872e2d8a0b28ce8718bc754f205ab289d98f
lib/util/browserManager.js
lib/util/browserManager.js
/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/ /* * Copyright (c) 2014, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. * * */ var SelLib = require('../../arrow_selenium/selLib'), BrowserManager = module.exports = {}, log4js = require("log4js"), logger = log4js.getLogger("BrowserManager"); /** * Open browsers as part of setup * @param browser * @param config * @param capabilities * @param cb */ BrowserManager.openBrowsers = function (browser, config, capabilities, cb) { var selLib = new SelLib(config); selLib.open(browser, capabilities, function(error) { if (error) { logger.error('Error while opening browser ' + browser + ' :' + error); process.exit(1); } else { if (cb) { cb(); } } }); }; /** * Close browsers as part of teardown * close browsers * @param config * @param cb */ BrowserManager.closeBrowsers = function (config, cb) { var selLib = new SelLib(config); selLib.close(function(cb) { if (cb) { cb(); } }); }; module.exports = BrowserManager;
/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/ /* * Copyright (c) 2014, Yahoo! Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. * * */ var SelLib = require('../../arrow_selenium/selLib'), BrowserManager = module.exports = {}, log4js = require("log4js"), logger = log4js.getLogger("BrowserManager"); /** * Open browsers as part of setup * @param browser * @param config * @param capabilities * @param cb */ BrowserManager.openBrowsers = function (browser, config, capabilities, cb) { var selLib = new SelLib(config); // Use default browser if browser not passed if (!browser || browser === null) { browser = config.browser; logger.info('No browser passed. Defaulting to ' + config.browser); } selLib.open(browser, capabilities, function(error) { if (error) { logger.error('Error while opening browser ' + browser + ' :' + error); process.exit(1); } else { if (cb) { cb(); } } }); }; /** * Close browsers as part of teardown * close browsers * @param config * @param cb */ BrowserManager.closeBrowsers = function (config, cb) { var selLib = new SelLib(config); selLib.close(function(cb) { if (cb) { cb(); } }); }; module.exports = BrowserManager;
Use default browser if browser is not passed for reuseSession
Use default browser if browser is not passed for reuseSession
JavaScript
bsd-3-clause
yahoo/arrow,yahoo/arrow,proverma/arrow,proverma/arrow,proverma/arrow,yahoo/arrow
31f32e4a63597ae481d6b23fa5101a23d75148a7
src/components/Filters/Filter.js
src/components/Filters/Filter.js
import React, { Component } from 'react'; import classnames from 'classnames'; class Filter extends Component { constructor(props) { super(props); this.state = { active: false, }; } render() { return ( <div className={classnames('ui-filter')} onClick={() => { this.setState({ active: !this.state.active, }, () => this.props.onChange(this.state.active)); }} > <input type="checkbox" checked={this.state.active} /> {this.props.title} </div> ); } } Filter.propTypes = { title: React.PropTypes.string.isRequired, onChange: React.PropTypes.func.isRequired, }; export default Filter;
import React, { Component } from 'react'; import classnames from 'classnames'; class Filter extends Component { static propTypes = { title: React.PropTypes.string.isRequired, onChange: React.PropTypes.func.isRequired, active: React.PropTypes.bool, }; static defaultProps = { active: false, }; constructor(props) { super(props); const { active } = this.props; this.state = { active, }; } onFilterChange = () => { const { onChange } = this.props; const { active } = this.state; const nextActive = !active; this.setState({ active: nextActive }); onChange(nextActive); } render() { const { title } = this.props; const { active } = this.state; return ( <div className={classnames('ui-filter')} onClick={this.onFilterChange}> <input type="checkbox" checked={active} /> {title} </div> ); } } export default Filter;
Introduce an active prop for filters
Introduce an active prop for filters
JavaScript
mit
wundery/wundery-ui-react,wundery/wundery-ui-react
be292399cd4a6d528fae5b1b5cd0b7443f71f79c
app/validators/date-range.js
app/validators/date-range.js
import moment from 'moment' export default function validateDateRange(options) { return (key, newValue) => { let date = moment(newValue) return date >= moment(options.min) && date <= moment(options.max) } }
import moment from 'moment' export default function validateDateRange(options) { return (key, newValue) => { let date = moment.utc(newValue) return date >= moment.utc(options.min) && date <= moment.utc(options.max) } }
Validate dates using UTC timezone
Validate dates using UTC timezone Fixes #57
JavaScript
mit
opensource-challenge/opensource-challenge-client,opensource-challenge/opensource-challenge-client
ff911f95e7a1b53be6c9e1a1685b6dcf5cc62f73
codebrag-ui/test/common/directives/savingStatus-spec.js
codebrag-ui/test/common/directives/savingStatus-spec.js
ddescribe('Dynamic favicon directive', function() { var $rootScope, $scope, el, $compile; var statusClasses = ['pending', 'success', 'failed']; beforeEach(module('codebrag.common.directives')); beforeEach(inject(function (_$rootScope_, _$compile_) { $compile = _$compile_; $rootScope = _$rootScope_; $scope = $rootScope.$new(); el = angular.element('<span saving-status="status"></span>'); $compile(el)($scope); })); it('should be empty with no status-related class on start', function() { expect(el.text()).toBe(''); statusClasses.forEach(function(clazz) { expect(el.hasClass(clazz)).toBeFalsy(); }) }); it('should show pending with class pending when saving in progress', function() { $scope.status = 'pending'; $scope.$apply(); expect(el.text()).toBe('Saving...'); expect(el.hasClass($scope.status)).toBeTruthy(); }); it('should show success with class success when saving was ok', function() { $scope.status = 'success'; $scope.$apply(); expect(el.text()).toBe('Saved'); expect(el.hasClass($scope.status)).toBeTruthy(); }); });
describe('Saving status indicator directive', function() { var $rootScope, $scope, el, $compile; var statusClasses = ['pending', 'success', 'failed']; beforeEach(module('codebrag.common.directives')); beforeEach(inject(function (_$rootScope_, _$compile_) { $compile = _$compile_; $rootScope = _$rootScope_; $scope = $rootScope.$new(); el = angular.element('<span saving-status="status"></span>'); $compile(el)($scope); })); it('should be empty with no status-related class on start', function() { expect(el.text()).toBe(''); statusClasses.forEach(function(clazz) { expect(el.hasClass(clazz)).toBeFalsy(); }) }); it('should show pending with class pending when saving in progress', function() { $scope.status = 'pending'; $scope.$apply(); expect(el.text()).toBe('Saving...'); expect(el.hasClass($scope.status)).toBeTruthy(); }); it('should show success with class success when saving was ok', function() { $scope.status = 'success'; $scope.$apply(); expect(el.text()).toBe('Saved'); expect(el.hasClass($scope.status)).toBeTruthy(); }); });
Fix - run all tests, not only those for saving status directive.
Fix - run all tests, not only those for saving status directive.
JavaScript
agpl-3.0
cazacugmihai/codebrag,cazacugmihai/codebrag,softwaremill/codebrag,softwaremill/codebrag,softwaremill/codebrag,softwaremill/codebrag,cazacugmihai/codebrag,cazacugmihai/codebrag,cazacugmihai/codebrag
0db4c9a76a63ac417004b0899f43902ffc9aebf0
lib/ribosome.js
lib/ribosome.js
var path = require('path') var tmp = require('tmp') var html = require('./html.js') var pdf = require('./pdf.js') module.exports = ribosome = {} ribosome.translate = function(url, success, error, license) { tmp.dir(function(err, dirPath) { if (err) { error(err) } else { var htmlPath = path.join(dirPath, "tmp.html") var pdfPath = path.join(dirPath, "tmp.pdf") html.save(url, htmlPath, function() { pdf.generate(htmlPath, pdfPath, function(pdfContent) { success(pdfContent) }, function(err) { error(err) }) }, function(err) { error(err) }) } }, license) }
var path = require('path') var tmp = require('tmp') var html = require('./html.js') var pdf = require('./pdf.js') module.exports = ribosome = {} ribosome.translate = function(url, success, error, license) { tmp.dir(function(err, dirPath) { if (err) { error(err) } else { var htmlPath = path.join(dirPath, "tmp.html") var pdfPath = path.join(dirPath, "tmp.pdf") html.save(url, htmlPath, function() { pdf.generate(htmlPath, pdfPath, function(pdfContent) { success(pdfContent) }, function(err) { error(err) }, license) }, function(err) { error(err) }) } }) }
Fix a bug not passing license properly
Fix a bug not passing license properly
JavaScript
apache-2.0
color/ribosome,ColorGenomics/ribosome
cdebb9acdc409af5f55a224f374bc3f25b04877f
app/containers/main/MainContainer.js
app/containers/main/MainContainer.js
import React from 'react' import { Navigation } from 'components' import { connect } from 'react-redux' import { container, innerContainer } from './styles.css' const MainContainer = React.createClass({ render () { // console.log('props', this.props); return ( <div className={container}> <Navigation isAuthed={this.props.isAuthed}/> <div className={innerContainer}> {this.props.children} </div> </div> ) }, }) // function mapStateToProps (state) { // return { // isAuthed: state.isAuthed, // } // } export default connect( (state) => ({isAuthed: state.isAuthed}) )(MainContainer)
import React, { PropTypes } from 'react' import { Navigation } from 'components' import { connect } from 'react-redux' import { container, innerContainer } from './styles.css' const MainContainer = React.createClass({ propTypes: { isAuthed: PropTypes.bool.isRequired, }, render () { // console.log('props', this.props); return ( <div className={container}> <Navigation isAuthed={this.props.isAuthed}/> <div className={innerContainer}> {this.props.children} </div> </div> ) }, }) // function mapStateToProps (state) { // return { // isAuthed: state.isAuthed, // } // } export default connect( (state) => ({isAuthed: state.isAuthed}) )(MainContainer)
Add proptypes, navbar changes on isAuthed true
Add proptypes, navbar changes on isAuthed true
JavaScript
mit
guilsa/ducker,guilsa/ducker
d4a4377e96babe1137e08b281aa774936655383b
fan/views/Checkbox.js
fan/views/Checkbox.js
jsio('from shared.javascript import Class, bind') jsio('import fan.views.Value') exports = Class(fan.views.Value, function(supr){ this._domTag = 'input' this._domType = 'checkbox' this._className += ' Checkbox' this._createContent = function() { supr(this, '_createContent') this._on('change', bind(this, '_checkValue')) this._makeFocusable() } this.setValue = function(value) { if (typeof value == 'undefined') { return } this._element.checked = this._value = value ? true : null } this.createDelayedMethod('_checkValue', function() { var isChecked = this._element.checked this._value = Boolean(isChecked) fin.set(this._itemId, this._property, this._value) }) })
jsio('from shared.javascript import Class, bind') jsio('import fan.views.Value') exports = Class(fan.views.Value, function(supr){ this._domTag = 'input' this._domType = 'checkbox' this._className += ' Checkbox' this._createContent = function() { supr(this, '_createContent') this._on('change', bind(this, '_checkValue')) this._makeFocusable() } this.handleKeyboardSelect = function() { this.setValue(!this._value) fin.set(this._itemId, this._property, this._value) } this.setValue = function(value) { if (typeof value == 'undefined') { return } this._element.checked = this._value = value ? true : null } this.createDelayedMethod('_checkValue', function() { var isChecked = this._element.checked this._value = Boolean(isChecked) fin.set(this._itemId, this._property, this._value) }) })
Handle keyboard select for checkbox views
Handle keyboard select for checkbox views
JavaScript
mit
marcuswestin/Focus
a9dbed5c5a866bb48377e63b8cf1d8b6ac8af165
_site/js/controllers/AnalyzerCtrl.js
_site/js/controllers/AnalyzerCtrl.js
function AnalyzerCtrl($scope, $http, Analyzer, Data){ $scope.analyzer = Analyzer; $scope.data = Data; $scope.atext = {}; $scope.$watch('analyzer.query', function(value){ for (i in $scope.analyzer.analyzers){ $scope.analyze($scope.analyzer.analyzers[i]); } }); $scope.analyze = function(analyzer) { var path = $scope.data.host + "/_analyze?analyzer=" + analyzer; $http.post(path, $scope.analyzer.query) .success(function(response){ var tokens = []; for(i in response.tokens){ tokens.push(response.tokens[i].token); } $scope.analyzer.atext[analyzer] = tokens; }) .error(function(data, status, headers, config){ //console.log(data); }); } }
function AnalyzerCtrl($scope, $http, Analyzer, Data){ $scope.analyzer = Analyzer; $scope.data = Data; $scope.$watch('analyzer.query', function(value){ for (i in $scope.analyzer.analyzers){ $scope.analyze($scope.analyzer.analyzers[i]); } }); $scope.analyze = function(analyzer) { var path = $scope.data.host + "/_analyze?analyzer=" + analyzer; $http.post(path, $scope.analyzer.query) .success(function(response){ var tokens = []; for(i in response.tokens){ tokens.push(response.tokens[i].token); } $scope.analyzer.atext[analyzer] = tokens; }) .error(function(data, status, headers, config){ //console.log(data); }); } }
Remove unused variable in $scope
Remove unused variable in $scope
JavaScript
apache-2.0
polyfractal/elasticsearch-inquisitor,AlphaStaxLLC/elasticsearch-inquisitor,AlphaStaxLLC/elasticsearch-inquisitor,polyfractal/elasticsearch-inquisitor
3a344d3a91172115dca758974ee6608bb67549d3
spec/javascripts/lib/jasmine/conf/init_local_fixtures.js
spec/javascripts/lib/jasmine/conf/init_local_fixtures.js
if(typeof jasmine !== "undefined") { jasmine.getFixtures().fixturesPath = '/spec/javascripts/specs/fixtures'; }
if(typeof jasmine !== "undefined") { jasmine.getFixtures().fixturesPath = '/src/main/javascript/tetra/spec/javascripts/specs/fixtures'; }
Fix local conf for jasmine tests
Fix local conf for jasmine tests
JavaScript
mit
viadeo/tetra,viadeo/tetra
36216b3dc083b9ef0c6d9ce1d2c7cf01848cf120
public/js/url-formatter.js
public/js/url-formatter.js
(function (doc) { "use strict"; var REGEX_URL = /^(https?):\/\/(?:gist|raw)\.github(?:usercontent)?\.com\/([^\/]+\/[^\/]+\/[^\/]+|[0-9A-Za-z-]+\/[0-9a-f]+\/raw)\//i; var devEl = doc.getElementById('url-dev'), prodEl = doc.getElementById('url-prod'), urlEl = doc.getElementById('url'); urlEl.addEventListener('input', function () { var url = urlEl.value.trim(); if (REGEX_URL.test(url)) { urlEl.classList.remove('invalid'); urlEl.classList.add('valid'); devEl.value = encodeURI(url.replace(REGEX_URL, '$1://rawgit.com/$2/')); prodEl.value = encodeURI(url.replace(REGEX_URL, '$1://cdn.rawgit.com/$2/')); } else { urlEl.classList.remove('valid'); if (url.length) { urlEl.classList.add('invalid'); } else { urlEl.classList.remove('invalid'); } devEl.value = ''; prodEl.value = ''; } }, false); devEl.addEventListener('focus', onFocus); prodEl.addEventListener('focus', onFocus); function onFocus(e) { setTimeout(function () { e.target.select(); }, 1); } }(document));
(function (doc) { "use strict"; var REGEX_URL = /^(https?):\/\/(?:gist|raw\.)?github(?:usercontent)?\.com\/([^\/]+\/[^\/]+\/[^\/]+|[0-9A-Za-z-]+\/[0-9a-f]+\/raw)\/(.+)/i; var devEl = doc.getElementById('url-dev'), prodEl = doc.getElementById('url-prod'), urlEl = doc.getElementById('url'); urlEl.addEventListener('input', function () { var url = urlEl.value.trim(); if (REGEX_URL.test(url)) { urlEl.classList.remove('invalid'); urlEl.classList.add('valid'); devEl.value = encodeURI(url.replace(REGEX_URL, '$1://rawgit.com/$2/$3')); prodEl.value = encodeURI(url.replace(REGEX_URL, '$1://cdn.rawgit.com/$2/$3')); } else { urlEl.classList.remove('valid'); if (url.length) { urlEl.classList.add('invalid'); } else { urlEl.classList.remove('invalid'); } devEl.value = ''; prodEl.value = ''; } }, false); devEl.addEventListener('focus', onFocus); prodEl.addEventListener('focus', onFocus); function onFocus(e) { setTimeout(function () { e.target.select(); }, 1); } }(document));
Make the URL formatter friendlier.
Make the URL formatter friendlier.
JavaScript
mit
cnbin/rawgit,rgrove/rawgit,ssddi456/rawgit,rgrove/rawgit,cnbin/rawgit,ssddi456/rawgit,cnbin/rawgit,matsmith/rawgit,gnowxilef/rawgit,raimo/livegit,ddtxra/rawgit,matsmith/rawgit,gnowxilef/rawgit,ssddi456/rawgit,matsmith/rawgit,sereepap2029/rawgit,ddtxra/rawgit,sereepap2029/rawgit,gnowxilef/rawgit,sereepap2029/rawgit,ddtxra/rawgit,raimo/livegit
fad95a6071d39e649916f534f8561bd1fadd8a4a
packages/fela-bindings/src/ThemeProviderFactory.js
packages/fela-bindings/src/ThemeProviderFactory.js
/* @flow */ import { shallowEqual } from 'recompose' import { objectEach } from 'fela-utils' import createTheme from './createTheme' export default function ThemeProviderFactory( BaseComponent: any, renderChildren: Function, statics?: Object ): any { class ThemeProvider extends BaseComponent { theme: Object constructor(props: Object, context: Object) { super(props, context) const previousTheme = !props.overwrite && this.context.theme this.theme = createTheme(props.theme, previousTheme) } componentWillReceiveProps(nextProps: Object): void { if (this.props.theme !== nextProps.theme) { this.theme.update(nextProps.theme) } } shouldComponentUpdate(nextProps: Object): boolean { return shallowEqual(this.props.theme, nextProps.theme) === false } getChildContext(): Object { return { theme: this.theme } } render(): Object { return renderChildren(this.props.children) } } if (statics) { objectEach(statics, (value, key) => { ThemeProvider[key] = value }) } return ThemeProvider }
/* @flow */ import { shallowEqual } from 'recompose' import { objectEach } from 'fela-utils' import createTheme from './createTheme' export default function ThemeProviderFactory( BaseComponent: any, renderChildren: Function, statics?: Object ): any { class ThemeProvider extends BaseComponent { theme: Object constructor(props: Object, context: Object) { super(props, context) const previousTheme = !props.overwrite && this.context.theme this.theme = createTheme(props.theme, previousTheme) } componentWillReceiveProps(nextProps: Object): void { if (shallowEqual(this.props.theme, nextProps.theme) === false) { this.theme.update(nextProps.theme) } } shouldComponentUpdate(nextProps: Object): boolean { return shallowEqual(this.props.theme, nextProps.theme) === false } getChildContext(): Object { return { theme: this.theme } } render(): Object { return renderChildren(this.props.children) } } if (statics) { objectEach(statics, (value, key) => { ThemeProvider[key] = value }) } return ThemeProvider }
Use shallowEqual to prevent false-positive values
Use shallowEqual to prevent false-positive values
JavaScript
mit
derek-duncan/fela,rofrischmann/fela,risetechnologies/fela,risetechnologies/fela,derek-duncan/fela,derek-duncan/fela,derek-duncan/fela,derek-duncan/fela,derek-duncan/fela,risetechnologies/fela,rofrischmann/fela,rofrischmann/fela
ac4df0c99a4ccab30d8f3d242211c0155ebb619f
app/components/x-toggle.js
app/components/x-toggle.js
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'span', theme: 'default', off: 'Off', on: 'On', toggled: false, inputClasses: Ember.observer('themeClass', 'inputCheckbox', function () { var themeClass = this.get('themeClass'); var input = this.get('inputCheckbox'); if (input) { var inputClasses = input.get('classNames') || []; input.set('classNames', inputClasses.concat(['x-toggle', themeClass])); } }).on('init'), themeClass: Ember.computed('theme', function () { var theme = this.get('theme') || 'default'; return 'x-toggle-' + theme; }), generatedId: Ember.computed(function () { return this.get('elementId') + '-x-toggle'; }), wasToggled: Ember.observer('toggled', function () { var toggled = this.get('toggled'); this.sendAction('toggle', toggled); }).on('init') });
import Ember from 'ember'; var observer = Ember.observer; var on = Ember.on; var computed = Ember.computed; export default Ember.Component.extend({ tagName: 'span', theme: 'default', off: 'Off', on: 'On', toggled: false, inputClasses: on('init', observer('themeClass', 'inputCheckbox', function () { var themeClass = this.get('themeClass'); var input = this.get('inputCheckbox'); if (input) { var inputClasses = input.get('classNames') || []; input.set('classNames', inputClasses.concat(['x-toggle', themeClass])); } }), themeClass: computed('theme', function () { var theme = this.get('theme') || 'default'; return 'x-toggle-' + theme; }), generatedId: computed(function () { return this.get('elementId') + '-x-toggle'; }), wasToggled: on('init', observer('toggled', function () { var toggled = this.get('toggled'); this.sendAction('toggle', toggled); }) });
Use local variables to make methods parse easier.
Use local variables to make methods parse easier. * Stash local variables, and use them inline (seems to be easier to read to me). * Do not require function prototype extensions (`Function.prototype.on` was used before).
JavaScript
mit
knownasilya/ember-toggle,knownasilya/ember-toggle,lifegadget/ember-cli-toggle,paulkogel/ember-cli-toggle,lifegadget/ember-cli-toggle,knownasilya/ember-cli-toggle,paulkogel/ember-cli-toggle,knownasilya/ember-cli-toggle
7ff065c62c1d1a1ab0665e4f71967dc9ef5e2c0f
src/app/components/players/player/playerModel.service.js
src/app/components/players/player/playerModel.service.js
export class PlayerModelService { constructor($log, $http, $localStorage, $q, _, playersApi) { 'ngInject'; this.$log = $log; this.$http = $http; this.$localStorage = $localStorage; this.$q = $q; this._ = _; this.playersApi = playersApi; this.model = { player: null }; this.numDrawCards = 7; } insert(data) { let pl = Object.assign({}, { isCurrent: true, cardsInHand: [] }, data ); this.$log.info('insert()', pl, this); this.model.player = pl; this.$localStorage.player = this.model.player; } discard(id) { let cards = this.model.player.cardsInHand; this.$log.info('discard()', id, cards, this); // Remove card from player this._.pull(cards, id); let plData = { cardsInHand: cards, totalCards: cards.length }; this.$log.info('playerModel:cards -> ', plData); return this.playersApi.update(plData, this.model.player.id); } update(data) { Object.assign(this.model.player, data); } }
export class PlayerModelService { constructor($log, $http, $localStorage, $q, _, playersApi) { 'ngInject'; this.$log = $log; this.$http = $http; this.$localStorage = $localStorage; this.$q = $q; this._ = _; this.playersApi = playersApi; this.model = { player: null }; this.numDrawCards = 7; } insert(data) { let pl = Object.assign({}, { isCurrent: true, cardsInHand: [], cardsSelected: [] }, data ); this.$log.info('insert()', pl, this); this.model.player = pl; this.$localStorage.player = this.model.player; } discard(id) { let cards = this.model.player.cardsInHand; this.$log.info('discard()', id, cards, this); // Remove card from player this._.pull(cards, id); let plData = { cardsInHand: cards, totalCards: cards.length }; this.$log.info('playerModel:cards -> ', plData); return this.playersApi.update(plData, this.model.player.id); } update(data) { Object.assign(this.model.player, data); } }
Add 'cardsSelected' property to the PlayerModelService
Add 'cardsSelected' property to the PlayerModelService
JavaScript
unlicense
ejwaibel/squarrels,ejwaibel/squarrels
18f75fe27652ab3c1c9d8cbe53b28e6363ea23e7
api/db/rescue.js
api/db/rescue.js
'use strict' module.exports = function (sequelize, DataTypes) { let Rescue = sequelize.define('Rescue', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, client: { type: DataTypes.STRING, allowNull: true }, codeRed: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, data: { type: DataTypes.JSONB, allowNull: true }, epic: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, open: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, notes: { type: DataTypes.TEXT, allowNull: false, defaultValue: '' }, platform: { type: DataTypes.ENUM('xb', 'pc'), allowNull: true, defaultValue: 'pc' }, quotes: { type: DataTypes.ARRAY(DataTypes.STRING), allowNull: false }, successful: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, system: { type: DataTypes.STRING, allowNull: false, defaultValue: '' } }, { classMethods: { associate: function (models) { Rescue.belongsToMany(models.Rat, { as: 'rats', through: 'RescueRats' }) Rescue.belongsTo(models.Rat, { as: 'firstLimpet' }) } } }) return Rescue }
'use strict' module.exports = function (sequelize, DataTypes) { let Rescue = sequelize.define('Rescue', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, client: { type: DataTypes.STRING, allowNull: true }, codeRed: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, data: { type: DataTypes.JSONB, allowNull: true }, epic: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, open: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, notes: { type: DataTypes.TEXT, allowNull: false, defaultValue: '' }, platform: { type: DataTypes.ENUM('xb', 'pc', 'unknown'), allowNull: true, defaultValue: 'pc' }, quotes: { type: DataTypes.ARRAY(DataTypes.STRING), allowNull: false }, successful: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false }, system: { type: DataTypes.STRING, allowNull: false, defaultValue: '' } }, { classMethods: { associate: function (models) { Rescue.belongsToMany(models.Rat, { as: 'rats', through: 'RescueRats' }) Rescue.belongsTo(models.Rat, { as: 'firstLimpet' }) } } }) return Rescue }
Add back unknown platform type
Add back unknown platform type
JavaScript
bsd-3-clause
FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com
4693d84d058bc1dc79842bbb11e0c9126c59bf4a
app/assets/js/component/Combobox.js
app/assets/js/component/Combobox.js
/** * Created by dungvn3000 on 2/18/14. */ Ext.define('sunerp.component.Combobox', { extend: 'Ext.form.field.ComboBox', alias: 'widget.comboboxx', triggerAction: 'all', forceSelection: true, queryMode: 'local', listeners: { afterRender: function() { this.store.reload(); } }, getSelected: function() { var value = this.getValue(); var record = this.findRecordByValue(value); return record.getData(); } });
/** * Created by dungvn3000 on 2/18/14. */ Ext.define('sunerp.component.Combobox', { extend: 'Ext.form.field.ComboBox', alias: 'widget.comboboxx', triggerAction: 'all', forceSelection: true, queryMode: 'local', config: { modelName: null }, listeners: { afterRender: function() { this.store.reload(); } }, getSelectedData: function() { var value = this.getValue(); var record = this.findRecordByValue(value); return record.getData(); } });
Rename method getSelect to getSelectData. Add config modelName.
Rename method getSelect to getSelectData. Add config modelName.
JavaScript
apache-2.0
SunriseSoftVN/sunerp,SunriseSoftVN/sunerp,SunriseSoftVN/sunerp
304cbd60f2c06ed863ef06ce6bde79b7bb613889
server/src/seeders/20171202141325-existing-memberships.js
server/src/seeders/20171202141325-existing-memberships.js
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Memberships', [ { id: new Sequelize.UUIDV1(), memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'admin', createdAt: new Date(), updatedAt: new Date() }, { id: new Sequelize.UUIDV1(), memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'member', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface) => { return queryInterface.bulkDelete('Memberships', null, {}); } };
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Memberships', [ { id: '047fbd50-2d5a-4800-86f0-05583673fd7f', memberId: '75b936c0-ba72-11e7-84e1-058ffffd96c5', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'admin', createdAt: new Date(), updatedAt: new Date() }, { id: '75ba1746-bc81-47e5-b43f-cc1aa304db84', memberId: '9ee489d0-9c6f-11e7-a4d2-3b6a4940d978', groupId: 'c46ebe90-bd68-11e7-922f-4d48c5331440', userRole: 'member', createdAt: new Date(), updatedAt: new Date() } ], {}); }, down: (queryInterface) => { return queryInterface.bulkDelete('Memberships', null, {}); } };
Fix UUID column error in membership seeder
Fix UUID column error in membership seeder
JavaScript
mit
Philipeano/post-it,Philipeano/post-it
4ef11b0788bcbd870df8da6283878f9e50f867cd
app/transforms/appearance-status.js
app/transforms/appearance-status.js
import DS from 'ember-data'; export default DS.Transform.extend({ deserialize: function(serialized) { var map = { 0: 'New', 7: 'Built', 10: 'Started', 20: 'Finished', 30: 'Verified', }; return map[serialized]; }, serialize: function(deserialized) { var map = { 'New': 0, 'Built': 7, 'Started': 10, 'Finished': 20, 'Verified': 30, }; return map[deserialized]; } });
import DS from 'ember-data'; export default DS.Transform.extend({ deserialize: function(serialized) { var map = { 0: 'New', 7: 'Built', 10: 'Started', 20: 'Finished', 25: 'Variance', 30: 'Verified', }; return map[serialized]; }, serialize: function(deserialized) { var map = { 'New': 0, 'Built': 7, 'Started': 10, 'Finished': 20, 'Variance': 25, 'Verified': 30, }; return map[deserialized]; } });
Add new `variance` state to appearance
Add new `variance` state to appearance
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
00c8e59af411093c58f0673e1959a2edc59e2d24
src/scripts/app/cms/grammarActivities/edit.controller.js
src/scripts/app/cms/grammarActivities/edit.controller.js
'use strict'; module.exports = /*@ngInject*/ function GrammarActivitiesEditCmsCtrl ( $scope, GrammarActivity, $state, _ ) { $scope.grammarActivity = {}; $scope.grammarActivity.concepts = []; GrammarActivity.getOneByIdFromFB($state.params.id).then(function (ga) { $scope.grammarActivity = ga; $scope.grammarActivity.concepts = _.map($scope.grammarActivity.concepts, function(c, k) { c.fb_concept_key = k; return c; }); }); $scope.processGrammarActivityForm = function () { }; };
'use strict'; module.exports = /*@ngInject*/ function GrammarActivitiesEditCmsCtrl ( $scope, GrammarActivity, $state, _, ConceptsFBService ) { $scope.grammarActivity = {}; $scope.grammarActivity.concepts = []; GrammarActivity.getOneByIdFromFB($state.params.id).then(function (ga) { $scope.grammarActivity = ga; $scope.grammarActivity.concepts = _.map($scope.grammarActivity.concepts, function(c, k) { c.fb_concept_key = k; ConceptsFBService.getById(k).then(function (cfb) { if (cfb) { c.concept_level_2 = cfb.concept_level_2; c.concept_level_1 = cfb.concept_level_1; c.concept_level_0 = cfb.concept_level_0; } }); return c; }); }); $scope.processGrammarActivityForm = function () { }; };
Load level 2,1,0 concepts into question model for qs
Load level 2,1,0 concepts into question model for qs
JavaScript
agpl-3.0
ddmck/Quill-Grammar,ddmck/Quill-Grammar,empirical-org/Quill-Grammar,ddmck/Quill-Grammar,empirical-org/Quill-Grammar,empirical-org/Quill-Grammar
16df59f1a7c8df7624fb084891ee2d00587ad489
test/javascripts/unit/double_click_protection_test.js
test/javascripts/unit/double_click_protection_test.js
module("Double click protection", { setup: function(){ this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>'); $('#qunit-fixture').append(this.$form); } }); test('clicking submit input disables the button', function() { GOVUK.doubleClickProtection(); var $submit_tag = this.$form.find('input[type=submit]'); ok(!$submit_tag.prop('disabled')); $submit_tag.on('click', function (e) { e.preventDefault(); ok($submit_tag.prop('disabled')); }); $submit_tag.click(); }); test('clicking submit input creates a hidden input with the same name and value', function() { GOVUK.doubleClickProtection(); var $submit_tag = this.$form.find('input[type=submit]'); $submit_tag.on('click', function (e) { e.preventDefault(); equal($.find('form input[type=hidden][name=input_name][value=Save]').length, 1); }); $submit_tag.click(); });
module("Double click protection", { setup: function(){ this.$form = $('<form action="/go" method="POST"><input type="submit" name="input_name" value="Save" /></form>'); $('#qunit-fixture').append(this.$form); } }); test('clicking submit input disables the button', function() { GOVUK.doubleClickProtection(); var $submit_tag = this.$form.find('input[type=submit]'); ok(!$submit_tag.prop('disabled')); this.$form.on('submit', function (e) { e.preventDefault(); ok($submit_tag.prop('disabled')); }); $submit_tag.click(); }); test('clicking submit input creates a hidden input with the same name and value', function() { GOVUK.doubleClickProtection(); var $submit_tag = this.$form.find('input[type=submit]'); this.$form.on('submit', function (e) { e.preventDefault(); equal($.find('form input[type=hidden][name=input_name][value=Save]').length, 1); }); $submit_tag.click(); });
Fix JS test causing navigation away from tests
Fix JS test causing navigation away from tests
JavaScript
mit
YOTOV-LIMITED/whitehall,alphagov/whitehall,hotvulcan/whitehall,alphagov/whitehall,alphagov/whitehall,YOTOV-LIMITED/whitehall,robinwhittleton/whitehall,ggoral/whitehall,robinwhittleton/whitehall,askl56/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,askl56/whitehall,ggoral/whitehall,askl56/whitehall,alphagov/whitehall,robinwhittleton/whitehall,hotvulcan/whitehall,hotvulcan/whitehall,YOTOV-LIMITED/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,ggoral/whitehall,ggoral/whitehall
02b36658cf08a87717860f7b7de3f08aad92d364
resources/assets/components/CampaignOverview/index.js
resources/assets/components/CampaignOverview/index.js
import React from 'react'; import { map } from 'lodash'; import CampaignTable from '../CampaignTable'; class CampaignOverview extends React.Component { render() { const causeData = this.props; const causeTables = map(causeData, (data, cause) => ( <CampaignTable key={cause} cause={cause} campaigns={data} causeData={causeData} /> )); return <div className="container">{causeTables}</div>; } } export default CampaignOverview;
import React from 'react'; import { map } from 'lodash'; import CampaignTable from '../CampaignTable'; class CampaignOverview extends React.Component { render() { const causeData = this.props; const causeTables = map(causeData, (data, cause) => ( <CampaignTable key={cause} cause={cause || 'Uncategorized'} campaigns={data} causeData={causeData} /> )); return <div className="container">{causeTables}</div>; } } export default CampaignOverview;
Fix missing heading for cause-less campaigns.
Fix missing heading for cause-less campaigns.
JavaScript
mit
DoSomething/rogue,DoSomething/rogue,DoSomething/rogue
136dd3ead528a087571bba104ffde9fe02de44ca
minimal-carousel.js
minimal-carousel.js
function Carousel(settings){ 'use strict'; this.carousel = document.querySelector(settings.carousel || '.carousel'); this.slides = this.carousel.querySelectorAll('ul li'); this.delay = settings.delay || 2.5; this.autoplay = settings.autoplay === undefined ? true : settings.autoplay; this.slides_total = this.slides.length; this.current_slide = -1; if (this.autoplay) { this.play(); } } Carousel.prototype.next = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = (this.current_slide + 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.prev = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = Math.abs(this.current_slide - 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.play = function () { 'use strict'; this.next(); var that = this; if (this.autoplay) { this.interval = setTimeout(function () { that.play(); }, this.delay * 1000); } };
function Carousel(settings){ 'use strict'; settings = settings || {}; this.carousel = document.querySelector(settings.carousel || '.carousel'); this.slides = this.carousel.querySelectorAll('ul li'); this.delay = settings.delay || 2.5; this.autoplay = settings.autoplay === undefined ? true : settings.autoplay; this.slides_total = this.slides.length; this.current_slide = -1; if (this.autoplay) { this.play(); } } Carousel.prototype.next = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = (this.current_slide + 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.prev = function () { 'use strict'; for (var s = 0; s < this.slides.length; s += 1) { this.slides[s].style.display = 'none'; } this.current_slide = Math.abs(this.current_slide - 1) % this.slides.length; this.slides[this.current_slide].style.display = 'block'; }; Carousel.prototype.play = function () { 'use strict'; this.next(); var that = this; if (this.autoplay) { this.interval = setTimeout(function () { that.play(); }, this.delay * 1000); } };
Allow no setting parameter at all.
Allow no setting parameter at all.
JavaScript
mit
jhderojasUVa/minimal-carousel,wecodeio/minimal-carousel,wecodeio/minimal-carousel,jhderojasUVa/minimal-carousel
844342dd5e458e3ac677e5491384526059b69577
models/userModel.js
models/userModel.js
var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); const saltRounds = 10; var userSchema = new mongoose.Schema({ signupDate: { type: Date, default: Date.now }, username: { type: String, required: true }, password: { type: String, required: true }, email: { type: String, required: true }, name: { type: String } }); userSchema.pre('save', function(next) { if (!this.isModified('password')) { return next(); } bcrypt.hash(this.password, saltRounds, function(err, hash) { if (err) { console.log(err); return next(err); } this.password = hash; next(); }.bind(this)); }); userSchema.methods.checkPassword = function(password, cb) { bcrypt.compare(password, this.password, function(err, result) { if (err) { console.log(err); return next(err); } cb(result); }); }; module.exports = mongoose.model('User', userSchema);
var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); const saltRounds = 10; var userSchema = new mongoose.Schema({ signupDate: { type: Date, default: Date.now }, username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String } }); userSchema.pre('save', function(next) { if (!this.isModified('password')) { return next(); } bcrypt.hash(this.password, saltRounds, function(err, hash) { if (err) { console.log(err); return next(err); } this.password = hash; next(); }.bind(this)); }); userSchema.methods.checkPassword = function(password, cb) { bcrypt.compare(password, this.password, function(err, result) { if (err) { console.log(err); return next(err); } cb(result); }); }; module.exports = mongoose.model('User', userSchema);
Add unique index to username and email for Users
Add unique index to username and email for Users
JavaScript
mit
heymanhn/journey-backend
4031aab3317a8932334b8c036517b2330701f06b
addon/-private/closure-action.js
addon/-private/closure-action.js
import Ember from 'ember'; const ClosureActionModule = Ember.__loader.require('ember-routing-htmlbars/keywords/closure-action'); export default ClosureActionModule.ACTION;
import Ember from 'ember'; let ClosureActionModule; if ('ember-htmlbars/keywords/closure-action' in Ember.__loader.registry) { ClosureActionModule = Ember.__loader.require('ember-htmlbars/keywords/closure-action'); } else { ClosureActionModule = Ember.__loader.require('ember-routing-htmlbars/keywords/closure-action'); } export default ClosureActionModule.ACTION;
Fix loading ACTION symbol on canary
Fix loading ACTION symbol on canary
JavaScript
mit
DockYard/ember-functional-helpers,DockYard/ember-functional-helpers
95acc8ea8150029259389d360be4aeeba143e045
blueprints/ember-cli-paint/index.js
blueprints/ember-cli-paint/index.js
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'broccoli-sass', target: '0.6.6' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.7.22' }, { name: 'spinjs', target: '2.0.1' }, { name: 'tooltipster', target: '3.3.0' }, { name: 'trackpad-scroll-emulator', target: '1.0.8' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner",', { after: '"predef": [\n' } ); }.bind(this)); }.bind(this)); } }
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'broccoli-sass', target: '0.6.6' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.9.0' }, { name: 'modernizr', target: '2.8.3' }, { name: 'spinjs', target: '2.0.1' }, { name: 'tooltipster', target: '3.3.0' }, { name: 'trackpad-scroll-emulator', target: '1.0.8' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner",', { after: '"predef": [\n' } ); }.bind(this)); }.bind(this)); } }
Update blueprints to include latest package versions
Update blueprints to include latest package versions
JavaScript
mit
alphasights/ember-cli-paint,alphasights/ember-cli-paint
4ba0fc51dfe71d37fd3ac7937f2d6438f3ce70a9
.eslintrc.js
.eslintrc.js
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "vue" ], "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, }, "sourceType": "module" }, "plugins": [ "vue" ], "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ], "vue/jsx-uses-vars": 2, } };
Add support for JSX *within* .vue files
Add support for JSX *within* .vue files
JavaScript
mit
kepler-12/code-standards
8e275a22aa419297eee0acc5ef65fc0cce4aa3cb
clients/web/test/spec/swaggerSpec.js
clients/web/test/spec/swaggerSpec.js
function jasmineTests() { var jasmineEnv = jasmine.getEnv(); var consoleReporter = new jasmine.ConsoleReporter(); window.jasmine_phantom_reporter = consoleReporter; jasmineEnv.addReporter(consoleReporter); function waitAndExecute() { if (!jasmineEnv.currentRunner().suites_.length) { window.setTimeout(waitAndExecute, 10); return; } jasmineEnv.execute(); } waitAndExecute(); describe('Test the swagger pages', function () { it('Test swagger', function () { waitsFor(function () { return $('li#resource_system.resource').length > 0; }, 'swagger docs to appear'); runs(function () { $('li#resource_system.resource .heading h2 a').click(); }); waitsFor(function () { return $('#system_getVersion:visible').length > 0; }, 'end points to be visible'); runs(function () { $('#system_getVersion h3 a').click(); }); waitsFor(function () { return $('#system_getVersion .sandbox_header input.submit[name="commit"]:visible').length > 0; }, 'version try out button to be visible'); runs(function () { $('#system_getVersion .sandbox_header input.submit[name="commit"]').click(); }); waitsFor(function () { return $('#system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0; }, 'version information was returned'); }); }); } $(function () { $.getScript('/static/built/testing-no-cover.min.js', jasmineTests); });
function jasmineTests() { var jasmineEnv = jasmine.getEnv(); var consoleReporter = new jasmine.ConsoleReporter(); window.jasmine_phantom_reporter = consoleReporter; jasmineEnv.addReporter(consoleReporter); function waitAndExecute() { if (!jasmineEnv.currentRunner().suites_.length) { window.setTimeout(waitAndExecute, 10); return; } jasmineEnv.execute(); } waitAndExecute(); describe('Test the swagger pages', function () { it('Test swagger', function () { waitsFor(function () { return $('li#resource_system.resource').length > 0; }, 'swagger docs to appear'); runs(function () { $('li#resource_system.resource .heading h2 a').click(); }); waitsFor(function () { return $('#system_system_getVersion:visible').length > 0; }, 'end points to be visible'); runs(function () { $('#system_system_getVersion h3 a').click(); }); waitsFor(function () { return $('#system_system_getVersion .sandbox_header input.submit:visible').length > 0; }, 'version try out button to be visible'); runs(function () { $('#system_system_getVersion .sandbox_header input.submit').click(); }); waitsFor(function () { return $('#system_system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0; }, 'version information was returned'); }); }); } $(function () { $.getScript('/static/built/testing-no-cover.min.js', jasmineTests); });
Update web client swagger test for swagger-ui 2.1.4
Update web client swagger test for swagger-ui 2.1.4
JavaScript
apache-2.0
adsorensen/girder,kotfic/girder,data-exp-lab/girder,jbeezley/girder,Kitware/girder,jbeezley/girder,adsorensen/girder,RafaelPalomar/girder,kotfic/girder,girder/girder,sutartmelson/girder,Xarthisius/girder,sutartmelson/girder,sutartmelson/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,data-exp-lab/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,Xarthisius/girder,adsorensen/girder,kotfic/girder,data-exp-lab/girder,adsorensen/girder,RafaelPalomar/girder,RafaelPalomar/girder,girder/girder,sutartmelson/girder,jbeezley/girder,adsorensen/girder,manthey/girder,Xarthisius/girder,kotfic/girder,Kitware/girder,girder/girder,Kitware/girder,Kitware/girder,sutartmelson/girder,Xarthisius/girder,girder/girder,manthey/girder,jbeezley/girder,kotfic/girder,Xarthisius/girder
899d3164f322abce2c287a4a315f82d7ad869cc0
test/num-test.js
test/num-test.js
const chai = require('chai'); const assert = chai.assert; // const stub = require('./support/stub') const Num = require("../lib/num") describe("Num", function(){ context("with calculated attributes", function(){ it("instantiates", function(){ assert.isObject(new Num(10)); }) it('has a decimal attribute', function(){ let num = new Num(10); assert.isAbove(num.decimal, 0) assert.isAtMost(num.decimal, 10) }) it('has a binary attribute', function(){ let num = new Num(10); let decimal = num.decimal assert.equal(num.binary, (decimal >>> 0).toString(2)) }) }) })
const chai = require('chai'); const assert = chai.assert; // const stub = require('./support/stub') const Num = require("../lib/num") describe("Num", function(){ context("with calculated attributes", function(){ it("instantiates", function(){ assert.isObject(new Num(10)); }) it('has a decimal attribute', function(){ let num = new Num(10); assert.isAbove(num.decimal, 0) assert.isAtMost(num.decimal, 10) }) it('has a binary attribute', function(){ let num = new Num(10); let decimal = num.decimal assert.equal(num.binary, (decimal >>> 0).toString(2)) }) }) }) describe("translateToBinary", function(){ it("translate a decimal number to binary", function(){ let num = new Num(2); num.decimal = 2; assert.equal(num.decimal, 2); assert.equal(num.translateToBinary(), 10); }) })
Add test for Num method translating a decimal to binary
Add test for Num method translating a decimal to binary
JavaScript
mit
kjs222/gametime,kjs222/gametime
fcb643f589b4168405bfe6d6b85ee9ad0aa29682
tests/cleanup.js
tests/cleanup.js
/** * @author EmmanuelOlaojo * @since 8/13/16 */ module.exports = function(){ return Promise.all([ utils.dropCollection(TEST_COLLECTION_A) , utils.dropCollection(TEST_COLLECTION_B) ]); };
/** * @author EmmanuelOlaojo * @since 8/13/16 */ module.exports = function(){ return Promise.all([ utils.dropCollection(TEST_COLLECTION_A) , utils.dropCollection(TEST_COLLECTION_B) , utils.dropCollection("fs.files") , utils.dropCollection("fs.chunks") ]); };
Drop files collection after tests
Drop files collection after tests
JavaScript
mit
e-oj/Fawn
5143eb144f27717d152cefd32a3fc1f703d20a72
code/schritte/5-redux/src/Counter.js
code/schritte/5-redux/src/Counter.js
import React from 'react'; import {connect} from 'react-redux'; import {filterGreetings} from './selectors'; const Counter = ({greetings, filteredGreetings}) => ( <div className="Counter">Showing {filteredGreetings.length} of {greetings.length} Greetings</div> ); export default connect( state => ({ greetings: state.greetings, filteredGreetings: filterGreetings(state.greetings, state.filter) }) )(Counter);
import React from 'react'; import {connect} from 'react-redux'; import {filterGreetings} from './selectors'; const Counter = ({greetingCount, filteredGreetingsCount}) => ( <div className="Counter">Showing {filteredGreetingsCount} of {greetingCount} Greetings</div> ); export default connect( state => ({ greetingCount: state.greetings.length, filteredGreetingsCount: filterGreetings(state.greetings, state.filter).length }) )(Counter);
Determine counter numbers in connect
Determine counter numbers in connect
JavaScript
mit
st-he/react-workshop,st-he/react-workshop,DJCordhose/react-workshop,st-he/react-workshop,DJCordhose/react-workshop,DJCordhose/react-workshop,st-he/react-workshop,DJCordhose/react-workshop
eb7727d2922f4eda310318b119fb435bfcfdc00c
common/modules/template100Handler.js
common/modules/template100Handler.js
module.exports = { inputValidator: function (fileInfo, callback) { }, mergeDataWithTemplate: function(data, template, callback) { } }
module.exports = { inputValidator: function (dataInput, callback) { if (dataInput) if (dataInput.header && dataInput.time && dataInput.holding && dataInput.subtitle) return callback(null) return callback(new Error('Input Validation for Dynamic Template Handler 100 Failed')) }, mergeDataWithTemplate: function(data, template, callback) { const cheerio = require('cheerio') const $ = cheerio.load(template) $('FL_Header').text(data.header) $('FL_Holding').text(data.holding) $('FL_Time').text(data.time) $('FL_Subtitle').text(data.subtitle) return callback(null, $.html()) } }
Implement Input Validator and Merge Data for Template100 Handler
Implement Input Validator and Merge Data for Template100 Handler
JavaScript
mit
Flieral/Announcer-Service-LB,Flieral/Announcer-Service-LB
ccc000a58a8c25fdbc5566e7f4bb61b62269078c
lib/control/util/index.js
lib/control/util/index.js
'use strict'; const STATUS_CODES = require('./status-codes'); const Handlers = { allowed(methods) { return (req, res) => { res.set('Allow', methods); res.status(STATUS_CODES.METHOD_NOT_ALLOWED); res.end(); } } }; const Err = (err, req, res, next) => { res.status(500); res.json({error: err.message}); }; module.exports = { Handlers, Err };
'use strict'; const STATUS_CODES = require('./status-codes'); const Handlers = { allowed(methods) { return (req, res) => { res.set('Allow', methods); res.status(STATUS_CODES.METHOD_NOT_ALLOWED); res.end(); } } }; const Err = (err, req, res, next) => { const error = { error: { name: err.name, message: err.message } }; const statusCode = err.statusCode || STATUS_CODES.BAD_REQUEST; // Include response headers if it's a HTTP error if (err.response) { error.error.headers = err.response.headers; } res.status(statusCode); res.json(error); }; module.exports = { Handlers, Err };
Add additional formatting to error handling.
Add additional formatting to error handling.
JavaScript
mit
rapid7/tokend,rapid7/tokend,rapid7/tokend
2deaf95cde707b5b85616f9f3d0167f7af47eed4
src/js/components/single-response-format-editor.js
src/js/components/single-response-format-editor.js
import React, { PropTypes } from 'react' import CodeListSelector from './code-list-selector' import VisHintPicker from './vis-hint-picker' import { updateSingle, newCodeListSingle } from '../actions/response-format' import { connect } from 'react-redux' function SingleResponseFormatEditor( { id, qrId, format: { codeListReference, visHint }, updateSingle, newCodeListSingle, locale }) { return ( <div> <CodeListSelector id={codeListReference} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} /> <VisHintPicker visHint={visHint} locale={locale} select={visHint => updateSingle(id, { visHint})}/> </div> ) } const mapStateToProps = state => ({ qrId: state.appState.questionnaire }) const mapDispatchToProps = { updateSingle, newCodeListSingle } SingleResponseFormatEditor.propTypes = { id: PropTypes.string.isRequired, /** * Id of the current questionnaire */ qrId: PropTypes.string.isRequired, format: PropTypes.object.isRequired, locale: PropTypes.object.isRequired, updateSingle: PropTypes.func.isRequired, newCodeListSingle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(SingleResponseFormatEditor)
import React, { PropTypes } from 'react' import CodeListSelector from './code-list-selector' import VisHintPicker from './vis-hint-picker' import { updateSingle, newCodeListSingle } from '../actions/response-format' import { connect } from 'react-redux' function SingleResponseFormatEditor( { id, qrId, format: { codeListReference, visHint }, updateSingle, newCodeListSingle, locale }) { return ( <div> <CodeListSelector id={codeListReference} title={locale.selectCl} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} /> <VisHintPicker visHint={visHint} locale={locale} select={visHint => updateSingle(id, { visHint})}/> </div> ) } const mapStateToProps = state => ({ qrId: state.appState.questionnaire }) const mapDispatchToProps = { updateSingle, newCodeListSingle } SingleResponseFormatEditor.propTypes = { id: PropTypes.string.isRequired, /** * Id of the current questionnaire */ qrId: PropTypes.string.isRequired, format: PropTypes.object.isRequired, locale: PropTypes.object.isRequired, updateSingle: PropTypes.func.isRequired, newCodeListSingle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(SingleResponseFormatEditor)
Add title for code list selection within single response
Add title for code list selection within single response
JavaScript
mit
InseeFr/Pogues,InseeFr/Pogues,Zenika/Pogues,InseeFr/Pogues,Zenika/Pogues,Zenika/Pogues
789de4ae409cd528c220fce54fab7adc8dae93c2
example/redux/src/modules/forms/index.js
example/redux/src/modules/forms/index.js
/* @flow */ import { Map, fromJS } from 'immutable'; const REGISTER_FORM = 'redux-example/forms/REGISTER_FORM'; const UNREGISTER_FORM = 'redux-example/forms/UNREGISTER_FORM'; const UPDATE_FORM = 'redux-example/forms/UPDATE_FORM'; const initialState = Map({}); /* ************************************************************************** * Reducer * *************************************************************************/ export default function reducer(state = initialState, action) { const { type, payload } = action; switch (type) { case REGISTER_FORM: const initialValues = payload.initialValues ? fromJS(payload.initialValues) : Map({}); return state.set(payload.id, fromJS({ initialValues, currentValues: initialValues, })); case UNREGISTER_FORM: return state.delete(payload); case UPDATE_FORM: return state.setIn(payload.keypath, payload.value); default: return state; } } /* ************************************************************************** * Action Creators * *************************************************************************/ /** * type initialForm = { id: string, initialValues: Object | Map } */ export function registerForm(initialForm) { return { type: REGISTER_FORM, payload: initialForm, }; } /** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) { return { type: UPDATE_FORM, payload: update, }; }
/* @flow */ import { Map, fromJS } from 'immutable'; const REGISTER_FORM = 'redux-example/forms/REGISTER_FORM'; const UNREGISTER_FORM = 'redux-example/forms/UNREGISTER_FORM'; const UPDATE_FORM = 'redux-example/forms/UPDATE_FORM'; const initialState = Map({}); /* ************************************************************************** * Reducer * *************************************************************************/ export default function reducer(state = initialState, action) { const { type, payload } = action; switch (type) { case REGISTER_FORM: const initialValues = payload.initialValues ? fromJS(payload.initialValues) : Map({}); return state.set(payload.id, fromJS({ initialValues, currentValues: initialValues, })); case UNREGISTER_FORM: return state.delete(payload); case UPDATE_FORM: return state.setIn(payload.keypath, payload.value); default: return state; } } /* ************************************************************************** * Action Creators * *************************************************************************/ /** * type initialForm = { id: string, initialValues: Object | Map } */ export function registerForm(initialForm) { return { type: REGISTER_FORM, payload: initialForm, }; } /** * type formId: string */ export function unregisterForm(formId) { return { type: REGISTER_FORM, payload: formId, }; } /** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) { return { type: UPDATE_FORM, payload: update, }; }
Add unregister form action creator
Add unregister form action creator
JavaScript
mit
iansinnott/react-static-webpack-plugin,iansinnott/react-static-webpack-plugin
ada2b9c9152edc91f6199c43b6d8838ba8026f98
server/models/locations.js
server/models/locations.js
const mongoose = require('mongoose') const { Schema } = mongoose const locationSchema = new Schema({ address: { type: String, unique: true, required: true }, rating: Number, reviews: [{rating: Number, content: String, userId: String}], photos: [], description: String, loc: { type: [Number], index: { type: '2dsphere' } } }) const Location = mongoose.model('Location', locationSchema) module.exports = Location
const mongoose = require('mongoose') const { Schema } = mongoose const locationSchema = new Schema({ address: { type: String, unique: true, required: true }, rating: { type: Number, default: 0 }, reviews: [{rating: Number, content: String, userId: String}], photos: [], description: String, loc: { type: [Number], index: { type: '2dsphere' } } }) const Location = mongoose.model('Location', locationSchema) module.exports = Location
Adjust location model to have default rating of 0
Adjust location model to have default rating of 0
JavaScript
mit
JabroniZambonis/pLot
528675ccbd0ea2cb182152c2efdd284c81c2b5ce
src/scripts/feature/dateTime/dateTimeController.js
src/scripts/feature/dateTime/dateTimeController.js
(function() { 'use strict'; angular.module('app.feature.dateTime').controller('DateTimeController', [ '$scope', '$interval', function($scope, $interval) { $interval(function() { $scope.dateTime = Date.now(); }, 1000); } ]); })();
(function() { 'use strict'; angular.module('app.feature.dateTime').controller('DateTimeController', [ '$scope', '$interval', function($scope, $interval) { // Set the current date and time on startup $scope.dateTime = Date.now(); // And afterwards every second in an endless loop $interval(function() { $scope.dateTime = Date.now(); }, 1000); } ]); })();
Set current date and time before starting the interval service
Set current date and time before starting the interval service - The interval service does not start immediately, instead it waits the configured amount of time before it runs the code that is declared inside the callback function.
JavaScript
mit
molehillrocker/mm-website,molehillrocker/mm-website
eb4366ca475f12871ad6be067433aa8011704224
lib/libra2/app/assets/javascripts/remove_download_link.js
lib/libra2/app/assets/javascripts/remove_download_link.js
(function() { "use strict"; function initPage() { // The thumbnail images on the show page are links, but the links aren't correct, so remove the links. // The html looks something like the following, but it varies depending on the type of media it is: // <a target="_new" title="Download the full-sized PDF" href="/downloads/xxxxxxxxxx"> // <figure> // <img class="img-responsive" alt="Download the full-sized PDF of zzzzzzzzzz.pdf" src="/downloads/xxxxxxxxxx?file=thumbnail"> // <figcaption>Download the full-sized PDF</figcaption> // </figure> // </a> var downloadArea = $('.thesis-thumbnail'); if (downloadArea.length > 0) {// If we are on the show page. var links = downloadArea.find("a"); links.removeAttr("href"); links.removeAttr("title"); links.removeAttr("target"); var captions = downloadArea.find("figcaption"); captions.remove(); } } $(window).bind('page:change', function() { initPage(); }); })();
(function() { "use strict"; function initPage() { // The thumbnail images on the show page are links, but the links aren't correct, so remove the links. // The html looks something like the following, but it varies depending on the type of media it is: // <a target="_new" title="Download the full-sized PDF" href="/downloads/xxxxxxxxxx"> // <figure> // <img class="img-responsive" alt="Download the full-sized PDF of zzzzzzzzzz.pdf" src="/downloads/xxxxxxxxxx?file=thumbnail"> // <figcaption>Download the full-sized PDF</figcaption> // </figure> // </a> var downloadArea = $('.thesis-thumbnail'); if (downloadArea.length > 0) {// If we are on the show page. var links = downloadArea.find("a"); links.removeAttr("href"); links.removeAttr("title"); links.removeAttr("target"); var captions = downloadArea.find("figcaption"); captions.remove(); var img = downloadArea.find("img"); if (img.length > 0) { var alt = img.attr("alt"); alt = alt.replace(/Download/, ""); img.attr("alt", alt); } } } $(window).bind('page:change', function() { initPage(); }); })();
Remove the word "download" from the thumbnail alt text.
Remove the word "download" from the thumbnail alt text.
JavaScript
apache-2.0
uvalib/Libra2,uvalib/Libra2,uvalib/Libra2,uvalib/Libra2,uvalib/Libra2
093005bfd926fdae42706e0554ad1a985196d9d7
lib/template/fs-loader.js
lib/template/fs-loader.js
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var nunjucks = require('nunjucks'); /* Nunjucks loader similar to FileSystemLoader, but avoid infinite looping */ var Loader = nunjucks.Loader.extend({ init: function(searchPaths) { this.searchPaths = searchPaths.map(path.normalize); }, getSource: function(fullpath) { fullpath = this.resolve(null, fullpath); if(!fullpath) { return null; } return { src: fs.readFileSync(fullpath, 'utf-8'), path: fullpath, noCache: true }; }, resolve: function(from, to) { var resultFolder = _.find(this.searchPaths, function(basePath) { var p = path.resolve(basePath, to); return ( p.indexOf(basePath) === 0 && p != from && fs.existsSync(p) ); }); return path.resolve(resultFolder, to); } }); module.exports = Loader;
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var nunjucks = require('nunjucks'); /* Nunjucks loader similar to FileSystemLoader, but avoid infinite looping */ function isRelative(filename) { return (filename.indexOf('./') === 0 || filename.indexOf('../') === 0); } var Loader = nunjucks.Loader.extend({ init: function(searchPaths) { this.searchPaths = searchPaths.map(path.normalize); }, getSource: function(fullpath) { if (!fullpath) return null; fullpath = this.resolve(null, fullpath); if(!fullpath) { return null; } return { src: fs.readFileSync(fullpath, 'utf-8'), path: fullpath, noCache: true }; }, // We handle absolute paths ourselves in ".resolve" isRelative: function() { return true; }, resolve: function(from, to) { // Relative template like "./test.html" if (isRelative(to) && from) { return path.resolve(path.dirname(from), to); } // Absolute template to resolve in root folder var resultFolder = _.find(this.searchPaths, function(basePath) { var p = path.resolve(basePath, to); return ( p.indexOf(basePath) === 0 && p != from && fs.existsSync(p) ); }); if (!resultFolder) return null; return path.resolve(resultFolder, to); } }); module.exports = Loader;
Fix FSLoader for relative paths
Fix FSLoader for relative paths
JavaScript
apache-2.0
tshoper/gitbook,strawluffy/gitbook,gencer/gitbook,tshoper/gitbook,GitbookIO/gitbook,ryanswanson/gitbook,gencer/gitbook
28ea49920beb7ad6ed4e3c3a9552fa6dabf931e7
client/app/js/crypto/main.js
client/app/js/crypto/main.js
angular.module('GLBrowserCrypto', []) .factory('glbcProofOfWork', ['$q', function($q) { // proofOfWork return the answer to the proof of work // { [challenge string] -> [ answer index] } var str2Uint8Array = function(str) { var result = new Uint8Array(str.length); for (var i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; }; var getWebCrypto = function() { if (typeof window !== 'undefined') { if (window.crypto) { return window.crypto.subtle || window.crypto.webkitSubtle; } if (window.msCrypto) { return window.msCrypto.subtle; } } }; return { proofOfWork: function(str) { var deferred = $q.defer(); var work = function(i) { var hashme = str2Uint8Array(str + i); var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme); var xxx = function (hash) { hash = new Uint8Array(hash); if (hash[31] === 0) { deferred.resolve(i); } else { work(i + 1); } } if (damnIE.then !== undefined) { damnIE.then(xxx); } else { damnIE.oncomplete = function(r) { xxx(r.target.result); }; } } work(0); return deferred.promise; } }; }]);
angular.module('GLBrowserCrypto', []) .factory('glbcProofOfWork', ['$q', function($q) { // proofOfWork return the answer to the proof of work // { [challenge string] -> [ answer index] } var str2Uint8Array = function(str) { var result = new Uint8Array(str.length); for (var i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; }; var getWebCrypto = function() { if (typeof window !== 'undefined') { if (window.crypto) { return window.crypto.subtle || window.crypto.webkitSubtle; } if (window.msCrypto) { return window.msCrypto.subtle; } } }; return { proofOfWork: function(str) { var deferred = $q.defer(); var i; var xxx = function (hash) { hash = new Uint8Array(hash); if (hash[31] === 0) { deferred.resolve(i); } else { i += 1; work(); } } var work = function() { var hashme = str2Uint8Array(str + i); var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme); if (damnIE.then !== undefined) { damnIE.then(xxx); } else { damnIE.oncomplete = function(r) { xxx(r.target.result); }; } } work(); return deferred.promise; } }; }]);
Remove function definition from proof of work recursion
Remove function definition from proof of work recursion
JavaScript
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
376e79a26e4e3c3886168d6e7bf3f2b2653a0162
app/assets/javascripts/form.js
app/assets/javascripts/form.js
$(document).ready(function() { $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") }; }); }); });
$(document).ready(function() { $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { $('.results').empty() for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") }; }); }); });
Clear results before loading new results
Clear results before loading new results
JavaScript
mit
tonysuaus/projectz,tonysuaus/projectz
b55a6f35084d0291d004e64a2b6b2ae68f08f4ad
snippet.js
snippet.js
// MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { version: "1.0", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. log: function(msg) { if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } document.body.insertAdjacentHTML( 'beforeend', '<p style="font-family: monospace; margin: 2px 0 2px 0">' + msg.replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</p>' ); }, // Writes out the given HTML at the end of the body, // exactly as-is logHTML: function(html) { document.body.insertAdjacentHTML("beforeend", html); } };
// MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { version: "1.1", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. log: function(msg, tag) { var elm = document.createElement(tag || "p"); elm.style.fontFamily = "monospace"; elm.style.margin = "2px 0 2px 0"; if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } elm.innerHTML = msg.replace(/&/g, '&amp;').replace(/</g, '&lt;'); document.body.appendChild(elm); }, // Writes out the given HTML at the end of the body, // exactly as-is logHTML: function(html) { document.body.insertAdjacentHTML("beforeend", html); } };
Add the ability to specify a tag
Add the ability to specify a tag
JavaScript
mit
tjcrowder/simple-snippets-console,tjcrowder/simple-snippets-console
3ad0835f36c87cdbb6e66528177e1a1413d0c113
test/integration/test/integration-mocha-setup.js
test/integration/test/integration-mocha-setup.js
const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const td = require('testdouble') const tdChai = require('testdouble-chai') chai.use(chaiAsPromised) chai.use(tdChai(td)) chai.config.includeStack = true chai.config.showDiff = false global.expect = chai.expect // if any unhandled rejections happen in promises, treat them as fatal errors process.on('unhandledRejection', function(err) { throw err }) // if there are any PropType warnings from React, treat them as fatal errors const realLogger = console.error console.error = function error(...args) { const msg = args.join(' ') if (~msg.indexOf('Failed prop type')) { throw new Error(msg) } else { return realLogger(...args) } }
const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const td = require('testdouble') const tdChai = require('testdouble-chai') chai.use(chaiAsPromised) chai.use(tdChai(td)) chai.config.includeStack = true chai.config.showDiff = false global.expect = chai.expect // if any unhandled rejections happen in promises, treat them as fatal errors process.on('unhandledRejection', function(err) { throw err })
Fix build error on node v4
Fix build error on node v4
JavaScript
mit
mwolson/jazzdom
76c08bcda29127a7e06c41c979854930217d36af
config/webpack-dev-server.config.js
config/webpack-dev-server.config.js
const path = require('path'); module.exports = { entry: [ path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'), path.resolve(process.cwd(), 'src/theme/assets/main.js') ], output: { publicPath: 'http://localhost:8080/_assets/', filename: '[name].js', chunkFilename: '[id].js' }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader?importLoaders=1&minimize=true', 'postcss-loader' ] }, { test: /\.(gif|png|jpe?g|svg)(\?.+)?$/, use: ['url-loader'] }, { test: /\.(eot|ttf|woff|woff2)(\?.+)?$/, use: ['url-loader'] } ] }, devtool: 'eval', devServer: { publicPath: 'http://localhost:8080/_assets/' } };
const path = require('path'); module.exports = { entry: [ path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'), path.resolve(process.cwd(), 'src/theme/assets/main.js') ], output: { publicPath: 'http://localhost:8080/_assets/', filename: '[name].js', chunkFilename: '[id].js' }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader?importLoaders=1&minimize=true', 'postcss-loader' ] }, { test: /\.(gif|png|jpe?g|svg)(\?.+)?$/, use: ['url-loader'] }, { test: /\.(eot|ttf|woff|woff2)(\?.+)?$/, use: ['url-loader'] } ] }, devtool: 'eval', devServer: { publicPath: 'http://localhost:8080/_assets/', headers: { 'Access-Control-Allow-Origin': '*' } } };
Add cors headers to dev server responses
Add cors headers to dev server responses
JavaScript
mit
jsor-labs/website,jsor-labs/website
16cb0348dab24ef26c98b4992aa2d04f73f4d525
components/ClickableImage.js
components/ClickableImage.js
import React, { Component } from 'react'; import { TouchableOpacity, Image, View } from 'react-native'; import styles from './styles/ClickableImageStyle'; import PropTypes from 'prop-types'; import { StackNagivator } from 'react-navigation'; import FadeInView from '../animations/FadeInView'; export default class ClickableImage extends Component { static propTypes = { onPress: PropTypes.func, text: PropTypes.object, children: PropTypes.object, navigation: PropTypes.object } render() { return ( <View> <FadeInView> <TouchableOpacity style={styles.touchableSize} activeOpacity={.85} onPress={this.props.onPress}> <Image style={styles.image} source={this.props.text} /> </TouchableOpacity> </FadeInView> </View> ) } }
import React, { Component } from 'react'; import { TouchableOpacity, Image, View } from 'react-native'; // import styles from './styles/ClickableImageStyle'; import PropTypes from 'prop-types'; import { StackNagivator } from 'react-navigation'; import FadeInView from '../animations/FadeInView'; export default class ClickableImage extends Component { static propTypes = { onPress: PropTypes.func, text: PropTypes.object, children: PropTypes.object, navigation: PropTypes.object, imageStyle: Image.propTypes.style, touchStyle: View.propTypes.style } render() { return ( <View> <FadeInView> <TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress}> <Image style={this.props.imageStyle} source={this.props.text} /> </TouchableOpacity> </FadeInView> </View> ) } }
Change clickableimage to allow it to take styles when a new component is called elsewhere
Change clickableimage to allow it to take styles when a new component is called elsewhere
JavaScript
mit
fridl8/cold-bacon-client,fridl8/cold-bacon-client,fridl8/cold-bacon-client
17b8376c523ea0e537abb91760fd25d866a3abfd
app/scripts/login.babel.js
app/scripts/login.babel.js
/** * * Meet-Up Event Planner * Copyright 2015 Justin Varghese John All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * */ /* eslint-env browser */ 'use strict'; var firebase = new Firebase("https://meet-up-event-planner.firebaseio.com"); let emailInput = document.querySelector('input[name="email"]'); let passwordInput = document.querySelector('input[name="password"]'); let submit = document.querySelector('button[type="submit"]'); submit.onclick = function() { event.preventDefault(); firebase.authWithPassword({ email : emailInput.value, password : passwordInput.value }, function(error, authData) { if (error) { console.log("Login Failed!", error); } else { console.log("Authenticated successfully with payload:", authData); } }); };
/** * * Meet-Up Event Planner * Copyright 2015 Justin Varghese John All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * */ /* eslint-env browser */ 'use strict'; var firebase = new Firebase("https://meet-up-event-planner.firebaseio.com"); let emailInput = document.querySelector('input[name="email"]'); let passwordInput = document.querySelector('input[name="password"]'); let submit = document.querySelector('button[type="submit"]'); submit.onclick = function() { event.preventDefault(); firebase.authWithPassword({ email : emailInput.value, password : passwordInput.value }, function(error, authData) { if (error) { console.log("Login Failed!", error); } else { console.log("Authenticated successfully with payload:", authData); window.location.href = '/create-event.html'; } }); };
Add redirect after successful login
Add redirect after successful login
JavaScript
apache-2.0
johnjv/meet-up-event-planner,johnjv/meet-up-event-planner
fb5275af0191c5ec9532f21c19f400b9798fba2f
angular-stomp.js
angular-stomp.js
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = Stomp.client('http://localhost:15674/stomp'); return { subscribe: function(queue, callback) { stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) }, send: function(queue, headers, data) { stompClient.send(queue, headers, data); }, connect: function(user, password, on_connect, on_error, vhost) { stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); }, disconnect: function(callback) { stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } } // function NGStomp(url, socketClass) { // Stomp.WebSocketClass = socketClass; // var stompClient = Stomp.client(url); // } });
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = {}; function NGStomp(url) { this.stompClient = Stomp.client(url); } NGStomp.prototype.subscribe = function(queue, callback) { this.stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) } NGStomp.prototype.send = function(queue, headers, data) { this.stompClient.send(queue, headers, data); } NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) { this.stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); } NGStomp.prototype.disconnect = function(callback) { this.stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } return function(url) { return new NGStomp(url); } });
Update to allow the url to be passed into a constructor for the service (the service returns a constructor).
Update to allow the url to be passed into a constructor for the service (the service returns a constructor).
JavaScript
apache-2.0
davinkevin/AngularStompDK
cbc42df4304d209f788fb9edc2688ee538c7470e
assets/js/ads.js
assets/js/ads.js
/** * This file is intended to detect active ad blocker. * * Ad blockers block URLs containing the word "ads" including this file. * If the file does load, `googlesitekit.canAdsRun` is set to true. */ global.googlesitekit = global.googlesitekit || {}; global.googlesitekit.canAdsRun = true; // Ensure that this flag does not get wiped at a later stage during pageload. document.addEventListener( 'DOMContentLoaded', function() { global.googlesitekit.canAdsRun = true; } );
/** * This file is intended to detect active ad blocker. * * Ad blockers block URLs containing the word "ads" including this file. * If the file does load, `googlesitekit.canAdsRun` is set to true. */ if ( global.googlesitekit === undefined ) { global.googlesitekit = {}; } global.googlesitekit.canAdsRun = true; // Ensure that this flag does not get wiped at a later stage during pageload. document.addEventListener( 'DOMContentLoaded', function() { global.googlesitekit.canAdsRun = true; } );
Tidy up check for Site Kit global.
Tidy up check for Site Kit global.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
aaaaa76705e996cad798ec0d964b78434a87e621
spec/dev/scheduler.spec.js
spec/dev/scheduler.spec.js
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const Scheduler = require("../../lib/scheduler"); const fsWatcher = require("../../lib/fs-watcher"); const MockInspector = require("../mock/file-tree-inspector"); const Ticker = require("../mock/ticker"); let scheduler = null; let ticker = null; let fakeFS = null; describe("in a mocked environment", () => { beforeEach(() => { let mockObj = MockInspector(); ticker = Ticker(); fakeFS = mockObj.fs; scheduler = Scheduler( {"watcher": fsWatcher({"tick": ticker.tick, "inspector": mockObj.inspector})}); }); it("does nothing when given nothing", done => { scheduler({}).then(() => { done(); }, error => { expect(error).toBe("not an error"); done(); }); }); });
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const Scheduler = require("../../lib/scheduler"); const fsWatcher = require("../../lib/fs-watcher"); const MockInspector = require("../mock/file-tree-inspector"); const Ticker = require("../mock/ticker"); let scheduler = null; let ticker = null; let fakeFS = null; let taskSpy = function(find) { let task = {}; task.pwd = ""; task.events = []; task.find = () => new Promise(function(resolve, reject) { resolve(find()); }); task.move = files => new Promise(function(resolve, reject) { task.events.push(["move", files]); }); task.run = wd => new Promise(function(resolve, reject) { task.events.push(["run", wd]); }); return task; }; describe("in a mocked environment", () => { beforeEach(() => { let mockObj = MockInspector(); ticker = Ticker(); fakeFS = mockObj.fs; scheduler = Scheduler( {"watcher": fsWatcher({"tick": ticker.tick, "inspector": mockObj.inspector})}); }); it("does nothing when given nothing", done => { scheduler({}).then(() => { done(); }, error => { expect(error).toBe("not an error"); done(); }); }); });
Create untested (so far) task spy
:art: Create untested (so far) task spy
JavaScript
bsd-3-clause
daaang/awful-mess
abfcaf9e91eb8ca9976d6c7055bbca4086a9c5b2
Gruntfile.js
Gruntfile.js
// Configuration module.exports = function(grunt) { // Initialize config grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), }); // Load required tasks from submodules grunt.loadTasks('grunt'); // Default grunt.registerTask('default', [ 'connect', 'localtunnel', 'watch' ]); // Testing grunt.registerTask('test', [ 'htmlhint', 'jshint', 'scsslint' ]); // Staging grunt.registerTask('stage', [ 'clean:deploy', 'fontello:build', 'assemble:stage', 'copy:stage', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); // Deployment grunt.registerTask('deploy', [ 'clean:deploy', 'fontello:build', 'assemble:deploy', 'copy:deploy', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); };
// Configuration module.exports = function(grunt) { // Initialize config grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), }); // Load required tasks from submodules grunt.loadTasks('grunt'); // Default task grunt.registerTask('default', ['dev']); // Development grunt.registerTask('dev', [ 'connect', 'localtunnel', 'watch' ]); // Testing grunt.registerTask('test', [ 'htmlhint', 'jshint', 'scsslint' ]); // Staging grunt.registerTask('stage', [ 'clean:deploy', 'fontello:build', 'assemble:stage', 'copy:stage', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); // Deployment grunt.registerTask('deploy', [ 'clean:deploy', 'fontello:build', 'assemble:deploy', 'copy:deploy', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); };
Make it easier to change the default Grunt task
Make it easier to change the default Grunt task
JavaScript
mit
yellowled/yl-bp,yellowled/yl-bp
e5f5593a922593bf8333c4704e35546c4a57b1c2
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", destinationFolder: process.env["JOB_NAME"] ? "<%= movePackageTo %>\\<%= jobName %>\\<%= grunt.template.today('yyyy-mm-dd') %> #<%= buildNumber %>" : "<%= movePackageTo %>", compress: { main: { options: { archive: "<%= destinationFolder %>\\Telerik AppBuilder.zip" }, files: [ { src: ["**/*.{py,pyd,so}", "*.{sublime-keymap,sublime-menu,sublime-settings}", "LICENSE"] } ] } }, clean: { src: ["**/*.pyc"] } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", "compress:main"); }
module.exports = function(grunt) { grunt.initConfig({ copyPackageTo: "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package", movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", destinationFolder: process.env["JOB_NAME"] ? "<%= movePackageTo %>\\<%= jobName %>\\<%= grunt.template.today('yyyy-mm-dd') %> #<%= buildNumber %>" : "<%= movePackageTo %>", compress: { main: { options: { archive: "<%= destinationFolder %>\\Telerik AppBuilder.zip" }, files: [ { src: ["**/*.{py,pyd,so}", "*.{sublime-keymap,sublime-menu,sublime-settings}", "LICENSE"] } ] } }, copy: { package_to_qa_drop_folder: { src: "*.zip", dest: "<%= copyPackageTo %>/<%= jobName %>/Telerik AppBuilder.zip" } }, clean: { src: ["**/*.pyc"] } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", "compress:main"); }
Copy built package to QA Folder
Copy built package to QA Folder
JavaScript
apache-2.0
Icenium/appbuilder-sublime-package,dimitardanailov/appbuilder-sublime-package,dimitardanailov/appbuilder-sublime-package,Icenium/appbuilder-sublime-package
71ef5ba237e6fa75eca9b64877faba452fbcd973
Gruntfile.js
Gruntfile.js
/* * grunt-check-pages * https://github.com/DavidAnson/grunt-check-pages * * Copyright (c) 2014 David Anson * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration grunt.initConfig({ // Linting jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, // Unit tests nodeunit: { tests: ['test/*_test.js'] } }); // Load this plugin's task grunt.loadTasks('tasks'); // Load required plugins grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Default: Test and lint grunt.registerTask('default', ['nodeunit', 'jshint']); };
/* * grunt-check-pages * https://github.com/DavidAnson/grunt-check-pages * * Copyright (c) 2014 David Anson * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration grunt.initConfig({ // Linting jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, // Unit tests nodeunit: { tests: ['test/*_test.js'] } }); // Load required plugins grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Default: Test and lint grunt.registerTask('default', ['nodeunit', 'jshint']); };
Remove unnecessary call to loadTasks.
Remove unnecessary call to loadTasks.
JavaScript
mit
DavidAnson/grunt-check-pages,DavidAnson/grunt-check-pages,DavidAnson/check-pages,Flimm/check-pages,Flimm/check-pages,DavidAnson/check-pages
27486485c9f5821d76090a75f05d5d27991cdf48
client/request.js
client/request.js
/* istanbul ignore file */ const http = require('http') module.exports = function httpRequest(body) { return new Promise((resolve, reject) => { const request = http.request( { hostname: 'server', port: 8653, path: '/graphql', method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', Accept: 'application/json', 'X-Requested-With': 'Node.js', }, }, response => { let xbody = '' response.setEncoding('utf8') response.on('data', d => { xbody += d }) response.on('end', () => { const { statusCode } = response if (statusCode < 400 && statusCode >= 200) { resolve(JSON.parse(xbody)) } else { reject(JSON.parse(xbody)) } }) } ) request.write(body) request.end() }) }
/* istanbul ignore file */ const http = require('http') function parseJSON(data) { try { return JSON.parse(data) } catch (e) { return data } } module.exports = function httpRequest(body) { return new Promise((resolve, reject) => { const request = http.request( { hostname: 'server', port: 8653, path: '/graphql', method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', Accept: 'application/json', 'X-Requested-With': 'Node.js', }, }, response => { let xbody = '' response.setEncoding('utf8') response.on('data', d => { xbody += d }) response.on('end', () => { const { statusCode } = response if (statusCode < 400 && statusCode >= 200) { resolve(parseJSON(xbody)) } else { reject(parseJSON(xbody)) } }) } ) request.write(body) request.end() }) }
Update to handle when response isnt json
Update to handle when response isnt json
JavaScript
apache-2.0
heiskr/sagefy,heiskr/sagefy,heiskr/sagefy,heiskr/sagefy
7b13a9fda936503e476fd9a5aa5ac92146fdb5ed
backbone-once.js
backbone-once.js
(function(Backbone) { _.extend(Backbone.Events, { // Bind an event only once. When executed for the first time, it would // remove itself from the callbacks list. once: function(events, callback, context) { var boundOff = _.bind(this.off, this); var oneOffCallback = function() { boundOff(events, oneOffCallback); callback.apply(context, arguments); }; return this.on(events, oneOffCallback); } }); // Mix `Backbone.Events` again so our `once` method gets picked up. By the // time the classes first mixed `Backbone.Events`, it was not defined. _.each(['Model', 'Collection', 'Router', 'View', 'History'], function(kind) { _.extend(Backbone[kind].prototype, Backbone.Events); }); }).call(this, Backbone);
(function(Backbone) { _.extend(Backbone.Events, { // Bind an event only once. When executed for the first time, it would // remove itself from the callbacks list. once: function(events, callback, context) { var boundOff = _.bind(this.off, this); var oneOffCallback = _.once(function() { boundOff(events, oneOffCallback); callback.apply(context, arguments); }); return this.on(events, oneOffCallback, context); } }); // Mix `Backbone.Events` again so our `once` method gets picked up. By the // time the classes first mixed `Backbone.Events`, it was not defined. _.each(['Model', 'Collection', 'Router', 'View', 'History'], function(kind) { _.extend(Backbone[kind].prototype, Backbone.Events); }); }).call(this, Backbone);
Fix a multiple execution in event handlers
Fix a multiple execution in event handlers As a bonus, also bind to the context, even if not used, to allow the handler to be unbound using the context too.
JavaScript
mit
gsamokovarov/backbone-once
bda47cb62117f4f29a7e633abaa01e06b21a100e
src/TodoApp/AddTodoForm.js
src/TodoApp/AddTodoForm.js
import React from 'react'; export default class AddTodoForm extends React.Component { static propTypes = { onSubmit: React.PropTypes.func.isRequired } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref="newTodo"></input> <input type="submit" value="Add"></input> </form> ); } handleSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.refs.newTodo.value); this.refs.newTodo.value = ''; } }
import React from 'react'; export default class AddTodoForm extends React.Component { static propTypes = { onSubmit: React.PropTypes.func.isRequired } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref="newTodo" style={style}></input> <input type="submit" value="Add"></input> </form> ); } handleSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.refs.newTodo.value); this.refs.newTodo.value = ''; } } const style = { width: '200px', marginRight: '5px' };
Make input wider and spaced out more
Make input wider and spaced out more
JavaScript
cc0-1.0
ksmithbaylor/react-todo-list,ksmithbaylor/react-todo-list
16ad51fa278a7c6751b204d04c18a0e5357beea9
tests/unit/services/json-schema-draft4/required-test.js
tests/unit/services/json-schema-draft4/required-test.js
// https://github.com/json-schema/JSON-Schema-Test-Suite/blob/develop/tests/draft4/required.json var scenerios = [ { "description": "required validation", "schema": { "properties": { "foo": {}, "bar": {} }, "required": ["foo"] }, "tests": [ { "description": "present required property is valid", "data": {"foo": 1}, "valid": true }, { "description": "non-present required property is invalid", "data": {"bar": 1}, "valid": false } ] }, { "description": "required default validation", "schema": { "properties": { "foo": {} } }, "tests": [ { "description": "not required by default", "data": {}, "valid": true } ] } ]; import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { var schema = Schema.create(); schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid); }); }); });
// https://github.com/json-schema/JSON-Schema-Test-Suite/blob/develop/tests/draft4/required.json var scenerios = [ { "description": "required validation", "schema": { "properties": { "foo": {}, "bar": {} }, "required": ["foo"] }, "tests": [ { "description": "present required property is valid", "data": {"foo": 1}, "valid": true }, { "description": "non-present required property is invalid", "data": {"bar": 1}, "valid": false } ] }, { "description": "required default validation", "schema": { "properties": { "foo": {} } }, "tests": [ { "description": "not required by default", "data": {}, "valid": true } ] } ]; import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; var schema = Schema.create(); scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid); }); }); });
Add actual image rather than link to travis
Add actual image rather than link to travis
JavaScript
mit
southpolesteve/ember-cli-json-schema,southpolesteve/ember-cli-json-schema
188677d8389f7b2082ecdb606273c34d23127a5c
app/packages/fraction-twitter/lib/tweetHot.next.js
app/packages/fraction-twitter/lib/tweetHot.next.js
'use strict'; if (process.env.NODE_ENV === 'production') { var Twit = Npm.require('twit'); var twitter = new Twit({ consumer_key: process.env.TWIT_KEY, consumer_secret: process.env.TWIT_SECRET, access_token: process.env.TWIT_TOKEN, access_token_secret: process.env.TWIT_TOKEN_SECRET }); var tweetHot = () => { var hot = Posts.find({}, { limit: 50, sort: { heat: -1 }, fields: { oldChildren: false } }).fetch(); var finished = false; _(hot).forEach((item) => { // it hasn't been tweeted yet if (finished === false && (typeof item.tweeted === 'undefined')) { twitter.post('statuses/update', { status: item.title + "\n" + 'http://beta.fraction.io/comments/' + item._id }, (err /*, response */) => { if (err) { throw err; } }); Posts.update({ _id: item._id }, { $set: { tweeted: true } }); console.log('Tweeting "' + item.title + '"'); finished = true; } }); }; //post a new link every 20 minutes Meteor.setInterval(tweetHot, 20 * 60 * 1000); }
'use strict'; if (process.env.NODE_ENV === 'production') { var Twit = Npm.require('twit'); var twitter = new Twit({ consumer_key: process.env.TWIT_KEY, consumer_secret: process.env.TWIT_SECRET, access_token: process.env.TWIT_TOKEN, access_token_secret: process.env.TWIT_TOKEN_SECRET }); var tweetHot = () => { var hot = Posts.find({}, { limit: 50, sort: { heat: -1 }, fields: { oldChildren: false } }).fetch(); var finished = false; _(hot).forEach((item) => { // it hasn't been tweeted yet if (finished === false && (typeof item.tweeted === 'undefined')) { twitter.post('statuses/update', { status: item.title + 'http://beta.fraction.io/comments/' + item._id }, (err /*, response */) => { if (err) { throw err; } }); Posts.update({ _id: item._id }, { $set: { tweeted: true } }); console.log('Tweeting "' + item.title + '"'); finished = true; } }); }; //post a new link every 20 minutes Meteor.setInterval(tweetHot, 20 * 60 * 1000); }
Remove line break in tweets
Remove line break in tweets
JavaScript
mit
rrevanth/news,rrevanth/news
a3b47d5bb732e920cba5f7bcddf3f15eab60c337
src/api-components/Sort.js
src/api-components/Sort.js
import React from 'react'; import { sort } from 'sajari'; import Base from './Base.js'; import Components from '../constants/QueryComponentConstants.js'; const Sort = props => { const { field, order, ...others } = props; return ( <Base {...others} runDefault='update' componentName={Components.SORT} data={sort(field, order)} /> ); }; Sort.propTypes = { field: React.PropTypes.string.isRequired, order: React.PropTypes.string.isRequired, }; export default Sort;
import React from 'react'; import { sort } from 'sajari'; import Base from './Base.js'; import Components from '../constants/QueryComponentConstants.js'; const Sort = props => { const { field, order, ...others } = props; return ( <Base {...others} runDefault='update' componentName={Components.SORT} data={sort(field)} /> ); }; Sort.propTypes = { field: React.PropTypes.string.isRequired, }; export default Sort;
Remove order prop from sort
Remove order prop from sort
JavaScript
mit
sajari/sajari-sdk-react,sajari/sajari-sdk-react
4e48b29570a6b1b85492508f7e34656f130dc476
cli/Gulpfile.js
cli/Gulpfile.js
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); gulp.task('default', ['lint', 'mocha']); gulp.task('test', ['default']); gulp.task('mocha', function () { return gulp.src('./tests/**/*.js', { read: false }) .pipe(mocha({ reporter: 'spec' })); }); gulp.task('lint', function() { return gulp.src(['./lib/**/*.js', './tests/**/*.js', 'Gulpfile.js']) .pipe(jshint()) .pipe(jshint.reporter('default')); });
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); gulp.task('default', ['lint', 'mocha']); gulp.task('test', ['default']); gulp.task('mocha', function () { return gulp.src('./tests/**/*.js', { read: false }) .pipe(mocha({ reporter: 'spec' })); }); gulp.task('lint', function() { return gulp.src(['./lib/**/*.js', './tests/**/*.js', 'Gulpfile.js']) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(jshint.reporter('fail')); });
Fix bug: gulp not failing on lint error
Fix bug: gulp not failing on lint error Without piping the results to the 'fail' reporter inside gulp the build won't fail if an error is introduced.
JavaScript
bsd-3-clause
luizbranco/torus-cli,manifoldco/torus-cli,manifoldco/torus-cli,luizbranco/torus-cli,luizbranco/torus-cli,manifoldco/torus-cli
3a086bf6d4fbba72a9393c4d234d5462b5df68e8
header.js
header.js
// ==UserScript== // @name TPP Touchscreen Input Assist // @namespace chfoo/tppinputassist // @version 1.11.0 // @homepage https://github.com/chfoo/tppinputassist // @updateURL https://raw.githubusercontent.com/chfoo/tppinputassist/master/tppinputassist.user.js // @description Touchscreen coordinate tap overlay for inputting into Twitch chat // @author Christopher Foo // @match http://twitch.tv/* // @match http://www.twitch.tv/* // @match https://twitch.tv/* // @match https://www.twitch.tv/* // @grant none // ==/UserScript== /* jshint -W097 */ (function() {
// ==UserScript== // @name TPP Touchscreen Input Assist // @namespace chfoo/tppinputassist // @version 1.11.0 // @homepage https://github.com/chfoo/tppinputassist // @description Touchscreen coordinate tap overlay for inputting into Twitch chat // @author Christopher Foo // @match http://twitch.tv/* // @match http://www.twitch.tv/* // @match https://twitch.tv/* // @match https://www.twitch.tv/* // @grant none // ==/UserScript== /* jshint -W097 */ (function() {
Remove @updateURL to not override alternate hosted version.
Remove @updateURL to not override alternate hosted version. It wasn't even being used correctly. Blame the original Userscripts website tutorial.
JavaScript
mit
chfoo/tppinputassist,chfoo/tppinputassist
af375c49371a00e42686c11bc055ed5234a2f596
tests/gtype-signal2.js
tests/gtype-signal2.js
#!/usr/bin/env seed // Returns: 0 // STDIN: // STDOUT:2 Weathermen // STDERR: Seed.import_namespace("GObject"); Seed.import_namespace("Gtk"); Gtk.init(null, null); HelloWindowType = { parent: Gtk.Window, name: "HelloWindow", class_init: function(klass, prototype) { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, GObject.TYPE_STRING]}; hello_signal_id = klass.install_signal(HelloSignalDefinition); }, } HelloWindow = new GType(HelloWindowType); w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) {Seed.print(number+ " " + string)}); w.signal.hello.emit(2, "Weathermen");
#!/usr/bin/env seed // Returns: 0 // STDIN: // STDOUT:2 Weathermen\n\[object GtkWindow\] // STDERR: Seed.import_namespace("GObject"); Seed.import_namespace("Gtk"); Gtk.init(null, null); HelloWindowType = { parent: Gtk.Window, name: "HelloWindow", class_init: function(klass, prototype) { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, GObject.TYPE_STRING], return_type: GObject.TYPE_OBJECT}; hello_signal_id = klass.install_signal(HelloSignalDefinition); }, } HelloWindow = new GType(HelloWindowType); w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) {Seed.print(number+ " " + string); return new Gtk.Window()}); Seed.print(w.signal.hello.emit(2, "Weathermen"));
Add test of defining a signal with a return type.
Add test of defining a signal with a return type. svn path=/trunk/; revision=233
JavaScript
lgpl-2.1
danilocesar/seed,danilocesar/seed,danilocesar/seed,danilocesar/seed,danilocesar/seed
9810b9950de6f7830c0557abefd3a12e0edaf148
brunch-config.js
brunch-config.js
exports.config = { npm: { enabled: true }, files: { javascripts: { joinTo: 'app.js' }, stylesheets: { joinTo: { 'app.css': /^app\/styles/ } } }, overrides: { production: { plugins: { postcss: { processors: [ require('autoprefixer'), require('cssnano') ] } } } }, plugins: { digest: { prependHost: { production: '/tasty-brunch' }, referenceFiles: /\.(css|html|js)$/ }, postcss: { processors: [ require('autoprefixer') ] }, sass: { options: { includePaths: ['node_modules'] } }, static: { processors: [ require('html-brunch-static')({ handlebars: { enableProcessor: true, helpers: { join (context, block) { return context.join(block.hash.delimiter) }, updated_time () { return new Date().toISOString() } } } }) ] } } }
exports.config = { files: { javascripts: { joinTo: 'app.js' }, stylesheets: { joinTo: { 'app.css': /^app\/styles/ } } }, overrides: { production: { plugins: { postcss: { processors: [ require('autoprefixer'), require('cssnano') ] } } } }, plugins: { digest: { prependHost: { production: '/tasty-brunch' }, referenceFiles: /\.(css|html|js)$/ }, postcss: { processors: [ require('autoprefixer') ] }, sass: { options: { includePaths: ['node_modules'] } }, static: { processors: [ require('html-brunch-static')({ handlebars: { enableProcessor: true, helpers: { join (context, block) { return context.join(block.hash.delimiter) }, updated_time () { return new Date().toISOString() } } } }) ] } } }
Remove npm from config (enabled by default)
Remove npm from config (enabled by default)
JavaScript
mit
makenew/tasty-brunch,makenew/tasty-brunch,rxlabs/tasty-todos,makenew/tasty-brunch,rxlabs/tasty-todos,rxlabs/tasty-todos
c9f9444f3b7ad45cfffc6084de15a5c30796b264
DSA-Campaign-Uplift-Estimation/src/main/webapp/script.js
DSA-Campaign-Uplift-Estimation/src/main/webapp/script.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.
//Copyright 2020 Google LLC // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. function getLogsStatus() { fetch('/userapi').then(response => response.json()).then(logStatus => { const link = document.getElementById("login-link"); if(logStatus.Bool) { console.log('User is Logged In'); link.href = '../Home/home.html'; } else { console.log('User is not Logged In'); link.href = logStatus.Url; } }); }
Create new method for logging in
Create new method for logging in
JavaScript
apache-2.0
googleinterns/step51-2020,googleinterns/step51-2020,googleinterns/step51-2020,googleinterns/step51-2020,googleinterns/step51-2020
1cf9b5d0a0946057399b261e598080efe0f686a2
src/skinner/core/resolver.js
src/skinner/core/resolver.js
define (["lib/lodash", "lib/Handlebars", "src/skinner/core/keypath"], function (_, Handlebars, keyPath) { "use strict"; function resolveData(data, subject, additionalDimensionData, context) { var allContext = keyPath(subject, "condition", {}); if (!_.isUndefined(additionalDimensionData)) { allContext = _.extend({}, allContext, additionalDimensionData); } Handlebars.registerHelper("indexed", function (key) { return key[context]; }); function mapper(value) { console.log(value); if (_.isArray(value) || _.isObject(value)) { return resolveData(value, subject, additionalDimensionData, context); } else if (_.isString(value)) { var template = Handlebars.compile(value); return template(allContext); } else { return value; } } if (_.isArray(data)) { return _.map(data, mapper); } else { return _.mapValues(data, mapper); } } return { "resolveData": resolveData }; });
define (["lib/lodash", "lib/Handlebars", "src/skinner/core/keypath"], function (_, Handlebars, keyPath) { "use strict"; function resolveData(data, subject, additionalDimensionData, context) { var allContext = keyPath(subject, "condition", {}); if (!_.isUndefined(additionalDimensionData)) { allContext = _.extend({}, allContext, additionalDimensionData); } Handlebars.registerHelper("indexed", function (key) { return key[context]; }); function mapper(value) { if (_.isArray(value) || _.isObject(value)) { return resolveData(value, subject, additionalDimensionData, context); } else if (_.isString(value)) { var template = Handlebars.compile(value); return template(allContext); } else { return value; } } if (_.isArray(data)) { return _.map(data, mapper); } else { return _.mapValues(data, mapper); } } return { "resolveData": resolveData }; });
Remove a console log statement, so tests run without extraneous logging
Remove a console log statement, so tests run without extraneous logging
JavaScript
mit
dbachrach/skinner,dbachrach/skinner
b733ed269de8dee5fd25cb4b273cc9963a21aa1d
examples/pagination/js/callbacks.js
examples/pagination/js/callbacks.js
// TODO
function displayPage(results) { $('#results tbody').empty(); for (let row of results) { let tr = $('<tr />'); for (let field of ['id', 'name', 'category', 'sub_category', 'container_type', 'price_per_unit', 'margin']) { tr.append($('<td />').text(row[field])); } $('#results tbody').append(tr); } } var cache = {}; function ajaxOrCached(query, page, handler) { if ([query, page] in cache) { return handler(cache[[query, page]]); } $.ajax({ 'url' : 'http://localhost:8080?q=' + query + '&page=' + page, 'dataType': 'json', 'success' : result => { cache[[query, page]] = result; handler(result) } }); } function showPage(query, page) { function handler(results) { $('.paging-control').addClass('enabled'); let prev = results.prev; let next = results.next; let list = results.results; displayPage(list); // NOTE: This is not equivalent to the arrows version. This // pre-fetching will not be canceled when the user interacts // with paging controls. ajaxOrCached(query, page, () => {}); const h1 = () => { $('#next').off('click', h2); showPage(query, prev); }; const h2 = () => { $('#prev').off('click', h1); showPage(query, next); }; $('#prev').one('click', h1); $('#next').one('click', h2); } $('.paging-control').addClass('disabled'); ajaxOrCached(query, page, handler); } var clicks = 0; $('#filter').keyup((ev) => { var expected = ++clicks; setTimeout(() => { if (expected != clicks) { return; } $('#prev').unbind('click'); $('#next').unbind('click'); showPage($(ev.target).val(), 1); }, 400); });
Add callback version of pagination.
Add callback version of pagination.
JavaScript
mit
efritz/arrows,JoshuaSCochrane/arrows
3f9ee727a59c00f955521b1c3f2137c9b901bce9
extension/keysocket-yandex-radio.js
extension/keysocket-yandex-radio.js
var playTarget = '.player-controls__play'; var nextTarget = '.button_round'; function onKeyPress(key) { if (key === NEXT) { var cards = document.querySelectorAll('.slider__item') var nextCard = cards[cards.length - 3]; console.log(nextCard); simulateClick(nextCard.querySelector(nextTarget)); } else if (key === PLAY) { simulateClick(document.querySelector(playTarget)); } }
var playTarget = '.player-controls__play'; var nextTarget = '.button_round'; function onKeyPress(key) { if (key === NEXT) { var nextCard = document.querySelector('.slider__item_next'); console.log(nextCard); simulateClick(nextCard.querySelectorAll(nextTarget)[2]); } else if (key === PLAY) { simulateClick(document.querySelector(playTarget)); } }
Fix issue with forward button at Yandex.Radio
Fix issue with forward button at Yandex.Radio
JavaScript
apache-2.0
feedbee/keysocket,feedbee/keysocket
84746b5ce55292e85bdbbb031fff2712c8d40aee
scripts/cd-server.js
scripts/cd-server.js
// Continuous delivery server const { spawn } = require('child_process') const { resolve } = require('path') const { createServer } = require('http') const { urlencoded } = require('body-parser') const hostname = '127.0.0.1' const port = 80 const server = createServer((req, res) => { const { headers, method, url } = req // When a successful build has happened, kill the process, triggering a restart if (req.method === 'POST' && req.url === '/webhook') { // Send response res.statusCode = 200 res.end() let body = [] req .on('error', err => { console.error(err) }) .on('data', chunk => { body.push(chunk) }) .on('end', () => { req.body = Buffer.concat(body).toString() const data = urlencoded({ extended: true })(req) console.log(req.body.payload) if (req.body.payload) { const passed = req.body.payload.state == 'passed' const master = req.body.payload.branch == 'master' process.exit(0) } }) } res.statusCode = 404 res.end() }).listen(port)
// Continuous delivery server const { spawn } = require('child_process') const { resolve } = require('path') const { createServer } = require('http') const { urlencoded } = require('body-parser') const hostname = '127.0.0.1' const port = 80 const server = createServer((req, res) => { const { headers, method, url } = req // When a successful build has happened, kill the process, triggering a restart if (req.method === 'POST' && req.url === '/webhook') { // Send response res.statusCode = 200 res.end() let body = [] req .on('error', err => { console.error(err) }) .on('data', chunk => { body.push(chunk) }) .on('end', () => { req.body = Buffer.concat(body).toString() urlencoded({ extended: true })(req) console.log(req.body) if (req.body.payload) { const passed = req.body.payload.state == 'passed' const master = req.body.payload.branch == 'master' if (passed && master) { process.exit(0) } } }) } res.statusCode = 404 res.end() }).listen(port)
Add branch and state check on CD server.
Add branch and state check on CD server.
JavaScript
mit
jsonnull/jsonnull.com,jsonnull/jsonnull.com,jsonnull/jsonnull.com
5413c871f0d98e27515ee57e5a8a09fadaac11aa
lib/index.js
lib/index.js
/** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { var validSchemaTypes = ['String', 'Number', 'Date', 'ObjectID']; function validateSchemaType(path, schemaType) { if (!~validSchemaTypes.indexOf(schemaType.instance)) { throw new Error('Cannot use constant in path ' + path + '.\nConstant can only be used with: ' + validSchemaTypes.join(', ')); } } /* Register validations. */ schema.eachPath(function (path, schemaType) { if (!schemaType.options.constant) return; validateSchemaType(path, schemaType); (function (path) { schemaType.validators.push( [ function () { if (this.isNew || !this.isSelected(path)) return; return !this.isModified(path); }, constantPlugin.ErrorMessages.ERRRESETCONST, 'constant plugin' ] ); })(path); }); }; exports.ErrorMessages = { ERRRESETCONST: 'Constant `{PATH}` cannot be changed.' };
var util = require('util'); /** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { options = options || {}; options.ValidSchemaTypes = options.ValidSchemaTypes || ['String', 'Number', 'Date', 'ObjectID']; options.ErrorType = options.ErrorType || constantPlugin.ERROR_TYPE; function validateSchemaType(path, schemaType) { if (!~options.ValidSchemaTypes.indexOf(schemaType.instance)) throw new Error(util.format(constantPlugin.ErrorMessages.ERRINVALIDTYPE, path, schemaType.instance, options.ValidSchemaTypes.join(', '))); } /* Register validations. */ schema.eachPath(function (path, schemaType) { if (!schemaType.options.constant) return; validateSchemaType(path, schemaType); (function (path) { schemaType.validators.push([ function () { if (this.isNew || !this.isSelected(path)) return; return !this.isModified(path); }, constantPlugin.ErrorMessages.ERRCONSTRESET, options.ErrorType ]); })(path); }); }; exports.ErrorMessages = { ERRCONSTRESET: 'Constant `{PATH}` cannot be changed.', ERRINVALIDTYPE: 'Cannot use constant in path `%s` with type `%s`.\nConstant can only be used with: %s' }; exports.ERROR_TYPE = 'constant plugin';
Make valid schema types and validator error type configurable
Make valid schema types and validator error type configurable
JavaScript
isc
cakuki/mongoose-constant
867730d0855a81aa7b72118fc969932c37790cfb
packages/accounts/accounts_server.js
packages/accounts/accounts_server.js
/** * Sets the default permissions to new users */ Meteor.users.after.insert(function (userId, doc) { var userId = doc._id; if (orion.adminExists) { // if there is a admin created we will set the default roles. var defaultRoles = Options.get('defaultRoles'); Roles.addUserToRoles(userId, defaultRoles); } else { // If there is no admin, we will add the admin role to this new user. Roles.addUserToRoles(userId, 'admin'); // Pass to the client if the admin exists orion.adminExists = true; Inject.obj('adminExists', { exists: true }); } }); /** * Pass to the client if there is a admin account */ orion.adminExists = Roles._collection.find({ roles: 'admin' }).count() != 0; Inject.obj('adminExists', { exists: orion.adminExists });
/** * Sets the default permissions to new users */ Meteor.users.after.insert(function (userId, doc) { var userId = doc._id; if (orion.adminExists) { // if there is a admin created we will set the default roles. if (Roles._collection.find({ userId: userId }).count() == 0) { var defaultRoles = Options.get('defaultRoles'); Roles.addUserToRoles(userId, defaultRoles); } } else { // If there is no admin, we will add the admin role to this new user. Roles.addUserToRoles(userId, 'admin'); // Pass to the client if the admin exists orion.adminExists = true; Inject.obj('adminExists', { exists: true }); } }); /** * Pass to the client if there is a admin account */ orion.adminExists = Roles._collection.find({ roles: 'admin' }).count() != 0; Inject.obj('adminExists', { exists: orion.adminExists });
Set default roles only if user has no roles
Set default roles only if user has no roles
JavaScript
mit
kevohagan/orion,BudickDa/orion,justathoughtor2/orion,PEM--/orion,Citronnade/orion,mauricionr/orion,PEM--/orion,nabiltntn/orion,Citronnade/orion,orionjs/orion,BudickDa/orion,kevohagan/orion,jorisroling/orion,mauricionr/orion,justathoughtor2/orion,rwatts3/orion,rwatts3/orion,nabiltntn/orion,orionjs/orion,TedEwanchyna/orion,dgleba/orion,TedEwanchyna/orion,dgleba/orion,jorisroling/orion
935076aa1cb280bea1fe1ac9c49aa4c52108b820
commands/tell.js
commands/tell.js
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(''); var recipient = message.shift(); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; } function tellPlayer (p){ if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; };
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
Fix split/join and move functions so they can refer to recipient var.
Fix split/join and move functions so they can refer to recipient var.
JavaScript
mit
shawncplus/ranviermud,seanohue/ranviermud,seanohue/ranviermud
070cd9727bdb269a215b0dd087bb30c83fd3d5f5
commands/tell.js
commands/tell.js
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.toLowercase() !== player.getName().toLowercase()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
Fix conditional for recipient name/playername
Fix conditional for recipient name/playername
JavaScript
mit
seanohue/ranviermud,shawncplus/ranviermud,seanohue/ranviermud
7722859f57858f8567bb5ab82dfdc023b9470b50
server/privileges.js
server/privileges.js
BlogPosts.allow({ insert: Utils.constant(true), remove: Utils.constant(true), update: Utils.constant(true), });
BlogPosts.allow({ insert: anyoneLoggedIn, remove: onlyTheOwner, update: onlyTheOwner, }); // these documents can be only accessed with custom methods Published.deny({ insert: Utils.constant(true), remove: Utils.constant(true), update: Utils.constant(true), }); function anyoneLoggedIn(userId) { return !!userId; } function onlyTheOwner(userId, doc) { return !!userId && doc.createdBy === userId; }
Secure updates on BlogPost collection
Secure updates on BlogPost collection
JavaScript
mit
anticoders/blog,anticoders/blog,anticoders/blog
7b14081f1852c17167ea4295459f7514b234b5b6
server/userGarden.js
server/userGarden.js
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const UserDB = require('./UserDB'); const metrics = require('./metrics'); program .version('0.0.1') .option('-p, --port <n>', 'Port for WebSocket', parseInt) .option('-d, --dump <n>', 'Period for dump of user positions, sec', parseInt) .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); if (require.main === module) { const m = new metrics.Metrics(5000); m.runMeasures(); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; const userDB = new UserDB.UserDB( conn, program.dbname, program.dump, program.port, 100 // location size ); userDB.run(); }); }
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const UserDB = require('./UserDB'); const metrics = require('./metrics'); program .version('0.0.1') .option('-p, --port <n>', 'Port for WebSocket', parseInt) .option('-d, --dump <n>', 'Period for dump of user positions, sec', parseInt) .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); if (program.dump === undefined) { program.dump = 60; } if (require.main === module) { const m = new metrics.Metrics(5000); m.runMeasures(); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; const userDB = new UserDB.UserDB( conn, program.dbname, program.dump, program.port, 100 // location size ); userDB.run(); }); }
Add default value for period of dump.
Add default value for period of dump.
JavaScript
mit
nobus/Labyrinth,nobus/Labyrinth
42a291286b4627191a18e8848dffee0bf5574c93
settings/js/admin.js
settings/js/admin.js
$(document).ready(function(){ $('#loglevel').change(function(){ $.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){ OC.Log.reload(); } ); }); $('#backgroundjobs input').change(function(){ if($(this).attr('checked')){ var mode = $(this).val(); if (mode == 'ajax' || mode == 'webcron' || mode == 'cron') { OC.AppConfig.setValue('core', 'backgroundjobs_mode', mode); } } }); $('#shareAPIEnabled').change(function() { $('.shareAPI td:not(#enable)').toggle(); }); $('#shareAPI input').change(function() { if ($(this).attr('type') == 'radio') { console.log('radio'); } if ($(this).attr('type') == 'checkbox') { console.log('checked'); } OC.AppConfig.setValue('core', 'shareapi_', $(this).val()); }); });
$(document).ready(function(){ $('#loglevel').change(function(){ $.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){ OC.Log.reload(); } ); }); $('#backgroundjobs input').change(function(){ if($(this).attr('checked')){ var mode = $(this).val(); if (mode == 'ajax' || mode == 'webcron' || mode == 'cron') { OC.AppConfig.setValue('core', 'backgroundjobs_mode', mode); } } }); $('#shareAPIEnabled').change(function() { $('.shareAPI td:not(#enable)').toggle(); }); $('#shareAPI input').change(function() { if ($(this).attr('type') == 'checkbox') { if (this.checked) { var value = 'yes'; } else { var value = 'no'; } } else { var value = $(this).val() } OC.AppConfig.setValue('core', $(this).attr('name'), value); }); });
Fix incorrect Javascript for changing Share API settings
Fix incorrect Javascript for changing Share API settings
JavaScript
agpl-3.0
pmattern/server,pmattern/server,lrytz/core,pixelipo/server,owncloud/core,nextcloud/server,bluelml/core,owncloud/core,Ardinis/server,bluelml/core,phil-davis/core,michaelletzgus/nextcloud-server,pixelipo/server,cernbox/core,Ardinis/server,endsguy/server,pollopolea/core,IljaN/core,cernbox/core,IljaN/core,bluelml/core,whitekiba/server,pixelipo/server,nextcloud/server,Ardinis/server,owncloud/core,michaelletzgus/nextcloud-server,owncloud/core,whitekiba/server,pixelipo/server,lrytz/core,IljaN/core,nextcloud/server,cernbox/core,pollopolea/core,bluelml/core,whitekiba/server,pmattern/server,andreas-p/nextcloud-server,endsguy/server,pollopolea/core,andreas-p/nextcloud-server,lrytz/core,Ardinis/server,IljaN/core,jbicha/server,sharidas/core,pmattern/server,jbicha/server,lrytz/core,endsguy/server,Ardinis/server,xx621998xx/server,pollopolea/core,cernbox/core,endsguy/server,pollopolea/core,xx621998xx/server,xx621998xx/server,xx621998xx/server,nextcloud/server,cernbox/core,sharidas/core,sharidas/core,pixelipo/server,sharidas/core,owncloud/core,lrytz/core,xx621998xx/server,pmattern/server,jbicha/server,jbicha/server,whitekiba/server,michaelletzgus/nextcloud-server,michaelletzgus/nextcloud-server,bluelml/core,andreas-p/nextcloud-server,jbicha/server,IljaN/core,sharidas/core,endsguy/server,andreas-p/nextcloud-server,andreas-p/nextcloud-server,whitekiba/server
72d6da5a3550976deba5cc245f5d3b88f770cf4d
lib/utils.js
lib/utils.js
var fs = require('fs'), expandHomeDir = require('expand-home-dir'), async = require('async') ; function readFile(fileLocation, cb) { fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) { if (err) { cb(err); return; } cb(null, fileContents); }); } function loadConfigs(configLocations, cb) { async.map(configLocations, function (configLocation, cb) { var absoluteConfigLocation = expandHomeDir(configLocation); fs.exists(absoluteConfigLocation, function (exists) { if (exists) { readFile(absoluteConfigLocation, function (err, rawConfig) { if (err) { console.log("Unable to read config from: ", absoluteConfigLocation); cb(null, {}); return; } try { cb(null, JSON.parse(rawConfig)); } catch (err) { console.log("Unable to parse config from: ", absoluteConfigLocation); } }); } else { cb(null, {}); } }); }, function (err, results) { cb(results); }); } module.exports.readFile = readFile; module.exports.loadConfigs = loadConfigs;
var fs = require('fs'), expandHomeDir = require('expand-home-dir'), async = require('async') ; function readFile(fileLocation, cb) { fs.stat(fileLocation, function (stats) { if (stats.size > Math.pow(1024, 2) || !stats.isFile()) { cb(new Error('File ' + fileLocation + ' too large or not an ordinary file!')); } else { fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) { if (err) { cb(err); return; } cb(null, fileContents); }); } }); } function loadConfigs(configLocations, cb) { async.map(configLocations, function (configLocation, cb) { var absoluteConfigLocation = expandHomeDir(configLocation); fs.exists(absoluteConfigLocation, function (exists) { if (exists) { readFile(absoluteConfigLocation, function (err, rawConfig) { if (err) { console.log("Unable to read config from: ", absoluteConfigLocation); cb(null, {}); return; } try { cb(null, JSON.parse(rawConfig)); } catch (err) { console.log("Unable to parse config from: ", absoluteConfigLocation); } }); } else { cb(null, {}); } }); }, function (err, results) { cb(results); }); } module.exports.readFile = readFile; module.exports.loadConfigs = loadConfigs;
Check whether read file is actually a file, and if it's not too big.
Check whether read file is actually a file, and if it's not too big.
JavaScript
mit
dice-cyfronet/hyperflow-client,dice-cyfronet/hyperflow-client
f5b2a9545d57b687b3f3726db255a29a47a5df07
src/global/routers/netinfo.js
src/global/routers/netinfo.js
/* jshint node: true */ /** * Wake Up Platform * (c) Telefonica Digital, 2014 - All rights reserved * License: GNU Affero V3 (see LICENSE file) * Fernando Rodríguez Sela <frsela at tid dot es> * Guillermo López Leal <gll at tid dot es> */ var log = require('../shared_libs/logger'); module.exports.info = { name: 'netInfo', type: 'router', virtualpath: 'netinfo/v1', description: 'Returns a JSON with the MCC-MNC networks and state' }; module.exports.entrypoint = function netInfo(parsedURL, body, req, res) { res.setHeader('Content-Type', 'application/json'); res.statusCode = 200; res.write(JSON.stringify(process.netinfo || {})); };
/* jshint node: true */ /** * Wake Up Platform * (c) Telefonica Digital, 2014 - All rights reserved * License: GNU Affero V3 (see LICENSE file) * Fernando Rodríguez Sela <frsela at tid dot es> * Guillermo López Leal <gll at tid dot es> */ var log = require('../shared_libs/logger'), mn = require('../../common/libs/mobile_networks.js'); module.exports.info = { name: 'netInfo', type: 'router', virtualpath: 'netinfo/v1', description: 'Returns a JSON with the MCC-MNC networks and state' }; module.exports.entrypoint = function netInfo(parsedURL, body, req, res) { res.setHeader('Content-Type', 'application/json'); res.statusCode = 200; res.write(JSON.stringify(mn.getNetworkStatuses() || {})); };
Use Mobile Network module to fetch network statuses data
Use Mobile Network module to fetch network statuses data
JavaScript
agpl-3.0
telefonicaid/wakeup_platform_global,telefonicaid/wakeup_platform_global
2eebdd3b129adbaf661c6a6a5e18c5329f4b6311
liphte.ts.js
liphte.ts.js
var fs = require('fs'); var vm = require('vm'); var includeInThisContext = function(path) { var code = fs.readFileSync(path); vm.runInThisContext(code, path); }.bind(this); includeInThisContext("dist/liphte.min.js"); exports.liphte = liphte;
var fs = require('fs'); var vm = require('vm'); var includeInThisContext = function(path) { var code = fs.readFileSync(path); vm.runInThisContext(code, path); }.bind(this); includeInThisContext(__dirname+"/dist/liphte.min.js"); exports.liphte = liphte;
Fix module for NodeJS - apped_dir_name
Fix module for NodeJS - apped_dir_name
JavaScript
mit
maveius/liphte.ts,maveius/liphte.ts
1ffcd46beb7659fa314c6ea799991d6320c828e1
spec/bind_to_spec.js
spec/bind_to_spec.js
var vows = require('vows') , assert = require('assert') , Glue = require(__dirname + "/../lib/glue"); var suite = vows.describe('bindTo') suite.addBatch({ "ensures": { "that the target object of glue is changed": function() { var topic = new Glue({an: "object"}); topic.bindTo({another: "object"}); assert.notDeepEqual(topic.topic, {an: "object"}); assert.deepEqual(topic.target, {another: "object"}); }, "notifies listeners with the old and new target object": function() { var topic = new Glue({an: "object"}) , message = {}; topic.addListener('target', function(msg) { message = msg; }); topic.bindTo({ another: "object" }); assert.deepEqual(message, { oldTarget: { an: "object" } , newTarget: { another: "object" } }); this.target = { an: "object" }; //reset }, "executes a callback if available": function() { var topic = new Glue({an: "object"}) , invoked = false; topic.bindTo({}, function() { invoked = true; }); assert.equal(invoked, true); }, "when invoked, returns itself for chainability": function() { var topic = new Glue({an: "object"}); var returnedValue = topic.addListener(function(){}); assert.equal(topic, returnedValue); } } }); suite.export(module);
var vows = require('vows') , assert = require('assert') , Glue = require(__dirname + "/../lib/glue"); var suite = vows.describe('bindTo') suite.addBatch({ "ensures": { topic: new Glue({}), "that the target object of glue is changed": function(topic) { topic.target = {}; topic.bindTo({an: "object"}); assert.notDeepEqual(topic.topic, {}); assert.deepEqual(topic.target, {an: "object"}); }, "notifies listeners with the old and new target object": function(topic) { var message = {}; topic.target = {}; topic.addListener('target', function(msg) { message = msg; }); topic.bindTo({ an: "object" }); assert.deepEqual(message, { oldTarget: {} , newTarget: { an: "object" } }); this.target = { an: "object" }; //reset }, "executes a callback if available": function(topic) { var invoked = false; topic.target = {}; topic.bindTo({an: "object"}, function() { invoked = true; }); assert.equal(invoked, true); }, "when invoked, returns itself for chainability": function(topic) { var returnedValue = topic.addListener(function(){}); assert.equal(topic, returnedValue); } } }); suite.export(module);
Refactor bind_to spec to better performance
Refactor bind_to spec to better performance
JavaScript
mit
edgecase/glue.js
168c9b47763e30982a47c4c1fed683f31788d098
src/ipfs-access-controller.js
src/ipfs-access-controller.js
'use strict' const AccessController = require('./access-controller') const { DAGNode } = require('ipld-dag-pb') class IPFSAccessController extends AccessController { constructor (ipfs) { super() this._ipfs = ipfs } async load (address) { // Transform '/ipfs/QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' // to 'QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' if (address.indexOf('/ipfs') === 0) address = address.split('/')[2] try { const dag = await this._ipfs.object.get(address) const obj = JSON.parse(dag.toJSON().data) this._access = obj } catch (e) { console.log("ACCESS ERROR:", e) } } async save (onlyHash) { let hash try { const access = JSON.stringify(this._access, null, 2) let dag if (onlyHash) { dag = await new Promise(resolve => { DAGNode.create(Buffer.from(access), (err, n) => { resolve(n) }) }) } else { dag = await this._ipfs.object.put(new Buffer(access)) } hash = dag.toJSON().multihash.toString() } catch (e) { console.log("ACCESS ERROR:", e) } return hash } } module.exports = IPFSAccessController
'use strict' const AccessController = require('./access-controller') const { DAGNode } = require('ipld-dag-pb') class IPFSAccessController extends AccessController { constructor (ipfs) { super() this._ipfs = ipfs } async load (address) { // Transform '/ipfs/QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' // to 'QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' if (address.indexOf('/ipfs') === 0) address = address.split('/')[2] try { const dag = await this._ipfs.object.get(address) const obj = JSON.parse(dag.toJSON().data) this._access = obj } catch (e) { console.log("ACCESS ERROR:", e) } } async save (onlyHash) { let hash try { const access = JSON.stringify(this._access, null, 2) let dag if (onlyHash) { dag = await new Promise(resolve => { DAGNode.create(Buffer.from(access), (err, n) => { if (err) { throw err } resolve(n) }) }) } else { dag = await this._ipfs.object.put(new Buffer(access)) } hash = dag.toJSON().multihash.toString() } catch (e) { console.log("ACCESS ERROR:", e) } return hash } } module.exports = IPFSAccessController
Throw error returned from DAGNode.create in access controller
Throw error returned from DAGNode.create in access controller
JavaScript
mit
haadcode/orbit-db,orbitdb/orbit-db,orbitdb/orbit-db,haadcode/orbit-db
caa4e2071ae26d012a71eeae77b72cc60bcfe2e1
src/content/shorten-url.js
src/content/shorten-url.js
import fetchJsonP from 'fetch-jsonp'; import queryString from 'query-string'; import url from 'url'; export default function shortenURL(urlToShorten) { let longURL = urlToShorten; if (!longURL.startsWith('https://perf-html.io/')) { const parsedURL = url.parse(longURL); const parsedURLOnCanonicalHost = Object.assign({}, parsedURL, { protocol: 'https:', host: 'perf-html.io', }); longURL = url.format(parsedURLOnCanonicalHost); } const bitlyQueryURL = 'https://api-ssl.bitly.com/v3/shorten?' + queryString.stringify({ 'longUrl': longURL, 'domain': 'perfht.ml', 'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422', }); return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url); }
import fetchJsonP from 'fetch-jsonp'; import queryString from 'query-string'; import url from 'url'; export default function shortenURL(urlToShorten) { let longURL = urlToShorten; if (!longURL.startsWith('https://perf-html.io/')) { const parsedURL = url.parse(longURL); const parsedURLOnCanonicalHost = Object.assign({}, parsedURL, { protocol: 'https:', host: 'perf-html.io', }); longURL = url.format(parsedURLOnCanonicalHost); } const bitlyQueryURL = 'https://api-ssl.bitly.com/v3/shorten?' + queryString.stringify({ 'longUrl': longURL, 'domain': 'perfht.ml', 'format': 'json', 'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422', }); return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url); }
Add missing 'format' key in the bit.ly API request.
Add missing 'format' key in the bit.ly API request. Bit.ly have recently made a change on their side to ignore the jsonp callback argument if format=json was not specified, and that made our requests fail.
JavaScript
mpl-2.0
devtools-html/perf.html,mstange/cleopatra,squarewave/bhr.html,mstange/cleopatra,squarewave/bhr.html,devtools-html/perf.html
707ab3e66fb6f27a4e6d7e8165b229c3deea8140
client/src/components/SmallSave/styled.js
client/src/components/SmallSave/styled.js
import styled from 'styled-components'; export const Save = styled.div` align-items: center; display: flex; flex-direction: row; justify-content: center; padding: 8px; &:hover { color: #000; } `; export const Bookmark = styled.span` color: ${props => (props.saved ? '#04d092' : '#bbb')}; line-height: 12px; margin-left: 6px; width: 8px; & > .fa { font-size: 12px; } ${Save}:hover & { color: #04d092; } `;
import styled from 'styled-components'; export const Save = styled.div` align-items: center; display: flex; flex-direction: row; justify-content: center; padding: 8px; &:hover { color: #000; } `; export const Bookmark = styled.span` color: ${props => (props.saved ? '#04d092' : '#bbb')}; line-height: 12px; margin-left: 6px; pointer-events: none; width: 8px; & > .fa { font-size: 12px; } ${Save}:hover & { color: #04d092; } `;
Remove pointer events from bookmark symbol
Remove pointer events from bookmark symbol
JavaScript
mit
jenovs/bears-team-14,jenovs/bears-team-14
c47e5906cd53d9348df05194c511cc5a0c020b8e
routes/index.js
routes/index.js
const router = require('express').Router() // eslint-disable-line new-cap const website = require('../data/website') /* GET API */ router.get('/api', (req, res) => { res.json(website) }) /* GET home page */ router.get('/', (req, res) => { res.render('index', { title: website.author.name, description: website.description, projects: website.included.projects, author: website.author, isHome: true }) }) /* GET any HTML pages */ router.get('/:page', (req, res) => { res.render(req.params.page, { title: `${website.author.name} | ${req.params.page}`, description: website.description, author: website.author.name, isHome: false }) }) module.exports = router
const router = require('express').Router() // eslint-disable-line new-cap const website = require('../data/website') /* GET API */ router.get('/api', (req, res) => { res.json(website) }) /* GET home page */ router.get('/', (req, res) => { res.render('index', { title: website.author.name, description: website.description, author: website.author, isHome: true }) }) /* GET any HTML pages */ router.get('/:page', (req, res) => { res.render(req.params.page, { title: `${website.author.name} | ${req.params.page}`, description: website.description, author: website.author.name, isHome: false }) }) module.exports = router
Remove projects data from API
Remove projects data from API
JavaScript
mit
mlcdf/website,mlcdf/website
dd43ad4214d51d911beae3ecead16705736a5148
routes/users.js
routes/users.js
'use strict'; const userCtr = require('./../controllers/users.js'); const authentication = require('./../middleware/authentication'); const authorisation = require('./../middleware/authorisation'); const userRoutes = (router) => { router .route('/users') .post(userCtr.create); }; module.exports = userRoutes;
'use strict'; const userCtr = require('./../controllers/users.js'); const userAuth = require('./../controllers/authentication.js'); const authentication = require('./../middleware/authentication'); const authorisation = require('./../middleware/authorisation'); const userRoutes = (router) => { router .route('/users') .post(userCtr.create); router.post('/users/login', userAuth.signin); router.post('/users/logout', userAuth.signout); }; module.exports = userRoutes;
Add authentication controller to handle user authentication
Add authentication controller to handle user authentication
JavaScript
mit
andela-oolutola/document-management-system-api
57153e83cc810e5bb5f4c9a6774cc8a9163acddd
addon/helpers/elem.js
addon/helpers/elem.js
import Ember from 'ember'; import { elem, mod } from 'ember-cli-bem/mixins/bem'; const { HTMLBars: { makeBoundHelper }, } = Ember; const BLOCK_KEY = 'blockName'; export default makeBoundHelper(function(params, hash) { const blockName = hash[BLOCK_KEY]; const [ elemName ] = params; if (!blockName) { throw Error(`${BLOCK_KEY} is required for 'elem' helper`); } const elemClassName = elem(blockName, elemName); const modNames = Object.keys(hash).filter((key) => key !== BLOCK_KEY); const modClassNames = modNames.map((modName) => { const modValue = hash[modName]; return mod(elemClassName, { modName, modValue }); }); return [elemClassName, ...modClassNames].filter(Boolean).join(' '); });
import Ember from 'ember'; import { elem, mod } from 'ember-cli-bem/mixins/bem'; const { Helper: { helper } } = Ember; const BLOCK_KEY = 'blockName'; export default helper(function(params, hash) { const blockName = hash[BLOCK_KEY]; const [ elemName ] = params; if (!blockName) { throw Error(`${BLOCK_KEY} is required for 'elem' helper`); } const elemClassName = elem(blockName, elemName); const modNames = Object.keys(hash).filter((key) => key !== BLOCK_KEY); const modClassNames = modNames.map((modName) => { const modValue = hash[modName]; return mod(elemClassName, { modName, modValue }); }); return [elemClassName, ...modClassNames].filter(Boolean).join(' '); });
Remove makeBoundHelper in favor of helper.
Remove makeBoundHelper in favor of helper.
JavaScript
mit
nikityy/ember-cli-bem,nikityy/ember-cli-bem
57103d1f7e4eee6f4405de13c9650663395b0007
src/storage-queue/index.js
src/storage-queue/index.js
var azure = require("azure-storage"); // var nconf = require("nconf"); nconf.env() .file({ file: "config.json", search: true }); var storageName = nconf.get("StorageName"); var storageKey = nconf.get("StorageKey"); var dev = nconf.get("NODE_ENV");
var azure = require("azure-storage"); // var nconf = require("nconf"); nconf.env() .file({ file: "config.json", search: true }); var QueueName = "my-queue"; var storageName = nconf.get("StorageName"); var storageKey = nconf.get("StorageKey"); var dev = nconf.get("NODE_ENV"); // var retryOperations = new azure.ExponentialRetryPolicyFilter(); var queueSvc = azure.createQueueService(storageName, storageKey).withFilter(retryOperations); if(queueSvc) { queueSvc.createQueueIfNotExists(QueueName, function(error, results, response) { if(error) { return; } var created = results; if(created) { console.log("created new queue"); } else { console.log("queue already exists"); } var ticket = { EventId: 4711, Email: "peter@example.com", NumberOfTickets: 2, OrderDate: Date.UTC }; var msg = JSON.stringify(ticket); queueSvc.createMessage(QueueName, msg, function(error, result, response) { if(error) { return; } queueSvc.peekMessages(QueueName, { numOfMessages: 32 }, function(error, result, response){ if(!error){ // Message text is in messages[0].messagetext } }); }); }); }
Add couple of simple queue access methods
Add couple of simple queue access methods
JavaScript
mit
peterblazejewicz/azure-aspnet5-examples,peterblazejewicz/azure-aspnet5-examples
7772afb9c69d5c6e4ffc0bbe6507eaf1df257293
app/js/arethusa.core/routes/main.constant.js
app/js/arethusa.core/routes/main.constant.js
"use strict"; angular.module('arethusa.core').constant('MAIN_ROUTE', { controller: 'MainCtrl', template: '<div ng-include="template"></div>', resolve: { loadConfiguration: function($http, confUrl, configurator) { return $http.get(confUrl(true)).then(function(res) { configurator.defineConfiguration(res.data); }); } } });
"use strict"; angular.module('arethusa.core').constant('MAIN_ROUTE', { controller: 'MainCtrl', template: '<div ng-include="template"></div>', resolve: { loadConfiguration: function($http, confUrl, configurator) { var url = confUrl(true); return $http.get(url).then(function(res) { configurator.defineConfiguration(res.data, url); }); } } });
Add the location of a conf file in main route
Add the location of a conf file in main route
JavaScript
mit
Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa
dd1adfab80874c850279a5bd29f1d41c340455c6
jet/static/jet/js/src/layout-updaters/user-tools.js
jet/static/jet/js/src/layout-updaters/user-tools.js
var $ = require('jquery'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; }; UserToolsUpdater.prototype = { updateUserTools: function($usertools) { var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); $('<li>').addClass('user-tools-welcome-msg').text(user).appendTo($list); $usertools.find('a').each(function() { var $link = $(this); $('<li>').addClass('user-tools-link').html($link).appendTo($list); }); $usertools.empty().addClass('user-tools').append($list); $list.on('mouseenter', function() { $list.addClass('opened'); }); $list.on('mouseleave', function() { $list.removeClass('opened'); }); }, run: function() { try { this.updateUserTools(this.$usertools); } catch (e) { console.error(e); } this.$usertools.addClass('initialized'); } }; $(document).ready(function() { $('#user-tools').each(function() { new UserToolsUpdater($(this)).run(); }); });
var $ = require('jquery'); require('browsernizr/test/touchevents'); require('browsernizr'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; }; UserToolsUpdater.prototype = { updateUserTools: function($usertools) { var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); $('<li>') .addClass('user-tools-welcome-msg') .text(user).appendTo($list) .on('click', function() { if ($(document.documentElement).hasClass('touchevents')) { $list.toggleClass('opened'); } }); $usertools.find('a').each(function() { var $link = $(this); $('<li>').addClass('user-tools-link').html($link).appendTo($list); }); $usertools.empty().addClass('user-tools').append($list); $list.on('mouseenter', function() { $list.addClass('opened'); }).on('mouseleave', function() { $list.removeClass('opened'); }); }, run: function() { try { this.updateUserTools(this.$usertools); } catch (e) { console.error(e); } this.$usertools.addClass('initialized'); } }; $(document).ready(function() { $('#user-tools').each(function() { new UserToolsUpdater($(this)).run(); }); });
Add user tools closing by click
Add user tools closing by click
JavaScript
agpl-3.0
rcotrina94/django-jet,geex-arts/django-jet,pombredanne/django-jet,SalahAdDin/django-jet,geex-arts/django-jet,pombredanne/django-jet,SalahAdDin/django-jet,SalahAdDin/django-jet,rcotrina94/django-jet,rcotrina94/django-jet,geex-arts/django-jet,pombredanne/django-jet
f5f6841d299d4bcfcde428130d48ef7266b36747
dev/staticRss.js
dev/staticRss.js
'use strict'; var moment = require('moment'); var _ = require('lodash'); var config = require('../config'); var paths = require('../elements/PathsMixin'); module.exports = function(page) { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), t('link', {href: "#{config.baseUrl}atom.xml", rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl), t('author', {}, [ t('name', {}, config.author.name), t('email', {}, config.author.email), ]), _.map(paths.getAllPosts(), function(post, name) { return t('entry', {}, [ t('title', {}, post.title), t('link', {href: config.baseUrl + name}, ''), t('updated', {}, moment(post.date, 'YYYY-MM-DD').format()), t('content', {type: 'html'}, paths.getPostForPath(name)), ]); }).join('') ]); }; function t(name, attributes, content) { var attrStr = _.map(attributes, function(val, key) { return key + '=' + '"' + val + '"'; }).join(' '); if(_.isArray(content)) { content = content.join(''); } return '<' + name + ' ' + attrStr + '>' + content + '>/' + name + '>'; }
'use strict'; var moment = require('moment'); var _ = require('lodash'); var config = require('../config'); var paths = require('../elements/PathsMixin'); module.exports = function() { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), t('link', {href: 'config.baseUrl' + 'atom.xml', rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl), t('author', {}, [ t('name', {}, config.author.name), t('email', {}, config.author.email), ]), _.map(paths.getAllPosts(), function(post, name) { return t('entry', {}, [ t('title', {}, post.title), t('link', {href: config.baseUrl + name}, ''), t('updated', {}, moment(post.date, 'YYYY-MM-DD').format()), t('content', {type: 'html'}, paths.getPostForPath(name)), ]); }).join('') ]); }; function t(name, attributes, content) { var attrStr = _.map(attributes, function(val, key) { return key + '=' + '"' + val + '"'; }).join(' '); if(_.isArray(content)) { content = content.join(''); } return '<' + name + ' ' + attrStr + '>' + content + '>/' + name + '>'; }
Fix typo at RSS bit
Fix typo at RSS bit
JavaScript
mit
antwarjs/antwar,RamonGebben/antwar,RamonGebben/antwar
a51e96883d8fcc394ac1e2b4744c5634fb16184b
reviewboard/static/rb/js/resources/models/apiTokenModel.js
reviewboard/static/rb/js/resources/models/apiTokenModel.js
RB.APIToken = RB.BaseResource.extend({ defaults: _.defaults({ tokenValue: null, note: null, policy: {}, userName: null }, RB.BaseResource.prototype.defaults), rspNamespace: 'api_token', url: function() { var url = SITE_ROOT + (this.get('localSitePrefix') || '') + 'api/users/' + this.get('userName') + '/api-tokens/'; if (!this.isNew()) { url += this.id + '/'; } return url; }, toJSON: function() { return { note: this.get('note'), policy: JSON.stringify(this.get('policy')) }; }, parseResourceData: function(rsp) { return { tokenValue: rsp.token, note: rsp.note, policy: rsp.policy }; } }, { defaultPolicies: { readWrite: {}, readOnly: { resources: { '*': { allow: ['GET', 'HEAD', 'OPTIONS'], block: ['*'] } } }, custom: { resources: { '*': { allow: ['*'], block: [] } } } } });
RB.APIToken = RB.BaseResource.extend({ defaults: function() { return _.defaults({ tokenValue: null, note: null, policy: {}, userName: null }, RB.BaseResource.prototype.defaults()); }, rspNamespace: 'api_token', url: function() { var url = SITE_ROOT + (this.get('localSitePrefix') || '') + 'api/users/' + this.get('userName') + '/api-tokens/'; if (!this.isNew()) { url += this.id + '/'; } return url; }, toJSON: function() { return { note: this.get('note'), policy: JSON.stringify(this.get('policy')) }; }, parseResourceData: function(rsp) { return { tokenValue: rsp.token, note: rsp.note, policy: rsp.policy }; } }, { defaultPolicies: { readWrite: {}, readOnly: { resources: { '*': { allow: ['GET', 'HEAD', 'OPTIONS'], block: ['*'] } } }, custom: { resources: { '*': { allow: ['*'], block: [] } } } } });
Update the RB.APIToken resource to use a defaults function
Update the RB.APIToken resource to use a defaults function This change updates the `RB.APIToken` resource to use the new `defaults` function that all other resources are using. Testing Done: Ran JS tests. Reviewed at https://reviews.reviewboard.org/r/7394/
JavaScript
mit
KnowNo/reviewboard,chipx86/reviewboard,brennie/reviewboard,beol/reviewboard,davidt/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,brennie/reviewboard,beol/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,brennie/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,davidt/reviewboard,brennie/reviewboard,custode/reviewboard,custode/reviewboard,davidt/reviewboard,chipx86/reviewboard,bkochendorfer/reviewboard,beol/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,beol/reviewboard
c5caa31810a39e69ddb281143ecac063d0a9e3d5
app/services/data/get-individual-overview.js
app/services/data/get-individual-overview.js
const knex = require('../../../knex').web module.exports = function (id) { return knex('individual_case_overview') .first('grade_code AS grade', 'team_id AS teamId', 'team_name AS teamName', 'available_points AS availablePoints', 'total_points AS totalPoints', 'total_cases AS cases', 'contracted_hours AS contractedHours', 'reduction_hours AS reduction') .where('workload_owner_id', id) }
const knex = require('../../../knex').web module.exports = function (id) { var table = 'individual_case_overview' var whereClause = '' if (id !== undefined) { whereClause = ' WHERE workload_owner_id = ' + id } var selectColumns = [ 'grade_code AS grade', 'team_id AS teamId', 'team_name AS teamName', 'available_points AS availablePoints', 'total_points AS totalPoints', 'total_cases AS cases', 'contracted_hours AS contractedHours', 'reduction_hours AS reduction' ] return knex.raw( 'SELECT TOP (1) ' + selectColumns.join(', ') + ' FROM ' + table + ' WITH (NOEXPAND)' + whereClause ) .then(function (results) { return results[0] }) }
Add noexpand to individual overview
Add noexpand to individual overview
JavaScript
mit
ministryofjustice/wmt-web,ministryofjustice/wmt-web
0da039bab055f1c5c90f6424b67159bcb13b3577
app/assets/javascripts/lib/analytics/travel_insurance_omniture.js
app/assets/javascripts/lib/analytics/travel_insurance_omniture.js
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var analytics = new Analytics(); analytics.trackView(); // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(document).on("click", function() { windowUnloadedFromSubmitClick = false; }); // When the user clicks on the submit button, track that it's what // is causing the onbeforeunload event to fire (below) $(document).on("click", "button.cta-button-primary", function(e) { windowUnloadedFromSubmitClick = true; e.stopPropagation(); }); // Before redirection (which the WN widget does, it's not a form submit) // if the user clicked on the submit button, track click with Omniture window.onbeforeunload = function() { if (windowUnloadedFromSubmitClick) { window.s.events = "event42"; window.s.t(); } }; });
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var analytics = new Analytics(); if (window.lp.hasOwnProperty("tracking") && window.lp.tracking.hasOwnProperty("eVar12") && window.lp.tracking.eVar12 !== "dest essential information") { analytics.trackView(); } // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(document).on("click", function() { windowUnloadedFromSubmitClick = false; }); // When the user clicks on the submit button, track that it's what // is causing the onbeforeunload event to fire (below) $(document).on("click", "button.cta-button-primary", function(e) { windowUnloadedFromSubmitClick = true; e.stopPropagation(); }); // Before redirection (which the WN widget does, it's not a form submit) // if the user clicked on the submit button, track click with Omniture window.onbeforeunload = function() { if (windowUnloadedFromSubmitClick) { window.s.events = "event42"; window.s.t(); } }; });
Make sure Essential information is not double tracked
Make sure Essential information is not double tracked
JavaScript
mit
Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo,Lostmyname/rizzo,Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo
a76a96c708c5e6b111bbfff14415b794065d28ee
examples/links/webpack.config.js
examples/links/webpack.config.js
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js'] }, module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, { test: /\.css?$/, loaders: ['style', 'raw'] }] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js'], alias: { 'react': path.join(__dirname, '..', '..', 'node_modules', 'react') } }, module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, { test: /\.css?$/, loaders: ['style', 'raw'] }] } };
Use React from root project to avoid duplicate React problem
Use React from root project to avoid duplicate React problem
JavaScript
mit
rackt/redux-router,acdlite/redux-router,mjrussell/redux-router
8fadc42c9711d08efb182eb0d865c51fd39645af
src/chunkify.js
src/chunkify.js
function* chunkify(start, final, chunk, delay) { for (let index = start; index < final; index++) { if ((index > start) && (index % (start + chunk) === 0)) { yield new Promise(resolve => setTimeout(resolve, delay)) } yield index } } export default { interval: ({start, final, chunk, delay}) => { return chunkify(start, final, chunk, delay) } }
let pending_delay_error = (index) => { let pending_delay = `pending delay at index: ${index}; `; pending_delay += `wait ${delay} milliseconds before `; pending_delay += `further invocations of .next()`; throw new Error(pending_delay) }; // Return values from the range `start` to `final` synchronously when between // intervals of size `chunk`. // // Otherwise, return a promise that resolves in `delay` milliseconds. // // An error will be thrown in case the iterator is advanced before a // pending promise has resolved. function* chunkify(start, final, chunk, delay) { let delayed = null; let pending = null; function* do_delay() { yield new Promise(resolve => { setTimeout(() => { delayed = false; pending = false; resolve(); }, delay) }) } for (let index = start; index < final; index++) { if ((index > start) && (index % (start + chunk) === 0)) { delayed = true; pending = true; yield* do_delay() } if (delayed && pending) { pending_delay_error(index); } yield index } } export default { interval: ({start, final, chunk, delay}) => { return chunkify(start, final, chunk, delay) } }
Throw error if iterator advances if delay is pending
Throw error if iterator advances if delay is pending
JavaScript
mit
yangmillstheory/chunkify,yangmillstheory/chunkify
b5b5aa719f9e28fa73af44179cf2c8648728a646
src/demo/js/ephox/snooker/demo/DemoTranslations.js
src/demo/js/ephox/snooker/demo/DemoTranslations.js
define( 'ephox.snooker.demo.DemoTranslations', [ 'global!Array' ], function (Array) { var keys = { 'table.picker.rows': '{0} high', 'table.picker.cols': '{0} wide' }; return function (key) { if (keys[key] === undefined) throw 'key ' + key + ' not found'; var r = keys[key]; if (arguments.length > 1) { var parameters = Array.prototype.slice.call(arguments, 1); return r.replace(/\{(\d+)\}/g, function (match, contents) { var index = parseInt(contents, 10); if (parameters[index] === undefined) throw 'No value for token: ' + match + ' in translation: ' + r; return parameters[index]; }); } else { return r; } }; } );
define( 'ephox.snooker.demo.DemoTranslations', [ ], function () { return { row: function (row) { return row + ' high'; }, col: function (col) { return col + ' wide'; } }; } );
Update Demo Translations for echo change
Update Demo Translations for echo change
JavaScript
lgpl-2.1
FernCreek/tinymce,tinymce/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce,TeamupCom/tinymce
900e6845b52ba6389914f85c06d0d09cf07dc342
test/renderer/path-spec.js
test/renderer/path-spec.js
import { expect } from 'chai'; import { remote } from 'electron'; import { defaultPathFallback, cwdKernelFallback } from '../../src/notebook/path'; describe('defaultPathFallback', () => { it('returns a object with the defaultPath', () => { const path = defaultPathFallback('dummy-path'); expect(path).to.deep.equal({ defaultPath: 'dummy-path' }); }); it('returns a object with the correct path', () => { process.chdir('/') const path = defaultPathFallback(); expect(path).to.deep.equal({ defaultPath: '/home/home/on/the/range' }); }); });
import { expect } from 'chai'; import { remote } from 'electron'; import { defaultPathFallback, cwdKernelFallback } from '../../src/notebook/path'; describe('defaultPathFallback', () => { it('returns a object with the defaultPath', () => { const path = defaultPathFallback('dummy-path'); expect(path).to.deep.equal({ defaultPath: 'dummy-path' }); }); it('returns a object with the correct path', () => { if (process.platform !== 'win32') { process.chdir('/') const path = defaultPathFallback(); expect(path).to.deep.equal({ defaultPath: '/home/home/on/the/range' }); } }); });
Disable path fallback test on windows
chore(tests): Disable path fallback test on windows
JavaScript
bsd-3-clause
jdfreder/nteract,nteract/composition,rgbkrk/nteract,rgbkrk/nteract,captainsafia/nteract,0u812/nteract,nteract/composition,0u812/nteract,jdetle/nteract,0u812/nteract,jdetle/nteract,nteract/nteract,jdetle/nteract,rgbkrk/nteract,jdfreder/nteract,nteract/nteract,rgbkrk/nteract,nteract/nteract,temogen/nteract,nteract/nteract,temogen/nteract,nteract/nteract,captainsafia/nteract,captainsafia/nteract,nteract/composition,jdetle/nteract,jdfreder/nteract,rgbkrk/nteract,0u812/nteract,captainsafia/nteract,jdfreder/nteract,temogen/nteract