commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
6ec2bff81999a815fe44f1ddf3a02c9edc46829c
index.js
index.js
/* * gaze * https://github.com/shama/gaze * * Copyright (c) 2014 Kyle Robinson Young * Licensed under the MIT license. */ try { // Attempt to resolve optional pathwatcher require('bindings')('pathwatcher.node'); var version = process.versions.node.split('.'); module.exports = (version[0] === '0' && version[1] === '8') ? require('./lib/gaze04.js') : require('./lib/gaze.js'); } catch (err) { // Otherwise serve gaze04 module.exports = require('./lib/gaze04.js'); }
/* * gaze * https://github.com/shama/gaze * * Copyright (c) 2014 Kyle Robinson Young * Licensed under the MIT license. */ // If on node v0.8, serve gaze04 var version = process.versions.node.split('.'); if (version[0] === '0' && version[1] === '8') { module.exports = require('./lib/gaze04.js'); } else { try { // Check whether pathwatcher successfully built without running it require('bindings')({ bindings: 'pathwatcher.node', path: true }); // If successfully built, give the better version module.exports = require('./lib/gaze.js'); } catch (err) { // Otherwise serve gaze04 module.exports = require('./lib/gaze04.js'); } }
Determine whether pathwatcher built without running it. Ref GH-98.
Determine whether pathwatcher built without running it. Ref GH-98.
JavaScript
mit
bevacqua/gaze,modulexcite/gaze,bevacqua/gaze,prodatakey/gaze,modulexcite/gaze,bevacqua/gaze,prodatakey/gaze,modulexcite/gaze,prodatakey/gaze
0d0bc8deee992e72d593ec6e4f2cb038eff22614
index.js
index.js
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'Access-Control-Max-Age': '86400', 'Access-Control-Allow-Headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept" }; // Create a proxy server pointing at spreadsheets.google.com. //var proxy = httpProxy.createProxyServer({target: 'https://spreadsheets.google.com'}); var proxy = httpProxy.createProxyServer(); http.createServer(function(req, res) { if (req.method === 'OPTIONS') { res.writeHead(200, CORS_HEADERS); res.end(); return } delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); }).listen(process.env.PORT || 5000);
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'access-control-max-age': '86400', 'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }; // Create a proxy server pointing at spreadsheets.google.com. //var proxy = httpProxy.createProxyServer({target: 'https://spreadsheets.google.com'}); var proxy = httpProxy.createProxyServer(); https.createServer(function(req, res) { if (req.method === 'OPTIONS') { // Respond to OPTIONS requests advertising we support full CORS for * res.writeHead(200, CORS_HEADERS); res.end(); return } // Remove our original host so it doesn't mess up Google's header parsing. delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); // Add CORS headers to every other request also. proxy.on('proxyRes', function(proxyRes, req, res) { for (var key in CORS_HEADERS) { proxyRes.headers[key] = CORS_HEADERS[key]; } }); }).listen(process.env.PORT || 5000);
Fix CORS handling for POST and DELETE
Fix CORS handling for POST and DELETE
JavaScript
mpl-2.0
yourcelf/gspreadsheets-cors-proxy
c722da297169e89fc6d79860c2c305dc3b4a1c60
index.js
index.js
'use strict' var path = require('path') module.exports = function (file) { var segments = file.split(path.sep) var index = segments.lastIndexOf('node_modules') if (index === -1) return if (!segments[index + 1]) return var scoped = segments[index + 1].indexOf('@') === 0 var name = scoped ? segments[index + 1] + '/' + segments[index + 2] : segments[index + 1] if (!name) return var offset = scoped ? 3 : 2 return { name: name, basedir: segments.slice(0, index + offset).join(path.sep), path: segments.slice(index + offset).join(path.sep) } }
'use strict' var path = require('path') module.exports = function (file) { var segments = file.split(path.sep) var index = segments.lastIndexOf('node_modules') if (index === -1) return if (!segments[index + 1]) return var scoped = segments[index + 1][0] === '@' var name = scoped ? segments[index + 1] + '/' + segments[index + 2] : segments[index + 1] if (!name) return var offset = scoped ? 3 : 2 return { name: name, basedir: segments.slice(0, index + offset).join(path.sep), path: segments.slice(index + offset).join(path.sep) } }
Improve speed of detection of scoped packages
Improve speed of detection of scoped packages
JavaScript
mit
watson/module-details-from-path
66de12f38c0d0021dad895070e9b823d99d433e4
index.js
index.js
'use strict'; const YQL = require('yql'); const _ = require('lodash'); module.exports = (opts, callback) => { opts = opts || []; let query; if (_.isEmpty(opts)) { query = new YQL('select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Dhaka, Bangladesh")'); } else { query = new YQL('select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="' + opts[0] + ', ' + opts[1] + '")'); } query.exec((err, response) => { if (err) { return callback(err); } callback(null, response); }); };
'use strict'; const axios = require('axios'); const API_URL = 'https://micro-weather.now.sh'; module.exports = (opts) => { let city = opts[0] || 'Dhaka'; let country = opts[1] || 'Bangladesh'; return axios.get(`${API_URL}?city=${city}&country=${country}`); };
Refactor main weather module to use API
Refactor main weather module to use API Signed-off-by: Riyadh Al Nur <d7e60315016355bdcd32d48dde148183e3d8bb86@verticalaxisbd.com>
JavaScript
mit
riyadhalnur/weather-cli
69a1ac6f09fef4f7954677a005ebfe32235ed5cd
index.js
index.js
import React from 'react'; import Match from 'react-router/Match'; import Miss from 'react-router/Miss'; import Users from './Users'; class UsersRouting extends React.Component { NoMatch() { return <div> <h2>Uh-oh!</h2> <p>How did you get to <tt>{this.props.location.pathname}</tt>?</p> </div> } render() { var pathname = this.props.pathname; var connect = this.props.connect; console.log("matching location:", this.props.location.pathname); return <div> <h1>Users module</h1> <Match exactly pattern={`${pathname}`} component={connect(Users)}/> <Match exactly pattern={`${pathname}/:query`} component={connect(Users)}/> <Match pattern={`${pathname}/:query?/view/:userid`} component={connect(Users)}/> <Miss component={this.NoMatch.bind(this)}/> </div> } } export default UsersRouting;
import React from 'react'; import Match from 'react-router/Match'; import Miss from 'react-router/Miss'; import Users from './Users'; class UsersRouting extends React.Component { constructor(props){ super(props); this.connectedUsers = props.connect(Users); } NoMatch() { return <div> <h2>Uh-oh!</h2> <p>How did you get to <tt>{this.props.location.pathname}</tt>?</p> </div> } render() { var pathname = this.props.pathname; var connect = this.props.connect; console.log("matching location:", this.props.location.pathname); return <div> <h1>Users module</h1> <Match exactly pattern={`${pathname}`} component={this.connectedUsers}/> <Match exactly pattern={`${pathname}/:query`} component={this.connectedUsers}/> <Match pattern={`${pathname}/:query?/view/:userid`} component={this.connectedUsers}/> <Miss component={this.NoMatch.bind(this)}/> </div> } } export default UsersRouting;
Call connect() on the Users component only once, and cache the result. This seems to fix STRIPES-97 at last!
Call connect() on the Users component only once, and cache the result. This seems to fix STRIPES-97 at last!
JavaScript
apache-2.0
folio-org/ui-users,folio-org/ui-users
9a7bada461b9c2096b282952333eb6869aa613cb
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-ui-sortable', included: function(app) { app.import(app.bowerDirectory + '/jquery-ui/ui/version.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/data.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/ie.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/safe-active-element.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/safe-blur.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/scroll-parent.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widget.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/mouse.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/sortable.js'); } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-ui-sortable', included: function(app) { app.import(app.bowerDirectory + '/jquery-ui/ui/version.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/data.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/ie.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/safe-active-element.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/safe-blur.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/scroll-parent.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/plugin.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widget.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/mouse.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/draggable.js'); app.import(app.bowerDirectory + '/jquery-ui/ui/widgets/sortable.js'); } };
Update dependencies to be an exact copy of jquery-ui's custom download option
Update dependencies to be an exact copy of jquery-ui's custom download option
JavaScript
mit
12StarsMedia/ember-ui-sortable,12StarsMedia/ember-ui-sortable
3c660bb65805957ef71481c97277c0093cae856a
tests/integration/lambda-invoke/lambdaInvokeHandler.js
tests/integration/lambda-invoke/lambdaInvokeHandler.js
'use strict' const { config, Lambda } = require('aws-sdk') const { stringify } = JSON config.update({ accessKeyId: 'ABC', secretAccessKey: 'SECRET', }) const lambda = new Lambda({ apiVersion: '2015-03-31', endpoint: 'http://localhost:3000', }) exports.noPayload = async function noPayload() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.testHandler = async function testHandler() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', Payload: stringify({ event: { foo: 'bar' } }), } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.invokedHandler = async function invokedHandler(event) { return { event, } }
'use strict' const { config, Lambda } = require('aws-sdk') const { stringify } = JSON config.update({ accessKeyId: 'ABC', secretAccessKey: 'SECRET', }) const lambda = new Lambda({ apiVersion: '2015-03-31', endpoint: 'http://localhost:3000', }) exports.noPayload = async function noPayload() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.testHandler = async function testHandler() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', Payload: stringify({ foo: 'bar' }), } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.invokedHandler = async function invokedHandler(event) { return { event, } }
Fix lambda invoke with no payload
Fix lambda invoke with no payload
JavaScript
mit
dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline
9a38407db4740cb027f40cf2dbd7c4fbf3996816
test/e2e/view-offender-manager-overview.js
test/e2e/view-offender-manager-overview.js
const expect = require('chai').expect const dataHelper = require('../helpers/data/aggregated-data-helper') var workloadOwnerId var workloadOwnerGrade describe('View overview', function () { before(function () { return dataHelper.selectIdsForWorkloadOwner() .then(function (results) { var workloadOwnerIds = results.filter((item) => item.table === 'workload_owner') workloadOwnerId = workloadOwnerIds[workloadOwnerIds.length - 1].id return results }) .then(function (results) { dataHelper.selectGradeForWorkloadOwner(workloadOwnerId) .then(function (gradeResult) { workloadOwnerGrade = gradeResult }) }) }) it('should navigate to the overview page', function () { return browser.url('/offender-manager/' + workloadOwnerId + '/overview') .waitForExist('.breadcrumbs') .waitForExist('.sln-subnav') .waitForExist('.sln-grade') .getText('.sln-grade') .then(function (text) { expect(text).to.equal(workloadOwnerGrade) }) }) })
const expect = require('chai').expect const dataHelper = require('../helpers/data/aggregated-data-helper') var workloadOwnerId var workloadOwnerGrade describe('View overview', function () { before(function () { return dataHelper.selectIdsForWorkloadOwner() .then(function (results) { var workloadOwnerIds = results.filter((item) => item.table === 'workload_owner') workloadOwnerId = workloadOwnerIds[0].id return results }) .then(function (results) { dataHelper.selectGradeForWorkloadOwner(workloadOwnerId) .then(function (gradeResult) { workloadOwnerGrade = gradeResult }) }) }) it('should navigate to the overview page', function () { return browser.url('/offender-manager/' + workloadOwnerId + '/overview') .waitForExist('.breadcrumbs') .waitForExist('.sln-subnav') .waitForExist('.sln-grade') .getText('.sln-grade') .then(function (text) { expect(text).to.equal(workloadOwnerGrade) }) }) })
Use the first workload owner id in e2e test
Use the first workload owner id in e2e test
JavaScript
mit
ministryofjustice/wmt-web,ministryofjustice/wmt-web
72be6e08669779cbd6a6ed55d56cfb45b857dc95
share/spice/tfl_status/tfl_status.js
share/spice/tfl_status/tfl_status.js
(function (env) { "use strict"; env.ddg_spice_tfl_status = function(api_result){ Spice.add({ id: "tfl_status", name: "Travel", data: api_result, meta: { sourceName: "tfl.gov.uk", sourceUrl: 'http://tfl.gov.uk/tube-dlr-overground/status/#line-' + api_result.id, }, templates: { group: 'base', options: { content: Spice.tfl_status.content, moreAt: true } } }); }; }(this));
(function (env) { "use strict"; env.ddg_spice_tfl_status = function(api_result){ Spice.add({ id: "tfl_status", name: "Travel", data: api_result, meta: { sourceName: "tfl.gov.uk", sourceUrl: 'http://tfl.gov.uk/tube-dlr-overground/status/#line-' + api_result[0].id, }, templates: { group: 'base', options: { content: Spice.tfl_status.content, moreAt: true } } }); }; }(this));
Fix for the "More at..." link to correct lineId
Fix for the "More at..." link to correct lineId The sourceUrl link which controls the "More at tfl.gov.uk" href is now fixed to link to the correct anchor for the line in question. This will open the further information accordion and zoom the SVG map to the correct line. (There appears to be an issue with the lineIds being incorrect on the map on tfl.gov.uk at the moment?)
JavaScript
apache-2.0
sagarhani/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,levaly/zeroclickinfo-spice,lernae/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mayo/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,ppant/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,loganom/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,loganom/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,levaly/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,sevki/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,stennie/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,soleo/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,mayo/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,loganom/zeroclickinfo-spice,P71/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,echosa/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,imwally/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,echosa/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,imwally/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,echosa/zeroclickinfo-spice,stennie/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,soleo/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,stennie/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,imwally/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,echosa/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,ppant/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,imwally/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,lernae/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,sevki/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,levaly/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,soleo/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,levaly/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,mayo/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,stennie/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lernae/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,soleo/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,sevki/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,deserted/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,loganom/zeroclickinfo-spice,soleo/zeroclickinfo-spice,lerna/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,sevki/zeroclickinfo-spice,ppant/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,P71/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,lerna/zeroclickinfo-spice,mayo/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,lerna/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,levaly/zeroclickinfo-spice,deserted/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,P71/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,ppant/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,echosa/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,deserted/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,P71/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,deserted/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,soleo/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice
798f0a318578df8f91744accf1ec1a55310ee6ef
docs/ember-cli-build.js
docs/ember-cli-build.js
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Add options here }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. return app.toTree(); };
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { fingerprint: { prepend: '/Julz.jl/' } }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. return app.toTree(); };
Prepend ember fingerprints with Julz.jl path
Prepend ember fingerprints with Julz.jl path
JavaScript
mit
djsegal/julz,djsegal/julz
b1d90a138b7d285c0764d930b5b430b4e49ac2b0
milliseconds-to-iso-8601-duration.js
milliseconds-to-iso-8601-duration.js
(function (millisecondsToISO8601Duration) { 'use strict'; millisecondsToISO8601Duration.iso8601duration = function(milliseconds) { var offset = Math.floor(milliseconds); var milliseconds = offset % 1000; offset = Math.floor(offset / 1000); var seconds = offset % 60; offset = Math.floor(offset / 60); var minutes = offset % 60; offset = Math.floor(offset / 60); var hours = offset % 24; var days = Math.floor(offset / 24); var parts = ['P']; if (days) { parts.push(days + 'D'); } if (hours || minutes || seconds || milliseconds) { parts.push('T'); if (hours) { parts.push(hours + 'H'); } if (minutes) { parts.push(minutes + 'M'); } if (seconds || milliseconds) { parts.push(seconds); if (milliseconds) { parts.push('.' + milliseconds); } parts.push('S'); } } return parts.join('') }; })(typeof exports === 'undefined' ? millisecondsToISO8601Duration = {} : exports);
(function (millisecondsToISO8601Duration) { 'use strict'; millisecondsToISO8601Duration.iso8601duration = function(milliseconds) { var offset = Math.floor(milliseconds); var milliseconds = offset % 1000; offset = Math.floor(offset / 1000); var seconds = offset % 60; offset = Math.floor(offset / 60); var minutes = offset % 60; offset = Math.floor(offset / 60); var hours = offset % 24; var days = Math.floor(offset / 24); var parts = ['P']; if (days) { parts.push(days + 'D'); } if (hours || minutes || seconds || milliseconds) { parts.push('T'); if (hours) { parts.push(hours + 'H'); } if (minutes) { parts.push(minutes + 'M'); } if (seconds || milliseconds) { parts.push(seconds); if (milliseconds) { milliseconds = milliseconds.toString(); while (milliseconds.length < 3) { milliseconds = '0' + milliseconds; } parts.push('.' + milliseconds); } parts.push('S'); } } return parts.join('') }; })(typeof exports === 'undefined' ? millisecondsToISO8601Duration = {} : exports);
Handle zero-padding for millisecond component
Handle zero-padding for millisecond component Fixes tests for 1 and 12 milliseconds.
JavaScript
mit
wking/milliseconds-to-iso-8601-duration,wking/milliseconds-to-iso-8601-duration
955e8af495b9e43585fd088c8ed21fa92fb6307b
imports/api/events.js
imports/api/events.js
import { Mongo } from 'meteor/mongo'; export const Events = new Mongo.Collection('events');
import { Mongo } from 'meteor/mongo'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; export const Events = new Mongo.Collection('events'); Events.deny({ insert() { return true; }, update() { return true; }, remove() { return true; } }); export const createEvent = new ValidatedMethod({ name: 'events.create', validate: new SimpleSchema({ name: { type: String }, place: { type: String }, type: { type: String }, description: { type: String }, when: { type: Date }, howMany: { type: Number } }).validator(), run({ name, place, type, description, when, howMany }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } return Events.insert({ owner: this.userId, name, place, type, description, when, howMany }); } });
Add method to create an event
Add method to create an event
JavaScript
mit
f-martinez11/ActiveU,f-martinez11/ActiveU
c335e4816d0d7037dc2d9ea3fb02005612e16d9a
rollup.config.js
rollup.config.js
import uglify from "rollup-plugin-uglify" export default { plugins: [ uglify() ] }
import uglify from "rollup-plugin-uglify" export default { plugins: [ uglify({ compress: { collapse_vars: true, pure_funcs: ["Object.defineProperty"] } }) ] }
Optimize uglifyjs's output via options.
Optimize uglifyjs's output via options.
JavaScript
mit
jbucaran/hyperapp,hyperapp/hyperapp,hyperapp/hyperapp
fd9b4b9c8f7196269f84a77522bf3fd90ee360ff
www/js/load-ionic.js
www/js/load-ionic.js
(function () { var options = (function () { // Holy shit var optionsArray = location.href.split('?')[1].split('#')[0].split('=') var result = {} optionsArray.forEach(function (value, index) { // 0 is a property name and 1 the value of 0 if (index % 2 === 1) { return } result[value] = optionsArray[index + 1] }); return result }()) var toLoadSrc; if (options.ionic === 'build') { toLoadSrc = 'lib/ionic/local/ionic.bundle.js' } else if (options.ionic === 'local' || !options.ionic) { toLoadSrc = 'lib/ionic/js/ionic.bundle.js' } else { // Use options.ionic as ionic version toLoadSrc = '//code.ionicframework.com/' + options.ionic + '/js/ionic.bundle.min.js' } console.log('Ionic From') console.log(toLoadSrc) document.write('<script src="'+ toLoadSrc +'"></script>') }())
(function () { var options = (function () { // Holy shit var optionsArray var result = {} try { optionsArray = location.href.split('?')[1].split('#')[0].split('=') } catch (e) { return {} } optionsArray.forEach(function (value, index) { // 0 is a property name and 1 the value of 0 if (index % 2 === 1) { return } result[value] = optionsArray[index + 1] }); return result }()) var toLoadSrc; if (options.ionic === 'build') { toLoadSrc = 'lib/ionic/local/ionic.bundle.js' } else if (options.ionic === 'local' || !options.ionic) { toLoadSrc = 'lib/ionic/js/ionic.bundle.js' } else { // Use options.ionic as ionic version toLoadSrc = '//code.ionicframework.com/' + options.ionic + '/js/ionic.bundle.min.js' } console.log('Ionic From') console.log(toLoadSrc) document.write('<script src="'+ toLoadSrc +'"></script>') }())
Fix error `cannot read split of undefined`
Fix error `cannot read split of undefined`
JavaScript
mit
IonicBrazil/ionic-garden,Jandersoft/ionic-garden,IonicBrazil/ionic-garden,Jandersoft/ionic-garden
7571f2b5b4ecca329cf508ef07dd113e6dbe53fc
resources/assets/js/bootstrap.js
resources/assets/js/bootstrap.js
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); require('bootstrap-sass/assets/javascripts/bootstrap'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); require('vue-resource'); /** * We'll register a HTTP interceptor to attach the "CSRF" header to each of * the outgoing requests issued by this application. The CSRF middleware * included with Laravel will automatically verify the header's value. */ Vue.http.interceptors.push((request, next) => { request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken; next(); }); /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from "laravel-echo" // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); require('vue-resource'); /** * We'll register a HTTP interceptor to attach the "CSRF" header to each of * the outgoing requests issued by this application. The CSRF middleware * included with Laravel will automatically verify the header's value. */ Vue.http.interceptors.push((request, next) => { request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken; next(); }); /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from "laravel-echo" // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
Use module name instead of path
Use module name instead of path
JavaScript
apache-2.0
zhiyicx/thinksns-plus,beautifultable/phpwind,cbnuke/FilesCollection,orckid-lab/dashboard,zeropingheroes/lanyard,slimkit/thinksns-plus,tinywitch/laravel,hackel/laravel,cbnuke/FilesCollection,zhiyicx/thinksns-plus,zeropingheroes/lanyard,remxcode/laravel-base,hackel/laravel,orckid-lab/dashboard,beautifultable/phpwind,zeropingheroes/lanyard,remxcode/laravel-base,slimkit/thinksns-plus,hackel/laravel
b26c2afa7c54ead6d5c3ed608bc45a31e9d51e0f
addon/components/scroll-to-here.js
addon/components/scroll-to-here.js
import Ember from 'ember'; import layout from '../templates/components/scroll-to-here'; export default Ember.Component.extend({ layout: layout });
import Ember from 'ember'; import layout from '../templates/components/scroll-to-here'; let $ = Ember.$; function Window() { let w = $(window); this.top = w.scrollTop(); this.bottom = this.top + (w.prop('innerHeight') || w.height()); } function Target(selector) { let target = $(selector); this.isEmpty = !target.length; this.top = target.offset().top; this.bottom = this.top + target.height(); } Target.prototype.isOffscreen = function() { let w = new Window(); return this.top < w.top || this.bottom > w.bottom; }; Target.prototype.scroll = function() { if (!this.isEmpty && this.isOffscreen()) { Ember.run.schedule('afterRender', () => { $('html,body').animate({ scrollTop: this.top }, 1000); }); } }; function scrollTo(selector) { new Target(selector).scroll(); } export default Ember.Component.extend({ layout: layout, scrollToComponent: Ember.on('didInsertElement', function() { scrollTo(`#${this.elementId}`); }) });
Add scroll to here logic
Add scroll to here logic
JavaScript
mit
ember-montevideo/ember-cli-scroll-to-here,ember-montevideo/ember-cli-scroll-to-here
e5350251a99d92dc75c3db04674ed6044029f920
addon/initializers/simple-token.js
addon/initializers/simple-token.js
import TokenAuthenticator from '../authenticators/token'; export function initialize(application) { application.register('authenticator:token', TokenAuthenticator); } export default { name: 'simple-token', initialize };
import TokenAuthenticator from '../authenticators/token'; import TokenAuthorizer from '../authorizers/token'; export function initialize(application) { application.register('authenticator:token', TokenAuthenticator); application.register('authorizer:token', TokenAuthorizer); } export default { name: 'simple-token', initialize };
Fix authorizer missing from container
Fix authorizer missing from container Using routes with authorization was failing because the container didn't contain a definition for the factory. Adding the authorizer in the initialization fixes this. Fixes issue #6
JavaScript
mit
datajohnny/ember-simple-token,datajohnny/ember-simple-token
6ba02cc85b13ddd89ef7a787feee9398dff24c68
scripts/start.js
scripts/start.js
// This script is used to serve the built files in production and proxy api requests to the service. // Would be preferrable to replace with apache. const express = require('express'); const proxy = require('express-http-proxy'); const compression = require('compression'); const path = require('path'); const app = express(); // function forceHttps(request, response, next) { // if (request.headers['x-forwarded-proto'] !== 'https') { // return response.redirect(301, `https://${request.get('host')}${request.url}`); // } // return next(); // } app.use(compression()); // app.use(forceHttps); app.use(express.static(path.join(__dirname, '..', 'build'))); app.use('/api', proxy('https://onboarding-service.tuleva.ee')); app.get('/.well-known/acme-challenge/aqfyXwYn_9RtkQy64cwXdzMrRpjW2B4MwtUbtl7kKPk', (request, response) => response.send('aqfyXwYn_9RtkQy64cwXdzMrRpjW2B4MwtUbtl7kKPk.EMEBBxvSam3n_ien1J0z4dXeTuc2JuR3HqfAP6teLjE')); app.get('*', (request, response) => response.sendFile(path.join(__dirname, '..', 'build', 'index.html'))); const port = process.env.PORT || 8080; app.listen(port, () => console.log(`Static server running on ${port}`)); // eslint-disable-line
// This script is used to serve the built files in production and proxy api requests to the service. // Would be preferrable to replace with apache. const express = require('express'); const proxy = require('express-http-proxy'); const compression = require('compression'); const path = require('path'); const app = express(); function forceHttps(request, response, next) { if (request.headers['x-forwarded-proto'] !== 'https') { return response.redirect(301, `https://${request.get('host')}${request.url}`); } return next(); } app.use(compression()); app.use(forceHttps); app.use(express.static(path.join(__dirname, '..', 'build'))); app.use('/api', proxy('https://onboarding-service.tuleva.ee')); app.get('*', (request, response) => response.sendFile(path.join(__dirname, '..', 'build', 'index.html'))); const port = process.env.PORT || 8080; app.listen(port, () => console.log(`Static server running on ${port}`)); // eslint-disable-line
Remove acme challenge and enable forcing https
Remove acme challenge and enable forcing https
JavaScript
mit
TulevaEE/onboarding-client,TulevaEE/onboarding-client,TulevaEE/onboarding-client
0095363683a71a75de3da3470fc65fe4aa7da5ab
src/client/js/controllers/plusMin.js
src/client/js/controllers/plusMin.js
import app from '../app'; import '../services/PlusMinClient'; app.controller('plusMinController', function ($element, $scope, $http, PlusMinClient) { let client = PlusMinClient; $scope.state = 'loading'; $scope.toState = function (state) { $scope.state = state; }; $scope.openList = function (list) { $scope.list = list; $scope.list.new = false; $scope.state = 'editList'; }; $scope.openNewList = function () { $scope.list = { new: true, positives: [], negatives: [] }; $scope.state = 'editList'; }; client.loadLists().then(function (request) { let lists = request.data; if (lists.length < 2) { $scope.state = 'editList'; if (lists.length === 0) { $scope.list = { new: true, positives: [{ title: 'Positief dingetje 1' }, { title: 'Positief dingetje 2' }, { title: 'Positief dingetje 3' }], negatives: [{ title: 'Negatief dingetje 1' }] }; } else { $scope.list = lists[0]; $scope.list.new = false; } } else { $scope.state = 'selectList'; $scope.lists = lists; } }); });
import app from '../app'; import '../services/PlusMinClient'; app.controller('plusMinController', function ($element, $scope, $http, PlusMinClient) { let client = PlusMinClient; $scope.state = 'loading'; $scope.toState = function (state) { $scope.state = state; }; $scope.openList = function (list) { $scope.list = list; $scope.list.new = false; $scope.state = 'editList'; }; $scope.openNewList = function () { $scope.list = { new: true, positives: [], negatives: [] }; $scope.state = 'editList'; }; client.loadLists().then(function (request) { let lists = request.data; if (lists.length < 2) { $scope.state = 'editList'; if (lists.length === 0) { $scope.list = { new: true, positives: [], negatives: [] }; } else { $scope.list = lists[0]; $scope.list.new = false; } } else { $scope.state = 'selectList'; $scope.lists = lists; } }); });
Add list editor and list selector
Add list editor and list selector
JavaScript
mit
LuudJanssen/plus-min-list,LuudJanssen/plus-min-list,LuudJanssen/plus-min-list
1adbfa5376dc39faacbc4993a64c599409aadff4
static/js/order_hardware_software.js
static/js/order_hardware_software.js
$(document).ready(function () { if (!id_category_0.checked && !id_category_1.checked){ $("#id_institution").parents('.row').hide(); $("#id_department").parents('.row').hide(); } $("#id_category_0").click(function () { $("#id_institution").parents('.row').show(); $("#id_department").parents('.row').show(); }); $("#id_category_1").click(function () { $("#id_institution").parents('.row').hide(); $("#id_department").parents('.row').hide(); }); }); function ajax_filter_departments(institution_id) { $("#id_department").html('<option value="">Loading...</option>'); $.ajax({ type: "GET", url: "/order/show_department", dataType: "json", data: {'institution':institution_id}, success: function(retorno) { $("#id_department").empty(); $("#id_department").append('<option value="">--------</option>'); $.each(retorno, function(i, item){ $("#id_department").append('<option value="'+item.pk+'">'+item.valor+'</option>'); }); }, error: function(error) { alert('Error: No request return.'); } }); }
$(document).ready(function () { if (!id_category_0.checked && !id_category_1.checked){ $("#id_institution").parents('.row').hide(); $("#id_department").parents('.row').hide(); } $("#id_category_0").click(function () { $("#id_institution").parents('.row').show(); $("#id_department").parents('.row').show(); }); $("#id_category_1").click(function () { $("#id_institution").parents('.row').hide(); $("#id_department").parents('.row').hide(); }); if (id_category_1.checked){ $("#id_institution").parents('.row').hide(); $("#id_department").parents('.row').hide(); } }); function ajax_filter_departments(institution_id) { $("#id_department").html('<option value="">Loading...</option>'); $.ajax({ type: "GET", url: "/order/show_department", dataType: "json", data: {'institution':institution_id}, success: function(retorno) { $("#id_department").empty(); $("#id_department").append('<option value="">--------</option>'); $.each(retorno, function(i, item){ $("#id_department").append('<option value="'+item.pk+'">'+item.valor+'</option>'); }); }, error: function(error) { alert('Error: No request return.'); } }); }
Hide fields if "Consumption items" is selected
Hide fields if "Consumption items" is selected
JavaScript
mpl-2.0
neuromat/nira,neuromat/nira,neuromat/nira
17f3f1fb9967f3db50d0997d7be480726aaf0219
server/models/user.js
server/models/user.js
module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false, unique: true, }, password: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, unique: true }, salt: DataTypes.STRING }, { classMethods: { associate(models) { User.hasMany(models.Message, { foreignKey: 'userId', as: 'userMessages' }); User.belongsToMany(models.Group, { as: 'Members', foreignKey: 'groupId', through: 'UserGroup', }); } } }); return User; };
module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false, unique: true, }, password: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, unique: true }, salt: DataTypes.STRING }); User.associate = (models) => { User.hasMany(models.Message, { foreignKey: 'userId' }); User.belongsToMany(models.Group, { as: 'Members', foreignKey: 'groupId', through: 'UserGroup', }); }; return User; };
Edit model associations using new syntax
Edit model associations using new syntax
JavaScript
mit
3m3kalionel/PostIt,3m3kalionel/PostIt
ff3993c6583b331bd5326aeaa6a710517c6bdab6
packages/npm-bcrypt/package.js
packages/npm-bcrypt/package.js
Package.describe({ summary: "Wrapper around the bcrypt npm package", version: "0.9.2", documentation: null }); Npm.depends({ bcryptjs: "2.3.0" }); Package.onUse(function (api) { api.use("modules@0.7.5", "server"); api.mainModule("wrapper.js", "server"); api.export("NpmModuleBcrypt", "server"); });
Package.describe({ summary: "Wrapper around the bcrypt npm package", version: "0.9.2", documentation: null }); Npm.depends({ bcryptjs: "2.3.0" }); Package.onUse(function (api) { api.use("modules", "server"); api.mainModule("wrapper.js", "server"); api.export("NpmModuleBcrypt", "server"); });
Remove pinned version of `modules` from `npm-bcrypt`.
Remove pinned version of `modules` from `npm-bcrypt`.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
7ffd6936bd40a5a47818f51864a6eb86ed286e56
packages/phenomic/src/index.js
packages/phenomic/src/index.js
/** * @flow */ import path from "path" import flattenConfiguration from "./configuration/flattenConfiguration" import start from "./commands/start" import build from "./commands/build" function normalizeConfiguration(config: PhenomicInputConfig): PhenomicConfig { return { path: config.path || process.cwd(), outdir: config.outdir || path.join(process.cwd(), "dist"), bundler: config.bundler(), renderer: config.renderer(), plugins: flattenConfiguration(config).map(plugin => plugin()), port: config.port || 1414, } } export default { start(config: PhenomicInputConfig) { return start(normalizeConfiguration(config)) }, build(config: PhenomicInputConfig) { return build(normalizeConfiguration(config)) }, }
/** * @flow */ import path from "path" import flattenConfiguration from "./configuration/flattenConfiguration" import start from "./commands/start" import build from "./commands/build" const normalizePlugin = (plugin) => { if (!plugin) { throw new Error( "phenomic: You provided an undefined plugin" ) } if (typeof plugin !== "function") { throw new Error( "phenomic: You provided an plugin with type is " + typeof plugin + ". But function is expected instead of " + plugin ) } // @todo send config here return plugin() } function normalizeConfiguration(config: PhenomicInputConfig): PhenomicConfig { return { path: config.path || process.cwd(), outdir: config.outdir || path.join(process.cwd(), "dist"), bundler: config.bundler(), renderer: config.renderer(), plugins: flattenConfiguration(config).map(normalizePlugin), port: config.port || 1414, } } export default { start(config: PhenomicInputConfig) { return start(normalizeConfiguration(config)) }, build(config: PhenomicInputConfig) { return build(normalizeConfiguration(config)) }, }
Add poor validation for plugins
Add poor validation for plugins
JavaScript
mit
MoOx/statinamic,MoOx/phenomic,phenomic/phenomic,MoOx/phenomic,pelhage/phenomic,phenomic/phenomic,MoOx/phenomic,phenomic/phenomic
4d9a9d30326bda7d88b4877a9e75c94949df79ca
plugins/kalabox-core/events.js
plugins/kalabox-core/events.js
'use strict'; module.exports = function(kbox) { var events = kbox.core.events; var deps = kbox.core.deps; var envs = []; // EVENT: pre-engine-create events.on('pre-engine-create', function(createOptions, done) { var codeRoot = deps.lookup('globalConfig').codeDir; var kboxCode = 'KBOX_CODEDIR=' + codeRoot; envs.push(kboxCode); envs.push('KALABOX=true'); // Add some app opts kbox.whenApp(function(app) { envs.push('APPNAME=' + app.name); envs.push('APPDOMAIN=' + app.domain); }); if (createOptions.Env) { envs.forEach(function(env) { createOptions.Env.push(env); }); } else { createOptions.Env = envs; } done(); }); };
'use strict'; var _ = require('lodash'); module.exports = function(kbox) { var events = kbox.core.events; var deps = kbox.core.deps; // EVENT: pre-engine-create events.on('pre-engine-create', function(createOptions, done) { var envs = []; var codeRoot = deps.lookup('globalConfig').codeDir; var kboxCode = 'KBOX_CODEDIR=' + codeRoot; envs.push(kboxCode); envs.push('KALABOX=true'); // Add some app opts kbox.whenApp(function(app) { envs.push('APPNAME=' + app.name); envs.push('APPDOMAIN=' + app.domain); }); if (createOptions.Env) { envs.forEach(function(env) { if (!_.includes(createOptions.Env, env)) { createOptions.Env.push(env); } }); } else { createOptions.Env = envs; } done(); }); };
Fix some ENV add bugs
Fix some ENV add bugs
JavaScript
mit
kalabox/kalabox-cli,rabellamy/kalabox,ManatiCR/kalabox,RobLoach/kalabox,RobLoach/kalabox,ari-gold/kalabox,rabellamy/kalabox,oneorangecat/kalabox,ManatiCR/kalabox,oneorangecat/kalabox,ari-gold/kalabox,kalabox/kalabox-cli
cd841f91370e770e73992e3bf8cd0930c4fa4e82
assets/javascript/head.scripts.js
assets/javascript/head.scripts.js
/** * head.script.js * * Essential scripts, to be loaded in the head of the document * Use gruntfile.js to include the necessary script files. */ // Load respimage if <picture> element is not supported if(!window.HTMLPictureElement){ enhance.loadJS('/assets/javascript/lib/polyfills/respimage.min.js'); }
/** * head.script.js * * Essential scripts, to be loaded in the head of the document * Use gruntfile.js to include the necessary script files. */ // Load respimage if <picture> element is not supported if(!window.HTMLPictureElement) { document.createElement('picture'); enhance.loadJS('/assets/javascript/lib/polyfills/respimage.min.js'); }
Create hidden picture element when respimage is loaded.
Create hidden picture element when respimage is loaded. Seen in this example: https://github.com/fabianmichael/kirby-imageset#23-template-setup.
JavaScript
mit
jolantis/artlantis,jolantis/artlantis
b62647e8f52c9646d7f4f6eb789db1b84c94228a
scripts/replace-slack-link.js
scripts/replace-slack-link.js
// slack invite links expire after 30 days and you can't(at least as far as i can tell) create tokens for things like slackin anymore const fs = require('fs') const slackInviteLink = process.argv[2] const siteHeaderPath = `${__dirname}/../site/src/components/SiteHeader.js` const readmePath = `${__dirname}/../README.md` const slackInviteLinkRegex = /https:\/\/join\.slack\.com\/t\/emotion-slack\/shared_invite\/[^\/]+\// const siteHeader = fs.readFileSync(siteHeaderPath, 'utf8') fs.writeFileSync( siteHeaderPath, siteHeader.replace(slackInviteLinkRegex, slackInviteLink) ) const readme = fs.readFileSync(readmePath, 'utf8') fs.writeFileSync( readmePath, readme.replace(slackInviteLinkRegex, slackInviteLink) )
// slack invite links expire after 30 days and you can't(at least as far as i can tell) create tokens for things like slackin anymore const fs = require('fs') const slackInviteLink = process.argv[2] const siteHeaderPath = `${__dirname}/../site/src/components/SiteHeader.js` const readmePath = `${__dirname}/../README.md` const slackInviteLinkRegex = /https:\/\/join\.slack\.com\/t\/emotion-slack\/shared_invite\/[^/]+\// const siteHeader = fs.readFileSync(siteHeaderPath, 'utf8') fs.writeFileSync( siteHeaderPath, siteHeader.replace(slackInviteLinkRegex, slackInviteLink) ) const readme = fs.readFileSync(readmePath, 'utf8') fs.writeFileSync( readmePath, readme.replace(slackInviteLinkRegex, slackInviteLink) )
Fix regex to comply with no-useless-escape ESLint rule
Fix regex to comply with no-useless-escape ESLint rule
JavaScript
mit
tkh44/emotion,emotion-js/emotion,tkh44/emotion,emotion-js/emotion,emotion-js/emotion,emotion-js/emotion
7292d5c3db9d8a274567735d6bde06e8dcbd2b7b
src/clincoded/static/libs/render_variant_title.js
src/clincoded/static/libs/render_variant_title.js
'use strict'; import React from 'react'; /** * Method to display the title of a variant. * 1st option is the ClinVar Preferred Title if it's present. * 2nd alternative is a string constructed with the canonical transcript, gene symbol and protein change. * The fallback is the GRCh38 NC_ HGVS name. * @param {object} variant - A variant object */ export function renderVariantTitle(variant) { let variantTitle; if (variant) { if (variant.clinvarVariantId && variant.clinvarVariantTitle) { variantTitle = variant.clinvarVariantTitle; } else if (variant.carId && variant.canonicalTranscriptTitle) { variantTitle = variant.canonicalTranscriptTitle; } else if (variant.hgvsNames && Object.keys(variant.hgvsNames).length && !variantTitle) { if (variant.hgvsNames.GRCh38) { variantTitle = variant.hgvsNames.GRCh38 + ' (GRCh38)'; } else if (variant.hgvsNames.GRCh37) { variantTitle = variant.hgvsNames.GRCh37 + ' (GRCh37)'; } else { variantTitle = variant.carId ? variant.carId : 'A preferred title is not available'; } } } return <span className="variant-title">{variantTitle}</span>; }
'use strict'; import React from 'react'; /** * Method to display the title of a variant. * 1st option is the ClinVar Preferred Title if it's present. * 2nd alternative is a string constructed with the canonical transcript, gene symbol and protein change. * The fallback is the GRCh38 NC_ HGVS name. * @param {object} variant - A variant object * @param {boolean} stringOnly - Whether the output should be just string */ export function renderVariantTitle(variant, stringOnly) { let variantTitle; if (variant) { if (variant.clinvarVariantId && variant.clinvarVariantTitle) { variantTitle = variant.clinvarVariantTitle; } else if (variant.carId && variant.canonicalTranscriptTitle) { variantTitle = variant.canonicalTranscriptTitle; } else if (variant.hgvsNames && Object.keys(variant.hgvsNames).length && !variantTitle) { if (variant.hgvsNames.GRCh38) { variantTitle = variant.hgvsNames.GRCh38 + ' (GRCh38)'; } else if (variant.hgvsNames.GRCh37) { variantTitle = variant.hgvsNames.GRCh37 + ' (GRCh37)'; } else { variantTitle = variant.carId ? variant.carId : 'A preferred title is not available'; } } } if (stringOnly) { return variantTitle; } else { return <span className="variant-title">{variantTitle}</span>; } }
Add option to only return a string instead of JSX
Add option to only return a string instead of JSX
JavaScript
mit
ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded,ClinGen/clincoded
cbec0d253d7b451cb5584329b21900dbbce7ab19
src/components/common/SourceOrCollectionWidget.js
src/components/common/SourceOrCollectionWidget.js
import PropTypes from 'prop-types'; import React from 'react'; import { Col } from 'react-flexbox-grid/lib'; import { DeleteButton } from './IconButton'; const SourceOrCollectionWidget = (props) => { const { object, onDelete, onClick, children } = props; const isCollection = object.tags_id !== undefined; const typeClass = isCollection ? 'collection' : 'source'; const objectId = object.id || (isCollection ? object.tags_id : object.media_id); const name = isCollection ? (object.name || object.label || object.tag) : (object.name || object.label || object.url); return ( <div className={`media-widget ${typeClass}`} key={`media-widget${objectId}`} > <Col> <a href="#" onClick={onClick}>{name}</a> {children} </Col> <Col> <DeleteButton onClick={onDelete} /> </Col> </div> ); }; SourceOrCollectionWidget.propTypes = { object: PropTypes.object.isRequired, onDelete: PropTypes.func, onClick: PropTypes.func, children: PropTypes.node, }; export default SourceOrCollectionWidget;
import PropTypes from 'prop-types'; import React from 'react'; import { Col } from 'react-flexbox-grid/lib'; import { DeleteButton } from './IconButton'; const SourceOrCollectionWidget = (props) => { const { object, onDelete, onClick, children } = props; const isCollection = object.tags_id !== undefined; const typeClass = isCollection ? 'collection' : 'source'; const objectId = object.id || (isCollection ? object.tags_id : object.media_id); const name = isCollection ? (object.name || object.label || object.tag) : (object.name || object.label || object.url); // link the text if there is a click handler defined let text = name; if (onClick) { text = (<a href="#" onClick={onClick}>{name}</a>); } return ( <div className={`media-widget ${typeClass}`} key={`media-widget${objectId}`} > <Col> {text} {children} </Col> <Col> {onDelete && <DeleteButton onClick={onDelete} />} </Col> </div> ); }; SourceOrCollectionWidget.propTypes = { object: PropTypes.object.isRequired, onDelete: PropTypes.func, onClick: PropTypes.func, children: PropTypes.node, }; export default SourceOrCollectionWidget;
Handle list of media/collections that aren't clickable
Handle list of media/collections that aren't clickable
JavaScript
apache-2.0
mitmedialab/MediaCloud-Web-Tools,mitmedialab/MediaCloud-Web-Tools,mitmedialab/MediaCloud-Web-Tools,mitmedialab/MediaCloud-Web-Tools
1960321adb5c7fcc17fea23e0e313c94bb34de2e
TabBar.js
TabBar.js
'use strict'; import React, { Animated, Platform, StyleSheet, View, } from 'react-native'; import Layout from './Layout'; export default class TabBar extends React.Component { static propTypes = { ...View.propTypes, shadowStyle: View.propTypes.style, }; render() { return ( <Animated.View {...this.props} style={[styles.container, this.props.style]}> {this.props.children} <View style={[styles.shadow, this.props.shadowStyle]} /> </Animated.View> ); } } let styles = StyleSheet.create({ container: { backgroundColor: '#f8f8f8', flexDirection: 'row', justifyContent: 'space-around', height: Layout.tabBarHeight, position: 'absolute', bottom: 0, left: 0, right: 0, }, shadow: { backgroundColor: 'rgba(0, 0, 0, 0.25)', height: Layout.pixel, position: 'absolute', left: 0, right: 0, top: Platform.OS === 'android' ? 0 : -Layout.pixel, }, });
'use strict'; import React, { Animated, Platform, StyleSheet, View, } from 'react-native'; import Layout from './Layout'; export default class TabBar extends React.Component { static propTypes = { ...Animated.View.propTypes, shadowStyle: View.propTypes.style, }; render() { return ( <Animated.View {...this.props} style={[styles.container, this.props.style]}> {this.props.children} <View style={[styles.shadow, this.props.shadowStyle]} /> </Animated.View> ); } } let styles = StyleSheet.create({ container: { backgroundColor: '#f8f8f8', flexDirection: 'row', justifyContent: 'space-around', height: Layout.tabBarHeight, position: 'absolute', bottom: 0, left: 0, right: 0, }, shadow: { backgroundColor: 'rgba(0, 0, 0, 0.25)', height: Layout.pixel, position: 'absolute', left: 0, right: 0, top: Platform.OS === 'android' ? 0 : -Layout.pixel, }, });
Use 'Animated.View.propTypes' to avoid warnings.
Use 'Animated.View.propTypes' to avoid warnings. The propTypes Validation must be based on `Animated.View.propTypes` instead of just `View.propTypes` otherwise a Warning is displayed when passing Animated values to TabBar.
JavaScript
mit
exponentjs/react-native-tab-navigator
89b7985d0b21fe006d54f613ea7dc6625d5525f5
src/server/modules/counter/subscriptions_setup.js
src/server/modules/counter/subscriptions_setup.js
export default { countUpdated: () => ({ // Run the query each time count updated countUpdated: () => true }) };
export default { countUpdated: () => ({ // Run the query each time count updated countUpdated: { filter: () => { return true; } } }) };
Fix Counter subscription filter definition
Fix Counter subscription filter definition
JavaScript
mit
sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-fullstack-starter-kit,sysgears/apollo-universal-starter-kit
cb1a3ff383ef90b56d3746f4ed9ea193402a08b9
web_client/models/AnnotationModel.js
web_client/models/AnnotationModel.js
import _ from 'underscore'; import Model from 'girder/models/Model'; import ElementCollection from '../collections/ElementCollection'; import convert from '../annotations/convert'; export default Model.extend({ resourceName: 'annotation', defaults: { 'annotation': {} }, initialize() { this._elements = new ElementCollection( this.get('annotation').elements || [] ); this._elements.annotation = this; this.listenTo(this._elements, 'change add remove', () => { // copy the object to ensure a change event is triggered var annotation = _.extend({}, this.get('annotation')); annotation.elements = this._elements.toJSON(); this.set('annotation', annotation); }); }, /** * Return the annotation as a geojson FeatureCollection. * * WARNING: Not all annotations are representable in geojson. * Annotation types that cannot be converted will be ignored. */ geojson() { const json = this.get('annotation') || {}; const elements = json.elements || []; return convert(elements); }, /** * Return a backbone collection containing the annotation elements. */ elements() { return this._elements; } });
import _ from 'underscore'; import Model from 'girder/models/Model'; import ElementCollection from '../collections/ElementCollection'; import convert from '../annotations/convert'; export default Model.extend({ resourceName: 'annotation', defaults: { 'annotation': {} }, initialize() { this._elements = new ElementCollection( this.get('annotation').elements || [] ); this._elements.annotation = this; this.listenTo(this._elements, 'change add remove reset', () => { // copy the object to ensure a change event is triggered var annotation = _.extend({}, this.get('annotation')); annotation.elements = this._elements.toJSON(); this.set('annotation', annotation); }); }, /** * Return the annotation as a geojson FeatureCollection. * * WARNING: Not all annotations are representable in geojson. * Annotation types that cannot be converted will be ignored. */ geojson() { const json = this.get('annotation') || {}; const elements = json.elements || []; return convert(elements); }, /** * Return a backbone collection containing the annotation elements. */ elements() { return this._elements; } });
Update annotation on reset events
Update annotation on reset events
JavaScript
apache-2.0
girder/large_image,DigitalSlideArchive/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image,DigitalSlideArchive/large_image
aaf220bd9c37755bcf3082098c3df96d7a197001
webpack/webpack.config.base.babel.js
webpack/webpack.config.base.babel.js
import path from 'path'; const projectRoot = path.join(__dirname, '..'); export default { cache: true, entry: [ path.join(projectRoot, 'src', 'hibp.js'), ], output: { library: 'hibp', libraryTarget: 'umd', path: path.join(projectRoot, 'dist'), }, module: { rules: [ { test: /\.js$/, include: [ path.join(projectRoot, 'src'), ], use: [ { loader: 'babel-loader', options: { babelrc: false, cacheDirectory: true, plugins: [ 'add-module-exports', ], presets: [ [ 'env', { targets: { browsers: [ '> 1%', 'last 2 versions', ], }, }, ], ], }, }, ], }, ], }, node: { fs: 'empty', module: 'empty', Buffer: false, // axios 0.16.1 }, };
import path from 'path'; const projectRoot = path.join(__dirname, '..'); export default { cache: true, entry: [ path.join(projectRoot, 'src', 'hibp.js'), ], output: { library: 'hibp', libraryTarget: 'umd', umdNamedDefine: true, path: path.join(projectRoot, 'dist'), }, module: { rules: [ { test: /\.js$/, include: [ path.join(projectRoot, 'src'), ], use: [ { loader: 'babel-loader', options: { babelrc: false, cacheDirectory: true, plugins: [ 'add-module-exports', ], presets: [ [ 'env', { targets: { browsers: [ '> 1%', 'last 2 versions', ], }, }, ], ], }, }, ], }, ], }, node: { fs: 'empty', module: 'empty', Buffer: false, // axios 0.16.1 }, };
Set the AMD module name in the UMD build
Set the AMD module name in the UMD build
JavaScript
mit
wKovacs64/hibp,wKovacs64/hibp,wKovacs64/hibp
3b9cebffb70d2fc08b8cf48f86ceb27b42d8d9b4
migrations/20131122023554-make-user-table.js
migrations/20131122023554-make-user-table.js
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('users', { columns: { id: { type: 'int', primaryKey: true, autoIncrement: true }, firstName: { type: 'string', notNull: true}, lastName: { type: 'string', notNull: true}, email: { type: 'string', notNull: true}, hash: { type: 'string', notNull: true}, salt: { type: 'string', notNull: true} }, ifNotExists: true }, callback); }; exports.down = function(db, callback) { };
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('users', { columns: { id: { type: 'int', primaryKey: true, autoIncrement: true }, firstName: { type: 'string', notNull: true}, lastName: { type: 'string', notNull: true}, email: { type: 'string', notNull: true}, hash: { type: 'string', notNull: true}, salt: { type: 'string', notNull: true} }, ifNotExists: true }, callback); }; exports.down = function(db, callback) { console.log('not dropping table users'); callback(); };
Call user migrate down callback
Call user migrate down callback
JavaScript
bsd-3-clause
t3mpus/tempus-api
aa35d4f0801549420ae01f0be3c9dececaa6c345
core/devMenu.js
core/devMenu.js
"use strict"; const electron = require("electron"); const {app} = electron; const {Menu} = electron; const {BrowserWindow} = electron; module.exports.setDevMenu = function () { var devMenu = Menu.buildFromTemplate([{ label: "Development", submenu: [{ label: "Reload", accelerator: "CmdOrCtrl+R", click: function () { BrowserWindow.getFocusedWindow().reload(); } },{ label: "Toggle DevTools", accelerator: "Alt+CmdOrCtrl+I", click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } },{ label: "Quit", accelerator: "CmdOrCtrl+Q", click: function () { app.quit(); } }] }]); Menu.setApplicationMenu(devMenu); };
"use strict"; const electron = require("electron"); const {app} = electron; const {Menu} = electron; const {BrowserWindow} = electron; module.exports.setDevMenu = function () { var devMenu = Menu.buildFromTemplate([{ label: "Development", submenu: [{ label: "Reload", accelerator: "F5", click: function () { BrowserWindow.getFocusedWindow().reload(); } },{ label: "Toggle DevTools", accelerator: "Alt+CmdOrCtrl+I", click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } },{ label: "Quit", accelerator: "CmdOrCtrl+Q", click: function () { app.quit(); } }] }]); Menu.setApplicationMenu(devMenu); };
Change development reload shortcut to F5
Change development reload shortcut to F5 This prevents interference when using bash's Ctrl-R command
JavaScript
mit
petschekr/Chocolate-Shell,petschekr/Chocolate-Shell
0b54a083f4c1a3bdeb097fbf2462aa6d6bc484d5
basis/jade/syntax_samples/index.js
basis/jade/syntax_samples/index.js
#!/usr/bin/env node var assert = require('assert'); var jade = require('jade'); var source = [ 'each v, i in list', ' div #{v},#{i}' ].join('\n'); var fn = jade.compile(source); var html = fn({ list:['a', 'b', 'c'] }); assert.strictEqual(html, '<div>a,0</div><div>b,1</div><div>c,2</div>');
#!/usr/bin/env node var assert = require('assert'); var jade = require('jade'); var source = [ 'each v, i in list', ' div #{v},#{i}' ].join('\n'); var fn = jade.compile(source); var html = fn({ list:['a', 'b', 'c'] }); assert.strictEqual(html, '<div>a,0</div><div>b,1</div><div>c,2</div>'); // #{} と !{} var source = [ '|#{str}', '|!{str}' ].join('\n'); var fn = jade.compile(source); var text = fn({ str:'a&b' }); assert.strictEqual(text, 'a&amp;b\na&b');
Add a sample of jade
Add a sample of jade
JavaScript
mit
kjirou/nodejs-codes
e6de9cdbc7ee08097b041550fc1b1edd60a98619
src/sanity/inputResolver/inputResolver.js
src/sanity/inputResolver/inputResolver.js
import array from 'role:@sanity/form-builder/input/array?' import boolean from 'role:@sanity/form-builder/input/boolean?' import date from 'role:@sanity/form-builder/input/date?' import email from 'role:@sanity/form-builder/input/email?' import geopoint from 'role:@sanity/form-builder/input/geopoint?' import number from 'role:@sanity/form-builder/input/number?' import object from 'role:@sanity/form-builder/input/object?' import reference from 'role:@sanity/form-builder/input/reference?' import string from 'role:@sanity/form-builder/input/string?' import text from 'role:@sanity/form-builder/input/text?' import url from 'role:@sanity/form-builder/input/url?' import DefaultReference from '../inputs/Reference' const coreTypes = { array, boolean, date, email, geopoint, number, object, reference: reference || DefaultReference, string, text, url } const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name] return field.input || inputRole } export default inputResolver
import array from 'role:@sanity/form-builder/input/array?' import boolean from 'role:@sanity/form-builder/input/boolean?' import date from 'role:@sanity/form-builder/input/date?' import email from 'role:@sanity/form-builder/input/email?' import geopoint from 'role:@sanity/form-builder/input/geopoint?' import number from 'role:@sanity/form-builder/input/number?' import object from 'role:@sanity/form-builder/input/object?' import reference from 'role:@sanity/form-builder/input/reference?' import string from 'role:@sanity/form-builder/input/string?' import text from 'role:@sanity/form-builder/input/text?' import url from 'role:@sanity/form-builder/input/url?' import DefaultReference from '../inputs/Reference' const primitiveTypes = { array, boolean, date, number, object, reference: reference || DefaultReference, string } const bundledTypes = { email, geopoint, text, url } const coreTypes = Object.assign({}, primitiveTypes, bundledTypes) const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name] return field.input || inputRole } export default inputResolver
Split up vars for consistency with official Sanity terms
Split up vars for consistency with official Sanity terms
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
7b37439270e372ec4baf226330cdaa1610608d49
app/assets/javascripts/home.js
app/assets/javascripts/home.js
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. // You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
Remove HipsterScript-style comments from JS sources.
Remove HipsterScript-style comments from JS sources.
JavaScript
agpl-3.0
teikei/teikei,teikei/teikei,teikei/teikei,sjockers/teikei,sjockers/teikei,sjockers/teikei
fed23fcd236419462e5e5ee8f71db0d88eedfbe3
parseCloudCode/parse/cloud/main.js
parseCloudCode/parse/cloud/main.js
// Use Parse.Cloud.define to define as many cloud functions as you want. // For example: Parse.Cloud.define("hello", function(request, response) { response.success("Doms Cloud Code!"); });
// Use Parse.Cloud.define to define as many cloud functions as you want. // For example: Parse.Cloud.define("hello", function(request, response) { console.log("hello5"); response.success("Doms Cloud Code"); }); //test function Parse.Cloud.beforeSave("MatchScore", function(request, response) { if (request.object.get("P10Score") > 3) { response.error("Games are first to 3"); //return response.error(JSON.stringify({code: ErrorCodes["450"], message: "Games are first to 3"})); } else { response.success(); } }); //User opt in/out of leaderboard Parse.Cloud.define("joinLeaderboard", function(request, response) { //set the leaderboard flag to true var currentUser = Parse.User.current(); currentUser.set("Leaderboard", true); currentUser.save(); var AddLeaderboard = Parse.Object.extend("LeaderBoard"); var AddLeaderboard = Parse.Object.extend("LeaderBoard"); var query = new Parse.Query(AddLeaderboard); query.notEqualTo("Ranking", 0); query.count().then(function(count) { //success console.log(count); return count; }).then (function(count) { var currentUser = Parse.User.current(); var addLeaderboard = new AddLeaderboard(); var newPlayerRanking = count + 1; addLeaderboard.save({Ranking: newPlayerRanking, playerID: currentUser}, { success: function(object) { console.log("User added to the leaderboard55"); response.success("Learderboard Joined!!") }, error: function(model, error) { console.error("Error User could not be added to the leaderboard"); } }); }, function(error) { //error console.log("error5"); response.error("error5"); }); });
Add user to the leaderboard
Add user to the leaderboard adds the user to the bottom of the leaderboard in last place
JavaScript
mit
Mccoy123/sotonSquashAppCloudCode,Mccoy123/sotonSquashAppCloudCode
24cfc6510cf954c3181dd60f403ebb743ca6a7a1
src/server/test/timeIntervalTests.js
src/server/test/timeIntervalTests.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const moment = require('moment'); const mocha = require('mocha'); const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); const expect = chai.expect; const { TimeInterval } = require('../../common/TimeInterval'); mocha.describe('Time Intervals', () => { mocha.it('can be created', async () => { const start = moment('1970-01-01 00:01:00'); const end = moment('2069-12-31 00:01:00'); const ti = new TimeInterval(start, end); expect(ti.toString()).to.equal('1970-01-01T06:01:00Z_2069-12-31T06:01:00Z'); }); });
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const moment = require('moment'); const mocha = require('mocha'); const chai = require('chai'); const chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); const expect = chai.expect; const { TimeInterval } = require('../../common/TimeInterval'); mocha.describe('Time Intervals', () => { mocha.it('can be created', async () => { const start = moment('1970-01-01T00:01:00Z'); const end = moment('2069-12-31T00:01:00Z'); const ti = new TimeInterval(start, end); expect(ti.toString()).to.equal('1970-01-01T00:01:00Z_2069-12-31T00:01:00Z'); }); });
Fix TimeInterval test by acknowledging time zones
Fix TimeInterval test by acknowledging time zones
JavaScript
mpl-2.0
OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED
7dd2cfca7e87cd1d2d84c9685e1dbf4ad4c5a8a5
packages/lingui-cli/src/lingui-add-locale.js
packages/lingui-cli/src/lingui-add-locale.js
const fs = require('fs') const path = require('path') const chalk = require('chalk') const program = require('commander') const getConfig = require('lingui-conf').default const plurals = require('make-plural') const config = getConfig() program.parse(process.argv) function validateLocales (locales) { const unknown = locales.filter(locale => !(locale in plurals)) if (unknown.length) { console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`)) process.exit(1) } } function addLocale (locales) { if (!fs.existsSync(config.localeDir)) { fs.mkdirSync(config.localeDir) } locales.forEach(locale => { const localeDir = path.join(config.localeDir, locale) if (fs.existsSync(localeDir)) { console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`)) } else { fs.mkdirSync(localeDir) console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`)) } }) } validateLocales(program.args) addLocale(program.args) console.log() console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
const fs = require('fs') const path = require('path') const chalk = require('chalk') const program = require('commander') const getConfig = require('lingui-conf').default const plurals = require('make-plural') const config = getConfig() function validateLocales (locales) { const unknown = locales.filter(locale => !(locale in plurals)) if (unknown.length) { console.log(chalk.red(`Unknown locale(s): ${unknown.join(', ')}.`)) process.exit(1) } } function addLocale (locales) { if (!fs.existsSync(config.localeDir)) { fs.mkdirSync(config.localeDir) } locales.forEach(locale => { const localeDir = path.join(config.localeDir, locale) if (fs.existsSync(localeDir)) { console.log(chalk.yellow(`Locale ${chalk.underline(locale)} already exists.`)) } else { fs.mkdirSync(localeDir) console.log(chalk.green(`Added locale ${chalk.underline(locale)}.`)) } }) } program .description('Add target locales. Remove locale by removing <locale> directory from your localeDir (e.g. ./locale)') .arguments('<locale...>') .on('--help', function () { console.log('\n Examples:\n') console.log(' # Add single locale') console.log(' $ lingui add-locale en') console.log('') console.log(' # Add multiple locales') console.log(' $ lingui add-locale en es fr ru') }) .parse(process.argv) if (!program.args.length) program.help() validateLocales(program.args) addLocale(program.args) console.log() console.log(`(use "${chalk.yellow('lingui extract')}" to extract messages)`)
Add help to add-locale command
fix: Add help to add-locale command
JavaScript
mit
lingui/js-lingui,lingui/js-lingui
ededc73fd74777d0d44b3d1613414fe3787a6c9f
lib/cartodb/middleware/allow-query-params.js
lib/cartodb/middleware/allow-query-params.js
module.exports = function allowQueryParams(params) { return function allowQueryParamsMiddleware(req, res, next) { req.context.allowedQueryParams = params; next(); }; };
module.exports = function allowQueryParams(params) { if (!Array.isArray(params)) { throw new Error('allowQueryParams must receive an Array of params'); } return function allowQueryParamsMiddleware(req, res, next) { req.context.allowedQueryParams = params; next(); }; };
Throw on invalid params argument
Throw on invalid params argument
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
3fb83189ad65c6cd0ca13bf1e7ecfe41ca0eed8c
dev/amdDev.js
dev/amdDev.js
'use strict'; require.config({ paths: { raphael: '../raphael' //you will need eve if you use the nodeps version /*eve: '../bower_components/eve/eve'*/ } }); require(['raphael'], function(Raphael) { var paper = Raphael(0, 0, 640, 720, "container"); paper.circle(100, 100, 100); //example // Work here });
'use strict'; require.config({ paths: { raphael: '../raphael' //you will need eve if you use the nodeps version /*eve: '../bower_components/eve/eve'*/ } }); require(['raphael'], function(Raphael) { var paper = Raphael(0, 0, 640, 720, "container"); paper.circle(100, 100, 100).attr({'fill':'270-#FAE56B:0-#E56B6B:100'}); //example // Work here });
Add gradient to test page
Add gradient to test page
JavaScript
mit
DmitryBaranovskiy/raphael,DmitryBaranovskiy/raphael,danielgindi/raphael,danielgindi/raphael
83cd7781120c105b8eeffe3b957d6a5a1b365cdf
app/assets/javascripts/vivus/application.js
app/assets/javascripts/vivus/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require highlight.pack //= require_tree . $(document).ready(function() { $('pre').each(function(i, el) { hljs.highlightBlock(el); }); $('code').each(function(i, el) { hljs.highlightBlock(el); }); $('.vivus-documentation h1').each(function(i, el) { $('#vivus-navigation ul').append("<li><a href='#" + i + "'>" + $(el).text() + "</a></li>"); $(el).prepend("<a name='" + i + "'></a>"); }) });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require highlight.pack //= require_tree . $(document).ready(function() { $('pre').each(function(i, el) { hljs.highlightBlock(el); }); $('code').each(function(i, el) { hljs.highlightBlock(el); }); $('.vivus-documentation h1').each(function(i, el) { $('#vivus-navigation ul').append("<li><a href='#" + $(el).text().toLowerCase().replace(/ /g, '-') + "'>" + $(el).text() + "</a></li>"); $(el).prepend("<a name='" + $(el).text().toLowerCase().replace(/ /g, '-') + "'></a>"); }) });
Fix the navigation generating js
Fix the navigation generating js
JavaScript
mit
markcipolla/vivus,markcipolla/vivus,markcipolla/vivus
869da6419922b8b827cafbafebaf45b35af785e4
runner/test.js
runner/test.js
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ var _ = require('lodash'); var events = require('events'); var CleanKill = require('./cleankill'); var CliReporter = require('./clireporter'); var config = require('./config'); var steps = require('./steps'); module.exports = function test(options, done) { options = _.merge(config.defaults(), options); var emitter = new events.EventEmitter(); new CliReporter(emitter, options.output, options); // Add plugin reporters _.values(options.plugins).forEach(function(plugin) { if (plugin.reporter) { new plugin.reporter(emitter, options.output, plugin); } }); var cleanOptions = _.omit(options, 'output'); emitter.emit('log:debug', 'Configuration:', cleanOptions); steps.runTests(options, emitter, function(error) { CleanKill.close(done.bind(null, error)); }); return emitter; };
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ var _ = require('lodash'); var events = require('events'); var CleanKill = require('./cleankill'); var CliReporter = require('./clireporter'); var config = require('./config'); var steps = require('./steps'); module.exports = function test(options, done) { options = _.merge(config.defaults(), options); var emitter = new events.EventEmitter(); new CliReporter(emitter, options.output, options); // Add plugin event listeners _.values(options.plugins).forEach(function(plugin) { if (plugin.listener) { new plugin.listener(emitter, options.output, plugin); } }); var cleanOptions = _.omit(options, 'output'); emitter.emit('log:debug', 'Configuration:', cleanOptions); steps.runTests(options, emitter, function(error) { CleanKill.close(done.bind(null, error)); }); return emitter; };
Rename 'reporter' plugin hook to 'listener' as it's more semantic
Rename 'reporter' plugin hook to 'listener' as it's more semantic
JavaScript
bsd-3-clause
Polymer/web-component-tester,sankethkatta/web-component-tester,hvdb/web-component-tester,GabrielDuque/web-component-tester,hypnoce/web-component-tester,sankethkatta/web-component-tester,robdodson/web-component-tester,marcinkubicki/web-component-tester,hvdb/web-component-tester,Polymer/tools,rasata/web-component-tester,Polymer/tools,marcinkubicki/web-component-tester,marcinkubicki/web-component-tester,jimsimon/web-component-tester,Polymer/tools,fearphage/web-component-tester,GabrielDuque/web-component-tester,robdodson/web-component-tester,apowers313/web-component-tester,wibblymat/web-component-tester,jimsimon/web-component-tester,Polymer/web-component-tester,rasata/web-component-tester,hvdb/web-component-tester,sankethkatta/web-component-tester,apowers313/web-component-tester,fluxio/web-component-tester,fearphage/web-component-tester,fearphage/web-component-tester,hypnoce/web-component-tester,Polymer/web-component-tester,wibblymat/web-component-tester,Polymer/tools,fluxio/web-component-tester
7c326ab8b6cadbc12e01c98c5e0789cb12dc5969
src/AppRouter.js
src/AppRouter.js
import React from 'react'; import { Router, Route, hashHistory, IndexRoute } from 'react-router'; import App from './App'; import RecentTracks from './components/RecentTracks'; import TopArtists from './components/TopArtists'; let AppRouter = React.createClass ({ render() { return ( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={RecentTracks}/> <Route path="/recent-tracks" component={RecentTracks} /> <Route path="/top-artists" component={TopArtists} /> </Route> </Router> ); } }); export default AppRouter;
import React from 'react'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import App from './App'; import RecentTracks from './components/RecentTracks'; import TopArtists from './components/TopArtists'; let AppRouter = React.createClass ({ render() { return ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={RecentTracks}/> <Route path="/recent-tracks" component={RecentTracks} /> <Route path="/top-artists" component={TopArtists} /> </Route> </Router> ); } }); export default AppRouter;
Use browserHistory to get rid of url queries
Use browserHistory to get rid of url queries
JavaScript
bsd-3-clause
jeromelachaud/Last.fm-Activities-React,jeromelachaud/Last.fm-Activities-React
fa588af379d1f779ed501048e132b33241428bc6
app/components/quantity-widget-component.js
app/components/quantity-widget-component.js
var DEFAULT_MIN = 1; var DEFAULT_MAX = 3; App.QuantityWidgetComponent = Ember.Component.extend({ tagName: 'div', classNameBindings: [ ':quantity-widget', 'isMin', 'isMax' ], attributeBindings: [ 'name:data-icon' ], actions: { increment: function () { if (this.get('isMax')) return; this.set('quantity', this.incrementProperty('quantity') ); }, decrement: function () { if (this.get('isMin')) return; this.set('quantity', this.decrementProperty('quantity') ); } }, quantity: DEFAULT_MIN, // pass in your own to override. max: DEFAULT_MAX, min: DEFAULT_MIN, isMin: function () { return this.get('quantity') === this.get('min'); }.property('quantity'), isMax: function () { return this.get('quantity') >= this.get('max'); }.property('quantity') });
var DEFAULT_MIN = 1; var DEFAULT_MAX = 3; App.QuantityWidgetComponent = Ember.Component.extend({ tagName: 'div', classNameBindings: [ ':quantity-widget', 'isMin', 'isMax' ], attributeBindings: [ 'name:data-icon' ], actions: { increment: function () { if (this.get('isMax')) return; this.set('quantity', this.incrementProperty('quantity') ); }, decrement: function () { if (this.get('isMin')) return; this.set('quantity', this.decrementProperty('quantity') ); } }, quantity: DEFAULT_MIN, // pass in your own to override. max: DEFAULT_MAX, min: DEFAULT_MIN, isMin: function () { return this.get('quantity') === this.get('min'); }.property('quantity'), isMax: function () { return this.get('quantity') >= this.get('max'); }.property('quantity'), maxTooltip: function () { return '%@ is the maximum quantity.'.fmt(this.get('max')); }.property('max') });
Update quantity widget tooltips per prototype
Update quantity widget tooltips per prototype
JavaScript
mit
dollarshaveclub/ember-uni-form,dollarshaveclub/ember-uni-form
84997448d9c3b932c5d7349eea6d6de3877b9bfa
.storybook/preview.js
.storybook/preview.js
import { addParameters, addDecorator, setCustomElements, withA11y } from '@open-wc/demoing-storybook'; async function run() { const customElements = await ( await fetch(new URL('../custom-elements.json', import.meta.url)) ).json(); setCustomElements(customElements); addDecorator(withA11y); addParameters({ a11y: { config: {}, options: { checks: { 'color-contrast': { options: { noScroll: true } } }, restoreScroll: true } }, docs: { iframeHeight: '200px' } }); } run();
import { addParameters, addDecorator, setCustomElements, withA11y, } from '@open-wc/demoing-storybook'; async function run() { const customElements = await ( await fetch(new URL('../custom-elements.json', import.meta.url)) ).json(); setCustomElements(customElements); addDecorator(withA11y); addParameters({ a11y: { config: {}, options: { checks: { 'color-contrast': { options: { noScroll: true } } }, restoreScroll: true, }, }, docs: { iframeHeight: '200px', }, }); } run();
Fix linting errors in generated code
[style] Fix linting errors in generated code
JavaScript
mit
rpatterson/nOrg,rpatterson/nOrg
ffc9c2475174ea4d87c7f389f77631f2c7cd9a35
app/javascript/app/reducers/auth-reducer.js
app/javascript/app/reducers/auth-reducer.js
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR, SET_USER_DATA, SET_CREDIT_CARDS, SET_DEFAULT_CARD } from '../constants/'; const initialState = { authenticated: false, errors: null, user: null, creditCardDefault: null, creditCards: null }; const AuthReducer = (state=initialState, action) => { switch (action.type) { case AUTH_USER: return { ...state, authenticated: true, errors: [] }; case UNAUTH_USER: return { ...state, user: null, authenticated: false, errors: [] } case AUTH_ERROR: return { ...state, errors: action.payload }; case SET_USER_DATA: return { ...state, user: action.payload, errors: [] }; case SET_CREDIT_CARDS: return { ...state, creditCards: action.payload }; case SET_DEFAULT_CARD: return { ...state, creditCardDefault: action.payload } default: return state; } } export default AuthReducer;
import { AUTH_USER, UNAUTH_USER, AUTH_ERROR, SET_USER_DATA, SET_CREDIT_CARDS, SET_DEFAULT_CARD, ADD_CREDIT_CARD } from '../constants/'; const initialState = { authenticated: false, errors: null, user: null, creditCardDefault: null, creditCards: null }; const AuthReducer = (state=initialState, action) => { switch (action.type) { case AUTH_USER: return { ...state, authenticated: true, errors: [] }; case UNAUTH_USER: return { ...state, user: null, authenticated: false, errors: [] } case AUTH_ERROR: return { ...state, errors: action.payload }; case SET_USER_DATA: return { ...state, user: action.payload, errors: [] }; case SET_CREDIT_CARDS: return { ...state, creditCards: action.payload }; case SET_DEFAULT_CARD: return { ...state, creditCardDefault: action.payload } case ADD_CREDIT_CARD: return { ...state, creditCards: [ ...state.creditCards, action.payload ] }; default: return state; } } export default AuthReducer;
Refactor auth reducer to handler the new auth-card actions
Refactor auth reducer to handler the new auth-card actions
JavaScript
mit
GiancarlosIO/ecommerce-book-app,GiancarlosIO/ecommerce-book-app,GiancarlosIO/ecommerce-book-app
dd9345272923cc723eede78af5fb61797237df13
lib/buster-util.js
lib/buster-util.js
if (typeof buster == "undefined") { var buster = {}; } buster.util = (function () { var toString = Object.prototype.toString; var div = typeof document != "undefined" && document.createElement("div"); return { isNode: function (obj) { if (!div) { return false; } try { div.appendChild(obj); div.removeChild(obj); } catch (e) { return false; } return true; }, isElement: function (obj) { return obj && this.isNode(obj) && obj.nodeType === 1; }, isArguments: function (obj) { if (typeof obj != "object" || typeof obj.length != "number" || toString.call(obj) == "[object Array]") { return false; } if (typeof obj.callee == "function") { return true; } try { obj[obj.length] = 6; delete obj[obj.length]; } catch (e) { return true; } return false; }, keys: Object.keys || function (object) { var keys = []; for (var prop in object) { if (Object.prototype.hasOwnProperty.call(object, prop)) { keys.push(prop); } } return keys; } }; }()); if (typeof module != "undefined") { module.exports = buster.util; }
if (typeof buster == "undefined") { var buster = {}; } buster.util = (function () { var toString = Object.prototype.toString; var div = typeof document != "undefined" && document.createElement("div"); return { isNode: function (obj) { if (!div) { return false; } try { div.appendChild(obj); div.removeChild(obj); } catch (e) { return false; } return true; }, isElement: function (obj) { return obj && this.isNode(obj) && obj.nodeType === 1; }, isArguments: function (obj) { if (typeof obj != "object" || typeof obj.length != "number" || toString.call(obj) == "[object Array]") { return false; } if (typeof obj.callee == "function") { return true; } try { obj[obj.length] = 6; delete obj[obj.length]; } catch (e) { return true; } return false; }, keys: function (object) { var keys = []; for (var prop in object) { if (Object.prototype.hasOwnProperty.call(object, prop)) { keys.push(prop); } } return keys; } }; }()); if (typeof module != "undefined") { module.exports = buster.util; }
Fix keys implementation - Object.keys does not work on functions
Fix keys implementation - Object.keys does not work on functions
JavaScript
bsd-3-clause
geddski/buster-core,busterjs/buster-core,busterjs/buster-core
72d231edb93d2a9bf6ead440c9b46d6b35d70717
seequmber/testResults/testResults.js
seequmber/testResults/testResults.js
'use strict'; function TestResults(dataTable) { var Cucumber = require('cucumber'); var TestResult = require('./testResult'); var maximums = [0, 0, 0, 0]; var testCollection = Cucumber.Type.Collection(); (function rowToTestResult() { dataTable.getRows().syncForEach(function(row) { var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]); testCollection.add(testResult); row.raw().forEach(function(element, index) { if (maximums[index] < element.length) { maximums[index] = element.length; } }); }); })(); var self = { getTestResults: function getTestResults() { var newTests = Cucumber.Type.Collection(); testCollection.syncForEach(function(test) { newTests.add(test); }); return newTests; }, attachTest: function attachTest(test) { testCollection.add(test); }, getMaximums: function getMaximums() { return maximums; }, raw: function raw() { var rawTests = []; testCollection.syncForEach(function(test) { rawTests.push(test.raw()); }); return rawTests; } }; return self; } module.exports = TestResults;
'use strict'; function TestResults(dataTable) { var Cucumber = require('cucumber'); var TestResult = require('./testResult'); var maximums = [0, 0, 0, 0]; var testCollection = Cucumber.Type.Collection(); (function rowToTestResult() { var rows = dataTable.getRows(); rows = rows.sort(function(a, b) { return (a.raw()[1]) < (b.raw()[1]); }); rows.syncForEach(function(row) { var testResult = new TestResult(row.raw()[0], row.raw()[1], row.raw()[2], row.raw()[3]); testCollection.add(testResult); row.raw().forEach(function(element, index) { if (maximums[index] < element.length) { maximums[index] = element.length; } }); }); })(); var self = { getTestResults: function getTestResults() { var newTests = Cucumber.Type.Collection(); testCollection.syncForEach(function(test) { newTests.add(test); }); return newTests; }, attachTest: function attachTest(test) { testCollection.add(test); }, getMaximums: function getMaximums() { return maximums; }, raw: function raw() { var rawTests = []; testCollection.syncForEach(function(test) { rawTests.push(test.raw()); }); return rawTests; } }; return self; } module.exports = TestResults;
Sort test results according to version
Sort test results according to version
JavaScript
mit
seeq12/seequcumber,seeq12/seequcumber,seeq12/seequcumber
eff1b5b49924d1313470a645d00a2d5ddab2c735
ember_modules/routes/tasks.js
ember_modules/routes/tasks.js
var route = Ember.Route.extend({ model: function() { return this.store.all('task'); }, afterModel: function(tasks, transition) { if (transition.targetName == "tasks.index") { if($(document).width() > 700) { Ember.run.next(this, function(){ var task = this.controllerFor('tasks') .get('pendingTasks.firstObject'); if(task) { this.transitionTo('task', tasks.get('firstObject')); } }) } else { this.transitionToRoute('mobileTasks'); } } }, actions: { error: function(reason, tsn) { var application = this.controllerFor('application'); application.get('handleError').bind(application)(reason, tsn); } } }); module.exports = route;
var route = Ember.Route.extend({ model: function() { return this.store.all('task'); }, afterModel: function(tasks, transition) { if (transition.targetName == "tasks.index" || transition.targetName == "tasks") { if($(document).width() > 700) { Ember.run.next(this, function(){ var task = this.controllerFor('tasks') .get('pendingTasks.firstObject'); if(task) { this.transitionTo('task', tasks.get('firstObject')); } }) } else { this.transitionToRoute('mobileTasks'); } } }, actions: { error: function(reason, tsn) { var application = this.controllerFor('application'); application.get('handleError').bind(application)(reason, tsn); } } }); module.exports = route;
Check for multiple target routes for deciding when to transition.
Check for multiple target routes for deciding when to transition.
JavaScript
agpl-3.0
coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am
14eaff77c0293e55005a30ae64b4bffeb16c9ce3
src/client/components/Text.js
src/client/components/Text.js
import React from 'react' import _ from 'lodash' import fp from 'lodash/fp' export default props => { const { children: text } = props const linkPattern = /([a-z]+:\/\/[^,\s]+)/g const parts = fp.filter(s => s !== '')(text.split(linkPattern)) const textNodes = _.map(parts, (part, i) => { if (linkPattern.test(part)) { return <a key={i} href={part} target='_blank'>{part}</a> } else { return <span key={i}>{part}</span> } }) return <span>{textNodes}</span> }
import React from 'react' import _ from 'lodash' import fp from 'lodash/fp' export default props => { const { children: text } = props // Anything starting with one or more word characters followed by :// is considered a link. const linkPattern = /(\w+:\/\/\S+)/g const parts = fp.filter(s => s !== '')(text.split(linkPattern)) const textNodes = _.map(parts, (part, i) => { if (linkPattern.test(part)) { return <a key={i} href={part} target='_blank'>{part}</a> } else { return <span key={i}>{part}</span> } }) return <span>{textNodes}</span> }
Simplify regex for finding links
Simplify regex for finding links
JavaScript
mit
daGrevis/msks,daGrevis/msks,daGrevis/msks
7893445133fc85c7305ffba75a34936624bf3ca5
addon/components/object-list-view-input-cell.js
addon/components/object-list-view-input-cell.js
import BaseComponent from './flexberry-base'; export default BaseComponent.extend({ tagName: 'td', classNames: [], column: null, record: null });
import BaseComponent from './flexberry-base'; export default BaseComponent.extend({ tagName: 'td', classNames: [], column: null, record: null, didInsertElement: function() { var _this = this; this.$('input').change(function() { _this.record.set(_this.column.propName, _this.$(this).val()); }); } });
Add support of two way binding
Add support of two way binding in object-list-view-input-cell component
JavaScript
mit
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
b6bb30f5d90885b60c1406ccf211511dbb347a80
src/decoding/createDataStream.js
src/decoding/createDataStream.js
import dissolve from 'dissolve' function createDataStream() { return dissolve() .loop(function() { this .uint32("length") .int8("type") .tap(function() { if (this.vars.length) { this.buffer("data", this.vars.length); } }) .tap(function() { this.push(this.vars); this.vars = {}; }); }); }
import dissolve from 'dissolve' function createDataStream() { return dissolve() .loop(function() { this .uint32("length") .int8("type") .tap(function() { if (this.vars.length) { this.buffer("payload", this.vars.length); } }) .tap(function() { this.push(this.vars); this.vars = {}; }); }); }
Modify binary payload to be called payload instead of data
Modify binary payload to be called payload instead of data
JavaScript
apache-2.0
RobCoIndustries/pipboylib
a4311dc96f20b7f13275df7828c7c5a4b7b8dc52
config.js
config.js
export default { authToken: process.env.AUTH_TOKEN || 'secret', env: process.env.NODE_ENV, host: process.env.HOST || 'localhost', github: { apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username' }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' }, port: process.env.PORT || 8000 }
export default { authToken: process.env.AUTH_TOKEN || 'secret', env: process.env.NODE_ENV, host: process.env.HOST || 'localhost', github: { apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username' }, jobs: { frequency: { githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *' // '00 00 03 * * *' } }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' }, port: process.env.PORT || 8000 }
Add github activity job frequency option
Add github activity job frequency option
JavaScript
mit
franvarney/franvarney-api
c0a49738fbd196f8f79fda0d265268b3fc8b095d
src/frontend/html-renderer.js
src/frontend/html-renderer.js
import React from 'react'; import renderHTML from 'react-render-html'; import SocketClient from './socket-client'; import PropTypes from 'prop-types'; class HTMLRenderer extends React.Component { constructor(props) { super(props); this.state = { html: '' }; } componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } render() { return React.createElement('div', null, renderHTML(this.state.html)); } } HTMLRenderer.propTypes = { location: PropTypes.shape({ host: PropTypes.string.isRequired, pathname: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func, }; export default HTMLRenderer;
import React from 'react'; import renderHTML from 'react-render-html'; import SocketClient from './socket-client'; import PropTypes from 'prop-types'; class HTMLRenderer extends React.Component { constructor(props) { super(props); this.state = { html: '' }; } componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } render() { return React.createElement('div', null, renderHTML(this.state.html)); } } HTMLRenderer.propTypes = { location: PropTypes.shape({ host: PropTypes.string.isRequired, pathname: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func, }; export default HTMLRenderer;
Add line breaks between methods in HTMLRenderer
Add line breaks between methods in HTMLRenderer
JavaScript
mit
noraesae/pen
d2cab051760db8de79c6b59b3e67f28b11fe6c35
src/js/View.js
src/js/View.js
import '@webcomponents/webcomponentsjs'; class View extends HTMLElement { static wrapped() { const Cls = document.registerElement(this.name, this); return (params) => Object.assign(new Cls(), params); } createdCallback() { if (!this.constructor.html) { return; } const template = new DOMParser().parseFromString(this.constructor.html, 'text/html'); const content = document.importNode(template.head.firstChild.content, true); this.appendChild(content); } } export default View;
import '@webcomponents/webcomponentsjs'; class View extends HTMLElement { static wrapped() { customElements.define(this.name, this); return (params) => Object.assign(new this(), params); } constructor() { super(); if (!this.constructor.html) { return; } const template = new DOMParser().parseFromString(this.constructor.html, 'text/html'); const content = document.importNode(template.head.firstChild.content, true); this.appendChild(content); } } export default View;
Update to proper customElements spec
Update to proper customElements spec
JavaScript
mit
HiFiSamurai/ui-toolkit,HiFiSamurai/ui-toolkit
1174726f0e8d814afcd751b162e9d8b5cb1c8235
examples/filebrowser/webpack.conf.js
examples/filebrowser/webpack.conf.js
var ContextReplacementPlugin = require("webpack/lib/ContextReplacementPlugin"); module.exports = { entry: './build/index.js', output: { path: './build', filename: 'bundle.js' }, node: { fs: "empty" }, bail: true, debug: true, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, ] }, plugins: [ new ContextReplacementPlugin( /codemirror\/mode.*$/, /codemirror\/mode.*\.js$/ ) ] }
var ContextReplacementPlugin = require("webpack/lib/ContextReplacementPlugin"); module.exports = { entry: './build/index.js', output: { path: './build', filename: 'bundle.js' }, node: { fs: "empty" }, bail: true, debug: true, module: { loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.html$/, loader: "file?name=[name].[ext]" } ] } }
Fix the codemirror bundle handling
Fix the codemirror bundle handling
JavaScript
bsd-3-clause
eskirk/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,jupyter/jupyter-js-ui,jupyter/jupyter-js-ui,TypeFox/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyter-js-ui
37fb836e41d16631cef9a10321de1a578a92904d
src/constants/controlTypes.js
src/constants/controlTypes.js
// @flow import { RGB_NEAREST, RGB_APPROX, LAB_NEAREST } from "constants/color"; export const BOOL = "BOOL"; export const ENUM = "ENUM"; export const RANGE = "RANGE"; export const STRING = "STRING"; export const PALETTE = "PALETTE"; export const COLOR_ARRAY = "COLOR_ARRAY"; export const COLOR_DISTANCE_ALGORITHM = { type: ENUM, options: [ { name: "RGB", value: RGB_NEAREST }, { name: "RGB (perceptual approx.)", value: RGB_APPROX }, { name: "Lab", value: LAB_NEAREST } ], default: LAB_NEAREST };
// @flow import { RGB_NEAREST, RGB_APPROX, LAB_NEAREST } from "constants/color"; export const BOOL = "BOOL"; export const ENUM = "ENUM"; export const RANGE = "RANGE"; export const STRING = "STRING"; export const PALETTE = "PALETTE"; export const COLOR_ARRAY = "COLOR_ARRAY"; export const COLOR_DISTANCE_ALGORITHM = { type: ENUM, options: [ { name: "RGB", value: RGB_NEAREST }, { name: "RGB (perceptual approx.)", value: RGB_APPROX }, { name: "Lab", value: LAB_NEAREST } ], default: RGB_APPROX };
Switch default color distance algorithm for user to RGB_APPROX
Switch default color distance algorithm for user to RGB_APPROX LAB_NEAREST can be really slow
JavaScript
mit
gyng/ditherer,gyng/ditherer,gyng/ditherer
8dc281e7ddd4ec10f499cf19bb5743ebfa951179
app/components/participant-checkbox.js
app/components/participant-checkbox.js
import Ember from 'ember'; import { task } from 'ember-concurrency'; export default Ember.Component.extend({ store: Ember.inject.service(), flashMessages: Ember.inject.service(), isDisabled: false, isSelected: Ember.computed( 'member', 'participants.@each.member', function(){ let mapped = this.get('participants').mapBy('member.id'); if (mapped.includes(this.get('member.id'))) { return true; } else { return false; } }), toggleParticipant: task(function* (property, value){ if (value) { let newParticipant = this.get('store').createRecord('participant', { member: this.get('member'), entry: this.get('model'), }); try { yield newParticipant.save(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); newParticipant.deleteRecord(); } } else { let participant = this.get('model.participants').findBy('contest.id', this.get('contest.id')); if (participant) { try { yield participant.destroyRecord(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); } } } }).restartable(), });
import Ember from 'ember'; import { task } from 'ember-concurrency'; export default Ember.Component.extend({ store: Ember.inject.service(), flashMessages: Ember.inject.service(), isDisabled: false, isSelected: Ember.computed( 'member', 'participants.@each.member', function(){ let mapped = this.get('participants').mapBy('member.id'); if (mapped.includes(this.get('member.id'))) { return true; } else { return false; } }), toggleParticipant: task(function* (property, value){ if (value) { let newParticipant = this.get('store').createRecord('participant', { member: this.get('member'), entry: this.get('model'), }); try { yield newParticipant.save(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); newParticipant.deleteRecord(); } } else { let participant = this.get('model.participants').findBy('member.id', this.get('member.id')); if (participant) { try { yield participant.destroyRecord(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); } } } }).restartable(), });
Fix double-no clicking on participants
Fix double-no clicking on participants
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
c3943b7962770cf4e3379fa29eb6dcf9958d0297
src/js/events/MarathonActions.js
src/js/events/MarathonActions.js
import ActionTypes from '../constants/ActionTypes'; var AppDispatcher = require('./AppDispatcher'); var Config = require('../config/Config'); var RequestUtil = require('../utils/RequestUtil'); module.exports = { fetchApps: RequestUtil.debounceOnError( Config.getRefreshRate(), function (resolve, reject) { return function () { var url = Config.rootUrl + '/marathon/v2/apps'; RequestUtil.json({ url: url, success: function (response) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_SUCCESS, data: response }); resolve(); }, error: function (e) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ERROR, data: e.message }); reject(); }, hangingRequestCallback: function () { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ONGOING }); } }); }; }, {delayAfterCount: Config.delayAfterErrorCount} ) };
import ActionTypes from '../constants/ActionTypes'; var AppDispatcher = require('./AppDispatcher'); var Config = require('../config/Config'); var RequestUtil = require('../utils/RequestUtil'); module.exports = { fetchApps: RequestUtil.debounceOnError( Config.getRefreshRate(), function (resolve, reject) { return function () { const embed = 'embed=group.groups&embed=group.apps&' + 'embed=group.apps.deployments&embed=group.apps.counts'; let url = `${Config.rootUrl}/marathon/v2/groups?${embed}`; RequestUtil.json({ url: url, success: function (response) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_SUCCESS, data: response }); resolve(); }, error: function (e) { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ERROR, data: e.message }); reject(); }, hangingRequestCallback: function () { AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_MARATHON_APPS_ONGOING }); } }); }; }, {delayAfterCount: Config.delayAfterErrorCount} ) };
Change marathon endpoint to groups
Change marathon endpoint to groups
JavaScript
apache-2.0
dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui
58ac6e0986e0123732a7eb85c12c151fac028f4a
src/js/bpm-counter.js
src/js/bpm-counter.js
class BpmCounter { constructor() { this.numTaps = 0; this.bpm = 0; this.startTapTime = new Date(); } restart() { this.numTaps = 0; this.bpm = 0; } tick() { if (this.numTaps === 0) { this.startTapTime = new Date(); } this.numTaps++; let currentTime = new Date(); let timeDifferenceInMS = currentTime - this.startTapTime; this.bpm = this.numTaps / (timeDifferenceInMS / 1000) * 60; } }
class BpmCounter { constructor() { this.numTaps = 0; this.bpm = 0; this.startTapTime = new Date(); } restart() { this.numTaps = 0; this.bpm = 0; } tick() { if (this.numTaps === 0) { this.startTapTime = new Date(); } this.numTaps++; let currentTime = new Date(); let timeDifferenceInMS = currentTime - this.startTapTime; if (timeDifferenceInMS === 0) { this.bpm = "First tap"; } else { this.bpm = this.numTaps / (timeDifferenceInMS / 1000) * 60; } } }
Fix bug where the first tap gave a bpm of infinity
Fix bug where the first tap gave a bpm of infinity
JavaScript
mit
khwang/plum,khwang/plum
53f0ff80ae2adea22fa7821bd78b57a4920e272c
webapp/display/changes/jobstep_details.js
webapp/display/changes/jobstep_details.js
import React, { PropTypes } from 'react'; import APINotLoaded from 'es6!display/not_loaded'; import ChangesUI from 'es6!display/changes/ui'; import * as api from 'es6!server/api'; import custom_content_hook from 'es6!utils/custom_content'; /* * Shows artifacts for a jobstep */ export var JobstepDetails = React.createClass({ propTypes: { jobstepID: PropTypes.string, }, getInitialState: function() { return {}; }, componentDidMount: function() { api.fetch(this, { artifacts: `/api/0/jobsteps/${this.props.jobstepID}/artifacts/` }); }, render: function() { var { jobstepID, className, ...props} = this.props; if (!api.isLoaded(this.state.artifacts)) { return <APINotLoaded calls={this.state.artifacts} />; } var artifacts = this.state.artifacts.getReturnedData(); className = (className || "") + " jobstepDetails"; return <div {...props} className={className}> {this.renderArtifacts(artifacts)} </div>; }, renderArtifacts(artifacts) { var markup = []; if (artifacts.length > 0) { markup.push(<div className="lb marginTopM">Artifacts</div>); _.each(artifacts, a => { markup.push( <div> <a className="external" target="_blank" href={a.url}> {a.name} </a> </div> ); }); } return markup; } });
import React, { PropTypes } from 'react'; import APINotLoaded from 'es6!display/not_loaded'; import ChangesUI from 'es6!display/changes/ui'; import * as api from 'es6!server/api'; import custom_content_hook from 'es6!utils/custom_content'; /* * Shows artifacts for a jobstep */ export var JobstepDetails = React.createClass({ propTypes: { jobstepID: PropTypes.string, }, getInitialState: function() { return {}; }, componentDidMount: function() { api.fetch(this, { details: `/api/0/jobsteps/${this.props.jobstepID}/artifacts/` }); }, render: function() { var { jobstepID, className, ...props} = this.props; if (!api.isLoaded(this.state.details)) { return <APINotLoaded calls={this.state.details} />; } var details = this.state.details.getReturnedData(); className = (className || "") + " jobstepDetails"; return <div {...props} className={className}> {this.renderArtifacts(details.artifacts)} </div>; }, renderArtifacts(artifacts) { var markup = []; if (artifacts.length > 0) { markup.push(<div className="lb marginTopM">Artifacts</div>); _.each(artifacts, a => { markup.push( <div> <a className="external" target="_blank" href={a.url}> {a.name} </a> </div> ); }); } return markup; } });
Fix artifact display on job steps (which broke because the API changes to return an object rather than a list)
Fix artifact display on job steps (which broke because the API changes to return an object rather than a list) Test Plan: manual =( Reviewers: mkedia, kylec Reviewed By: kylec Subscribers: changesbot Differential Revision: https://tails.corp.dropbox.com/D143542
JavaScript
apache-2.0
dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes
4233edea9f06647e77033222f113392b44049f53
Server.js
Server.js
const util = require('util'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor(verbose) { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; if (verbose) { if (options) { console.log(url, util.inspect(options, {depth: null, breakLength: Infinity})); } else { console.log(url); } } options = Object.assing({forever: true, gzip: true}, options); ctx.body = await request(url, options); }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
const util = require('util'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor(verbose) { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; if (verbose) { if (options) { console.log(url, util.inspect(options, {depth: null, breakLength: Infinity})); } else { console.log(url); } } options = Object.assing({forever: true, gzip: true}, options); try { ctx.body = await request(url, options); } catch (error) { ctx.status = 502; ctx.body = {error: error.message}; } }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
Return HTTP 502 and error message if upstream server error.
Return HTTP 502 and error message if upstream server error.
JavaScript
mit
quentinadam/node-request-server
ab838c82bd48a01a99c152b2392518382d9181e3
app/controllers/dashboard/session-manager/index.js
app/controllers/dashboard/session-manager/index.js
import Ember from 'ember'; export default Ember.Controller.extend({ sortProperties: [ 'statusSort:asc', 'organizationKindSort:asc', 'nomen:asc', ], sortedSessions: Ember.computed.sort( 'model', 'sortProperties' ), actions: { sortBy(sortProperties) { this.set('sortProperties', [sortProperties]); }, } });
import Ember from 'ember'; export default Ember.Controller.extend({ sortProperties: [ 'statusSort:asc', 'organizationKindSort:asc', 'nomen:asc', ], uniqueSessions: Ember.computed.uniq( 'model', ), sortedSessions: Ember.computed.sort( 'uniqueSessions', 'sortProperties' ), actions: { sortBy(sortProperties) { this.set('sortProperties', [sortProperties]); }, } });
Fix duplicates on session manager
Fix duplicates on session manager
JavaScript
bsd-2-clause
barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web
566df4420093daf02422cbf344d49d0da089e583
src/lib/fileUpload.js
src/lib/fileUpload.js
var ssh2 = require('ssh2'); var SocketIOFileUpload = require('socketio-file-upload'); var completeFileUpload = function(client, sshCredentials) { return function(event) { var credentials = sshCredentials(client.instance); var connection = ssh2(); connection.on('end', function() { }); connection.on('ready', function() { connection.sftp(function(err, sftp) { if (err) { console.log("There was an error while connecting via sftp: " + err); } var stream = sftp.createWriteStream(event.file.name); stream.write(client.fileUploadBuffer.toString()); stream.end(function() { connection.end(); }); client.fileUploadBuffer = ""; }); }); connection.connect(credentials); }; }; module.exports = function(logExceptOnTest, sshCredentials) { return { attachUploadListenerToSocket: function(client, socket) { var uploader = new SocketIOFileUpload(); uploader.listen(socket); uploader.on("error", function(event) { console.error("Error in upload " + event); }); uploader.on("start", function(event) { client.fileUploadBuffer = ""; logExceptOnTest('File upload ' + event.file.name); }); uploader.on("progress", function(event) { client.fileUploadBuffer += event.buffer; }); uploader.on("complete", completeFileUpload(client, sshCredentials)); } }; };
var ssh2 = require('ssh2'); var SocketIOFileUpload = require('socketio-file-upload'); var completeFileUpload = function(client, sshCredentials) { return function(event) { var credentials = sshCredentials(client.instance); var connection = ssh2(); connection.on('end', function() { }); connection.on('ready', function() { connection.sftp(function(err, sftp) { if (err) { console.log("There was an error while connecting via sftp: " + err); } var stream = sftp.createWriteStream(event.file.name); stream.write(client.fileUploadBuffer); stream.end(function() { connection.end(); }); client.fileUploadBuffer = ""; }); }); connection.connect(credentials); }; }; module.exports = function(logExceptOnTest, sshCredentials) { return { attachUploadListenerToSocket: function(client, socket) { var uploader = new SocketIOFileUpload(); uploader.listen(socket); uploader.on("error", function(event) { console.error("Error in upload " + event); }); uploader.on("start", function(event) { client.fileUploadBuffer = ""; logExceptOnTest('File upload name:' + event.file.name); logExceptOnTest('File upload encoding: ' + event.file.encoding); }); uploader.on("progress", function(event) { client.fileUploadBuffer = event.buffer; }); uploader.on("complete", completeFileUpload(client, sshCredentials)); } }; };
Fix bug with uploading octed data like images
Fix bug with uploading octed data like images
JavaScript
mit
antonleykin/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell
4c5483125fcd12e111cffe1a1cadf67b8777ff7e
src/nbsp-positions.js
src/nbsp-positions.js
'use strict'; var execall = require('regexp.execall'); module.exports = function (text) { return execall(/ \w{1,2} [^ ]/g, text).map(function (match) { return match.index + match[0].length - 2; }); };
'use strict'; var execall = require('regexp.execall'); module.exports = function (text) { return execall(/(^|\s\W*)(\w{1,2})(?= [^ ])/g, text) .filter(function (match) { return !/\d/.test(match[1]); }) .map(function (match) { return match.index + match[0].length; }); };
Improve regular expression's overlapping and details
Improve regular expression's overlapping and details
JavaScript
mit
eush77/nbsp-advisor
d64d4fd171002890c5bc3a5e2ea697e03b37c59d
src/dom_components/view/ToolbarButtonView.js
src/dom_components/view/ToolbarButtonView.js
var Backbone = require('backbone'); module.exports = Backbone.View.extend({ events() { return ( this.model.get('events') || { mousedown: 'handleClick' } ); }, attributes() { return this.model.get('attributes'); }, initialize(opts) { this.editor = opts.config.editor; }, handleClick(event) { event.preventDefault(); event.stopPropagation(); this.execCommand(event); }, execCommand(event) { const opts = { event }; const command = this.model.get('command'); const editor = this.editor; if (typeof command === 'function') { command(editor, null, opts); } if (typeof command === 'string') { editor.runCommand(command, opts); } }, render() { var config = this.editor.getConfig(); this.el.className += ' ' + config.stylePrefix + 'toolbar-item'; return this; } });
var Backbone = require('backbone'); module.exports = Backbone.View.extend({ events() { return ( this.model.get('events') || { mousedown: 'handleClick' } ); }, attributes() { return this.model.get('attributes'); }, initialize(opts) { this.editor = opts.config.editor; }, handleClick(event) { event.preventDefault(); event.stopPropagation(); this.execCommand(event); }, execCommand(event) { const opts = { event }; const command = this.model.get('command'); const editor = this.editor; if (typeof command === 'function') { command(editor, null, opts); } if (typeof command === 'string') { editor.runCommand(command, opts); } }, render() { const { editor, $el, model } = this; const label = model.get('label'); const pfx = editor.getConfig('stylePrefix'); $el.addClass(`${pfx}toolbar-item`); label && $el.append(label); return this; } });
Add the possibility to append `label` on component toolbar buttons
Add the possibility to append `label` on component toolbar buttons
JavaScript
bsd-3-clause
QuorumDMS/grapesjs,artf/grapesjs,artf/grapesjs,QuorumDMS/grapesjs,artf/grapesjs
5fee62511ed5e733d501e86ac8fe8e0516ba8a54
src/util/maintenance/index.js
src/util/maintenance/index.js
const AssignedSchedule = require('../../structs/db/AssignedSchedule.js') const pruneGuilds = require('./pruneGuilds.js') const pruneFeeds = require('./pruneFeeds.js') const pruneFormats = require('./pruneFormats.js') const pruneFailCounters = require('./pruneFailCounters.js') const pruneSubscribers = require('./pruneSubscribers.js') const pruneCollections = require('./pruneCollections.js') const flushRedis = require('./flushRedis.js') /** * @param {Set<string>} guildIds * @param {import('discord.js').Client} bot */ async function prunePreInit (guildIds, bot) { await Promise.all([ AssignedSchedule.deleteAll(), flushRedis(), pruneGuilds(guildIds) ]) await pruneFeeds(guildIds) await Promise.all([ pruneFormats(), pruneFailCounters() ]) if (bot) { await pruneSubscribers(bot) } // Prune collections should not be called here until schedules were assigned } async function prunePostInit () { await pruneCollections() } module.exports = { flushRedis, prunePreInit, prunePostInit, pruneGuilds, pruneFeeds, pruneFormats, pruneFailCounters, pruneSubscribers, pruneCollections }
const AssignedSchedule = require('../../structs/db/AssignedSchedule.js') const pruneGuilds = require('./pruneGuilds.js') const pruneFeeds = require('./pruneFeeds.js') const pruneFormats = require('./pruneFormats.js') const pruneFailCounters = require('./pruneFailCounters.js') const pruneSubscribers = require('./pruneSubscribers.js') const pruneCollections = require('./pruneCollections.js') const flushRedis = require('./flushRedis.js') const checkLimits = require('./checkLimits.js') const checkPermissions = require('./checkPermissions.js') /** * @param {Set<string>} guildIds * @param {import('discord.js').Client} bot */ async function prunePreInit (guildIds, bot) { await Promise.all([ AssignedSchedule.deleteAll(), flushRedis(), pruneGuilds(guildIds) ]) await pruneFeeds(guildIds) await Promise.all([ pruneFormats(), pruneFailCounters() ]) if (bot) { await pruneSubscribers(bot) } // Prune collections should not be called here until schedules were assigned } async function prunePostInit () { await pruneCollections() } module.exports = { flushRedis, prunePreInit, prunePostInit, pruneGuilds, pruneFeeds, pruneFormats, pruneFailCounters, pruneSubscribers, pruneCollections, checkLimits, checkPermissions }
Add missing funcs to util maintenance
Add missing funcs to util maintenance
JavaScript
mit
synzen/Discord.RSS,synzen/Discord.RSS
78fc9a890a4bb46eae99cc3ccbe8eaf2e0a07068
src/parser/shaman/enhancement/modules/features/Checklist/Component.js
src/parser/shaman/enhancement/modules/features/Checklist/Component.js
import React from 'react'; import PropTypes from 'prop-types'; import Checklist from 'parser/shared/modules/features/Checklist2'; import Rule from 'parser/shared/modules/features/Checklist2/Rule'; import Requirement from 'parser/shared/modules/features/Checklist2/Requirement'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; const DowntimeDescription = () => ( <> You should try to avoid doing nothing during the fight. If you have to move, try casting something instant with range like <SpellLink id={SPELLS.FLAMETONGUE.id} /> or <SpellLink id={SPELLS.ROCKBITER.id} /> </> ); class EnhancementShamanChecklist extends React.PureComponent { static propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { combatant, castEfficiency, thresholds } = this.props; return ( <Checklist> <Rule name="Always be casting" description={DowntimeDescription} > <Requirement name="Downtime" thresholds={thresholds.alwaysBeCasting} /> </Rule> </Checklist> ); } } export default EnhancementShamanChecklist;
import React from 'react'; import PropTypes from 'prop-types'; import Checklist from 'parser/shared/modules/features/Checklist2'; import Rule from 'parser/shared/modules/features/Checklist2/Rule'; import Requirement from 'parser/shared/modules/features/Checklist2/Requirement'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; const DowntimeDescription = () => ( <> You should try to avoid doing nothing during the fight. If you have to move, try casting something instant with range like <SpellLink id={SPELLS.FLAMETONGUE.id} /> or <SpellLink id={SPELLS.ROCKBITER.id} /> </> ); class EnhancementShamanChecklist extends React.PureComponent { static propTypes = { castEfficiency: PropTypes.object.isRequired, combatant: PropTypes.shape({ hasTalent: PropTypes.func.isRequired, hasTrinket: PropTypes.func.isRequired, }).isRequired, thresholds: PropTypes.object.isRequired, }; render() { const { combatant, castEfficiency, thresholds } = this.props; return ( <Checklist> <Rule name="Always be casting" description={<DowntimeDescription />} > <Requirement name="Downtime" thresholds={thresholds.alwaysBeCasting} /> </Rule> </Checklist> ); } } export default EnhancementShamanChecklist;
Fix DowntimeDescription not showing on checklist
Fix DowntimeDescription not showing on checklist
JavaScript
agpl-3.0
anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,yajinni/WoWAnalyzer,fyruna/WoWAnalyzer,FaideWW/WoWAnalyzer,fyruna/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,ronaldpereira/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,yajinni/WoWAnalyzer,fyruna/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,ronaldpereira/WoWAnalyzer,FaideWW/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,FaideWW/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer
3de08c1740dac5c258d7291aba11f996c6e27c47
bin/gh.js
bin/gh.js
#!/usr/bin/env node /* * Copyright 2013 Eduardo Lundgren, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Eduardo Lundgren <eduardolundgren@gmail.com> */ var async = require('async'), fs = require('fs'), nopt = require('nopt'), base = require('../lib/base'), git = require('../lib/git'), commandFilePath, commandImpl, logger, operations, options, parsed, remain; logger = base.logger; operations = []; parsed = nopt(process.argv), remain = parsed.argv.remain; if (!remain.length) { logger.oops('usage: gh [command] [payload] [--flags]'); } commandFilePath = __dirname + '/../lib/cmds/' + remain[0] + '.js'; if (fs.existsSync(commandFilePath)) { commandImpl = require(commandFilePath).Impl; options = nopt( commandImpl.DETAILS.options, commandImpl.DETAILS.shorthands, process.argv, 2); operations.push(git.getRepositoryName); operations.push(git.getCurrentBranch); async.parallel(operations, function(err, results) { new commandImpl().run(options, results[0], results[1]); }); } else { logger.oops('command not found'); }
#!/usr/bin/env node /* * Copyright 2013 Eduardo Lundgren, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/eduardolundgren/blob/master/LICENSE.md * * @author Eduardo Lundgren <eduardolundgren@gmail.com> */ var async = require('async'), fs = require('fs'), nopt = require('nopt'), base = require('../lib/base'), git = require('../lib/git'), commandFilePath, commandImpl, logger, operations, options, parsed, remain; logger = base.logger; operations = []; parsed = nopt(process.argv), remain = parsed.argv.remain; if (!remain.length) { logger.oops('usage: gh [command] [payload] [--flags]'); } commandFilePath = __dirname + '/../lib/cmds/' + remain[0] + '.js'; if (fs.existsSync(commandFilePath)) { commandImpl = require(commandFilePath).Impl; options = nopt( commandImpl.DETAILS.options, commandImpl.DETAILS.shorthands, process.argv, 2); operations.push(git.getRepositoryName); operations.push(git.getCurrentBranch); async.parallel(operations, function(err, results) { new commandImpl(options, results[0], results[1]).run(); }); } else { logger.oops('command not found'); }
Change constructor to receive (options, repo, branch)
Change constructor to receive (options, repo, branch)
JavaScript
bsd-3-clause
tomzx/gh,TomzxForks/gh,oouyang/gh,TomzxForks/gh,oouyang/gh,dustinryerson/gh,dustinryerson/gh,modulexcite/gh,modulexcite/gh,tomzx/gh,henvic/gh,henvic/gh
abdee493c6b6a9811eae773bf07512834e228afa
server/api/conversion/index.js
server/api/conversion/index.js
'use strict'; var express = require('express'); var controller = require('./conversion.controller'); var router = express.Router(); router.post('/import', controller.import); router.post('/export/:format(cml,pdb,mol,mol2,smiles,hin)', controller.export); module.exports = router;
'use strict'; var express = require('express'); var controller = require('./conversion.controller'); var router = express.Router(); router.post('/import', controller.import); router.post('/export/:format(cml|pdb|mol|mol2|smiles|hin)', controller.export); module.exports = router;
Fix pattern for export formats
fixed: Fix pattern for export formats
JavaScript
apache-2.0
mohebifar/chemozart,mohebifar/chemozart,U4ICKleviathan/chemozart,U4ICKleviathan/chemozart
5205890e7806ea1997d02e8bb2b1554e34418d04
site/assets/_folder-of-crap.js
site/assets/_folder-of-crap.js
$(".container").addClass("tk-proxima-nova"); $(".page-header").addClass("tk-league-gothic"); $("td:nth-child(2)").each(function() { $(this).text(moment($.trim($(this).text()), "DD-MMM-YYYY HH:mm").fromNow()); });
$("td:nth-child(2)").each(function() { $(this).text(moment($.trim($(this).text()), "DD-MMM-YYYY HH:mm").fromNow()); });
Change how Typekit fonts are applied.
Change how Typekit fonts are applied. Prevent the FOUC that sometimes occurs by having Typekit apply fonts instead of handling it ourselves.
JavaScript
mit
damiendart/robotinaponcho,damiendart/robotinaponcho,damiendart/robotinaponcho
1b5cde782e42cf48c29a09921b1aec62c5be876a
eloquent_js/chapter09/ch09_ex03.js
eloquent_js/chapter09/ch09_ex03.js
let number = /^[+-]?\d*(\d\.|\.\d)?\d*([eE][+-]?\d+)?$/;
let number = /^[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?$/;
Add chapter 9, exercise 3
Add chapter 9, exercise 3
JavaScript
mit
bewuethr/ctci
d648388d8c9297efb610e86904853b937c051582
eloquent_js/chapter11/ch11_ex01.js
eloquent_js/chapter11/ch11_ex01.js
async function locateScalpel(nest) { let curNest = nest.name; for (;;) { let scalpelLoc = await anyStorage(nest, curNest, "scalpel"); if (scalpelLoc == curNest) return curNest; curNest = scalpelLoc; } } function locateScalpel2(nest) { let next = nest.name; function getNext(next) { return anyStorage(nest, next, "scalpel") .then(val => val == next ? next : getNext(val)); } return getNext(next); } locateScalpel(bigOak).then(console.log); // → Butcher's Shop locateScalpel2(bigOak).then(console.log); // → Butcher's Shop
async function locateScalpel(nest) { let current = nest.name; for (;;) { let next = await anyStorage(nest, current, "scalpel"); if (next == current) { return next; } current = next; } } function locateScalpel2(nest) { function next(current) { return anyStorage(nest, current, "scalpel") .then(value => value == current ? value : next(value)); } return next(nest.name); }
Add chapter 11, exercise 1
Add chapter 11, exercise 1
JavaScript
mit
bewuethr/ctci
d959e87e16280eb4cbcb7ca80b64c89cacde2662
addon/components/simple-table-cell.js
addon/components/simple-table-cell.js
import Ember from 'ember'; import layout from '../templates/components/simple-table-cell'; export default Ember.Component.extend({ layout, tagName: 'th', classNameBindings: ['columnsClass'], attributeBindings: ['rowspan', 'colspan', 'columnsStyle:style'], columnsClass: Ember.computed.alias('columns.classes'), columnsStyle: Ember.computed('columns.style', { get() { return Ember.String.htmlSafe(this.get('columns.style')); } }), actions: { sortBy(key) { return this.get('sortAction')(key); } } });
import Ember from 'ember'; import layout from '../templates/components/simple-table-cell'; export default Ember.Component.extend({ layout, tagName: 'th', classNameBindings: ['columnsClass'], attributeBindings: ['rowspan', 'colspan', 'columnsStyle:style'], columnsClass: Ember.computed('columns.classes', { get() { let columns = this.get('columns'); let column = Ember.isArray(columns) ? columns[0] : columns; return Ember.String.htmlSafe(column.classes); } }), columnsStyle: Ember.computed('columns.style', { get() { let columns = this.get('columns'); let column = Ember.isArray(columns) ? columns[0] : columns; return Ember.String.htmlSafe(column.style); } }), actions: { sortBy(key) { return this.get('sortAction')(key); } } });
Fix styles and classes for grouped columns
Fix styles and classes for grouped columns
JavaScript
mit
Baltazore/ember-simple-table,Baltazore/ember-simple-table
2c1b1b6d2b35ce363ca950e57d11e0e33b95dac2
fetch-node.js
fetch-node.js
'use strict'; var fetch = require('node-fetch'); var URL = require('url').URL; function wrapFetchForNode(fetch) { // Support schemaless URIs on the server for parity with the browser. // https://github.com/matthew-andrews/isomorphic-fetch/pull/10 return function (u, options) { if (u instanceof URL) { return fetch(u, options); } if (u instanceof fetch.Request) { return fetch(u, options); } var url = u.slice(0, 2) === '//' ? 'https:' + u : u; return fetch(url, options); }; } module.exports = function (context) { // This modifies the global `node-fetch` object, which isn't great, since // different callers to `fetch-ponyfill` which pass a different Promise // implementation would each expect to have their implementation used. But, // given the way `node-fetch` is implemented, this is the only way to make // it work at all. if (context && context.Promise) { fetch.Promise = context.Promise; } return { fetch: wrapFetchForNode(fetch), Headers: fetch.Headers, Request: fetch.Request, Response: fetch.Response }; };
'use strict'; var fetch = require('node-fetch'); var URL = require('url').URL; function wrapFetchForNode(fetch) { // Support schemaless URIs on the server for parity with the browser. // https://github.com/matthew-andrews/isomorphic-fetch/pull/10 return function (u, options) { if (typeof u === 'string' && u.slice(0, 2) === '//') { return fetch('https:' + u, options); } return fetch(u, options); }; } module.exports = function (context) { // This modifies the global `node-fetch` object, which isn't great, since // different callers to `fetch-ponyfill` which pass a different Promise // implementation would each expect to have their implementation used. But, // given the way `node-fetch` is implemented, this is the only way to make // it work at all. if (context && context.Promise) { fetch.Promise = context.Promise; } return { fetch: wrapFetchForNode(fetch), Headers: fetch.Headers, Request: fetch.Request, Response: fetch.Response }; };
Change to treat the string as a special case
Change to treat the string as a special case
JavaScript
mit
qubyte/fetch-ponyfill,qubyte/fetch-ponyfill
3515ea1cf459874f3a487e7c30fc585eb21f1f7f
app/assets/scripts/utils/constants.js
app/assets/scripts/utils/constants.js
'use strict'; import { t } from '../utils/i18n'; export const fileTypesMatrix = { 'admin-bounds': { display: t('Administrative Boundaries'), description: t('A GeoJSON containing polygons with the administrative boundaries.') }, origins: { display: t('Population data'), description: t('A GeoJSON with population point data. This will be used as the Origin in the analysis.') }, poi: { display: t('Points of Interest'), description: t('GeoJSON for the Points of Interest (eg. banks or hospitals). These are the destinations in the analysis.') }, 'road-network': { display: t('Road Network'), description: t('The underlying road network in OSM XML format.') }, profile: { display: t('Profile'), description: t('A lua file with the OSRM Profile.') } };
'use strict'; import { t } from '../utils/i18n'; export const fileTypesMatrix = { 'admin-bounds': { display: t('Administrative Boundaries'), description: t('A GeoJSON containing polygons with the administrative boundaries.'), helpPath: '/help#administrative-boundaries' }, origins: { display: t('Population data'), description: t('A GeoJSON with population point data. This will be used as the Origin in the analysis.'), helpPath: '/help#population-data' }, poi: { display: t('Points of Interest'), description: t('GeoJSON for the Points of Interest (eg. banks or hospitals). These are the destinations in the analysis.'), helpPath: '/help#points-of-interest' }, 'road-network': { display: t('Road Network'), description: t('The underlying road network in OSM XML format.'), helpPath: '/help#road-network' }, profile: { display: t('Profile'), description: t('A lua file with the OSRM Profile.'), helpPath: '/help#profile' } };
Add help path to poi data
Add help path to poi data
JavaScript
mit
WorldBank-Transport/rra-frontend,WorldBank-Transport/rra-frontend,WorldBank-Transport/rra-frontend
28590b794f879b426d9aaf1247ddbed2ae30170e
client/app/redux/reducers/series/series.test.js
client/app/redux/reducers/series/series.test.js
import assert from 'assert'; import series from './series'; import * as TYPES from '../../actions/types'; describe('A series reducer for redux state', () => { //Test states const seriesDefaultState = {}; const seriesWithTicker = { GOOGL: [] }; //Test actions const testAddSeries = { type: TYPES.ADD_SERIES, ticker: 'GOOGL', data: [], } const testInvalidAction = { type: 'INVALID_ACTION', } it('should return a default state when no arguments are supplied', () => { assert.deepEqual(series(), seriesDefaultState ); }) it('should add an empty series attribute if it is missing from the supplied state', () => { assert.deepEqual(series({}), seriesDefaultState); }) it('should return an unchanged state when no actions are supplied', () => { assert.deepEqual(series(seriesDefaultState), seriesDefaultState); }) it('should return an unchanged state when an invalid action is supplied', () => { assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState); }) it('should return a new state based on a passed action', () => { assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker); }) it('should return a new object', () => { assert(series({}) !== {}); }) })
import assert from 'assert'; import series from './series'; import * as TYPES from '../../actions/types'; describe('A series reducer for redux state', () => { //Test states const seriesDefaultState = {}; const seriesWithTicker = { GOOGL: [] }; //Test actions const testAddSeries = { type: TYPES.ADD_SERIES, ticker: 'GOOGL', data: [], } const testDelSeries = { type: TYPES.DEL_SERIES, ticker: 'GOOGL', } const testInvalidAction = { type: 'INVALID_ACTION', } it('should return a default state when no arguments are supplied', () => { assert.deepEqual(series(), seriesDefaultState ); }) it('should add an empty series attribute if it is missing from the supplied state', () => { assert.deepEqual(series({}), seriesDefaultState); }) it('should return an unchanged state when no actions are supplied', () => { assert.deepEqual(series(seriesDefaultState), seriesDefaultState); }) it('should return an unchanged state when an invalid action is supplied', () => { assert.deepEqual(series(seriesDefaultState, testInvalidAction), seriesDefaultState); }) it('should return a new state based on a ADD_SERIES action', () => { assert.deepEqual(series(seriesDefaultState, testAddSeries), seriesWithTicker); }) it('should return a new state based on a DEL_SERIES action', () => { assert.deepEqual(series(seriesDefaultState, testDelSeries), seriesDefaultState); }) it('should return a new object', () => { assert(series({}) !== {}); }) })
Test coverage for DEL_SERIES action
Test coverage for DEL_SERIES action
JavaScript
mit
fongelias/cofin,fongelias/cofin
f447483548193175cbb68780ba5a4b146183c964
__tests__/app.test.js
__tests__/app.test.js
/* eslint-env jest */ const { exec } = require('child_process') const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') await exec('docker cp dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') app = await require('../app') await twoSeconds() }) afterAll(done => exec('docker kill scraper_test_db', done)) describe('courses endpoint', () => { test('/courses succeeds', async () => { const response = await request(app).get('/courses') expect(response.type).toBe('application/json') expect(response.statusCode).toBe(200) }) test('/courses returns an Array', async () => { const response = await request(app).get('/courses') expect(Array.isArray(response.body)).toBeTruthy() }) }) function twoSeconds () { return new Promise(resolve => { setTimeout(() => { resolve() }, 2000) }) }
/* eslint-env jest */ const util = require('util') const exec = util.promisify(require('child_process').exec) const request = require('supertest') let app // start a mongo instance loaded with test data using docker beforeAll(async () => { await exec('docker run --name scraper_test_db -d --rm -p 27017:27017 mongo') await exec('docker cp __tests__/dump/ scraper_test_db:/dump') await exec('docker exec scraper_test_db mongorestore /dump') app = require('../app') await twoSeconds() }) afterAll(done => exec('docker kill scraper_test_db', done)) describe('courses endpoint', () => { test('/courses succeeds', async () => { const response = await request(app).get('/courses') expect(response.type).toBe('application/json') expect(response.statusCode).toBe(200) }) test('/courses returns an Array', async () => { const response = await request(app).get('/courses') expect(Array.isArray(response.body)).toBeTruthy() }) }) function twoSeconds () { return new Promise(resolve => { setTimeout(() => { resolve() }, 2000) }) }
Test db should have data now
Test db should have data now Didn’t realize that child_process functions don’t return promises
JavaScript
apache-2.0
classmere/api
3797f5b68e1426135dbc60729610087a3502d2ed
spec/install/get-email-spec.js
spec/install/get-email-spec.js
'use strict'; const fs = require('fs'); const GetEmail = require('../../lib/install/get-email'); describe('GetEmail', () => { let step; beforeEach(() => { step = new GetEmail(); }); describe('.start()', () => { describe('when the user has a .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(`[user] email = some.email@company.com`); }); it('returns a promise that is resolved with the user email', () => { waitsForPromise(() => step.start().then(data => { expect(data.email).toEqual('some.email@company.com'); })); }); }); describe('when the user has a .gitconfig file without an email', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(''); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); describe('when the user has no .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andCallFake(() => { throw new Error(); }); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); }); });
'use strict'; const fs = require('fs'); const GetEmail = require('../../lib/install/get-email'); describe('GetEmail', () => { let step; beforeEach(() => { step = new GetEmail(); }); describe('.start()', () => { afterEach(() => { fs.readFileSync.andCallThrough(); }); describe('when the user has a .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(`[user] email = some.email@company.com`); }); it('returns a promise that is resolved with the user email', () => { waitsForPromise(() => step.start().then(data => { expect(data.email).toEqual('some.email@company.com'); })); }); }); describe('when the user has a .gitconfig file without an email', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andReturn(''); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); describe('when the user has no .gitconfig file', () => { beforeEach(() => { spyOn(fs, 'readFileSync').andCallFake(() => { throw new Error(); }); }); it('returns a promise that is resolved with null', () => { waitsForPromise(() => step.start().then(data => { expect(data).toEqual({email: undefined}); })); }); }); }); });
Fix tests relying on fs spies
:green_heart: Fix tests relying on fs spies
JavaScript
bsd-3-clause
kiteco/kite-installer
f22f904a07059b3060d6818b926ec6aaf9571f71
src/operator/create/fromArray.js
src/operator/create/fromArray.js
const fromArray = array => createObservable((push, end) => { array.forEach(value => { push(value); }); end(); });
const fromArray = array => createObservable((push, end) => { if (array == null) { array = []; } array.forEach(value => { push(value); }); end(); });
Allow observable creation with no argument
Allow observable creation with no argument
JavaScript
mit
hhelwich/observable,hhelwich/observable
ffb8c1d6a86d60ebc6306db8e46762c480512f7f
interface_config.js
interface_config.js
var interfaceConfig = { CANVAS_EXTRA: 104, CANVAS_RADIUS: 7, SHADOW_COLOR: '#00ccff', INITIAL_TOOLBAR_TIMEOUT: 20000, TOOLBAR_TIMEOUT: 4000, DEFAULT_REMOTE_DISPLAY_NAME: "Fellow Jitster", DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME: "Speaker", SHOW_JITSI_WATERMARK: true, JITSI_WATERMARK_LINK: "http://jitsi.org", SHOW_BRAND_WATERMARK: false, BRAND_WATERMARK_LINK: "", SHOW_POWERED_BY: false, GENERATE_ROOMNAMES_ON_WELCOME_PAGE: true };
var interfaceConfig = { CANVAS_EXTRA: 104, CANVAS_RADIUS: 7, SHADOW_COLOR: '#ffffff', INITIAL_TOOLBAR_TIMEOUT: 20000, TOOLBAR_TIMEOUT: 4000, DEFAULT_REMOTE_DISPLAY_NAME: "Fellow Jitster", DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME: "Speaker", SHOW_JITSI_WATERMARK: true, JITSI_WATERMARK_LINK: "http://jitsi.org", SHOW_BRAND_WATERMARK: false, BRAND_WATERMARK_LINK: "", SHOW_POWERED_BY: false, GENERATE_ROOMNAMES_ON_WELCOME_PAGE: true };
Change the color of the audio levels indicator.
Change the color of the audio levels indicator.
JavaScript
apache-2.0
dwanghf/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,nwittstruck/jitsi-meet,bgrozev/jitsi-meet,learnium/jitsi-meet,gerges/jitsi-meet,gerges/jitsi-meet,gpolitis/jitsi-meet,Aharobot/jitsi-meet,bickelj/jitsi-meet,JiYou/jitsi-meet,IpexCloud/jitsi-meet,dyweb/jitsi-meet,luciash/jitsi-meet-bootstrap,gpolitis/jitsi-meet,gpolitis/jitsi-meet,pstros/jitsi-meet,kosmosby/jitsi-meet,dyweb/jitsi-meet,gpolitis/jitsi-meet,JiYou/jitsi-meet,bhatvv/jitsi-meet,kosmosby/jitsi-meet,bgrozev/jitsi-meet,dyweb/jitsi-meet,bhatvv/jitsi-meet,pstros/jitsi-meet,micahflee/jitsi-meet,gpolitis/jitsi-meet,learnium/jitsi-meet,isymchych/jitsi-meet,NxTec/jitsi-meet,procandi/jitsi-meet,jitsi/jitsi-meet,procandi/jitsi-meet,buzzyboy/jitsi-meet,jitsi/jitsi-meet,tsunli/jitsi-meet,bgrozev/jitsi-meet,buzzyboy/jitsi-meet,NxTec/jitsi-meet,IpexCloud/jitsi-meet,bgrozev/jitsi-meet,isymchych/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,bickelj/jitsi-meet,tsareg/jitsi-meet,tsunli/jitsi-meet,learnium/jitsi-meet,b100w11/jitsi-meet,dwanghf/jitsi-meet,luciash/jitsi-meet-bootstrap,buzzyboy/jitsi-meet,b100w11/jitsi-meet,jitsi/jitsi-meet,magatz/jitsi-meet-mod,Aharobot/jitsi-meet,micahflee/jitsi-meet,jitsi/jitsi-meet,gerges/jitsi-meet,kosmosby/jitsi-meet,jitsi/jitsi-meet,Aharobot/jitsi-meet,procandi/jitsi-meet,bhatvv/jitsi-meet,magatz/jitsi-meet-mod,gpolitis/jitsi-meet,tsunli/jitsi-meet,gpolitis/jitsi-meet,dwanghf/jitsi-meet,NxTec/jitsi-meet,bgrozev/jitsi-meet,JiYou/jitsi-meet,tsareg/jitsi-meet,jitsi/jitsi-meet,b100w11/jitsi-meet
bc861e0d9ac49bbba0fdd4288f67463a9aca36af
lib/builder-registry.js
lib/builder-registry.js
'use babel' import fs from 'fs-plus' import path from 'path' export default class BuilderRegistry { getBuilder (filePath) { const builders = this.getAllBuilders() const candidates = builders.filter((builder) => builder.canProcess(filePath)) switch (candidates.length) { case 0: return null case 1: return candidates[0] } return this.resolveAmbigiousBuilders(candidates) } getAllBuilders () { const moduleDir = path.join(__dirname, 'builders') const entries = fs.readdirSync(moduleDir) const builders = entries.map((entry) => require(path.join(moduleDir, entry))) return builders } resolveAmbigiousBuilders (builders) { const names = builders.map((builder) => builder.name) const indexOfLatexmk = names.indexOf('LatexmkBuilder') const indexOfTexify = names.indexOf('TexifyBuilder') if (names.length === 2 && indexOfLatexmk >= 0 && indexOfTexify >= 0) { switch (atom.config.get('latex.builder')) { case 'latexmk': return builders[indexOfLatexmk] case 'texify': return builders[indexOfTexify] } } throw Error('Unable to resolve ambigous builder registration') } }
'use babel' import _ from 'lodash' import fs from 'fs-plus' import path from 'path' import MagicParser from './parsers/magic-parser' export default class BuilderRegistry { getBuilder (filePath) { const builders = this.getAllBuilders() const candidates = builders.filter((builder) => builder.canProcess(filePath)) switch (candidates.length) { case 0: return null case 1: return candidates[0] } return this.resolveAmbiguousBuilders(candidates, this.getBuilderFromMagic(filePath)) } getBuilderFromMagic (filePath) { const magic = new MagicParser(filePath).parse() if (magic && magic.builder) { return magic.builder } return null } getAllBuilders () { const moduleDir = path.join(__dirname, 'builders') const entries = fs.readdirSync(moduleDir) const builders = entries.map((entry) => require(path.join(moduleDir, entry))) return builders } resolveAmbiguousBuilders (builders, builderOverride) { const name = builderOverride || atom.config.get('latex.builder') const namePattern = new RegExp(`^${name}Builder$`, 'i') const builder = _.find(builders, builder => builder.name.match(namePattern)) if (builder) return builder latex.log.warning(`Unable to resolve builder named ${name} using fallback ${builders[0].name}.`) return builders[0] } }
Use TeX magic to allow bulder override
Use TeX magic to allow bulder override
JavaScript
mit
thomasjo/atom-latex,thomasjo/atom-latex,thomasjo/atom-latex
43d297eadf58327bfefe81ced42bdb23099548fe
lib/dujs/domainscope.js
lib/dujs/domainscope.js
/* * DomainScope module * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-28 */ var Scope = require('./scope'); /** * DomainScope * @param {Object} cfg Graph of the domain scope * @constructor */ function DomainScope(cfg) { "use strict"; Scope.call(this, cfg, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype); Object.defineProperty(DomainScope.prototype, 'constructor', { value: DomainScope }); /* start-public-data-members */ Object.defineProperties(DomainScope.prototype, { /** * Array of build-in objects * @type {Array} * @memberof DomainScope.prototype * @inheritdoc */ builtInObjects: { get: function () { "use strict"; /* manual */ return [ {name: "localStorage", def: "localStorage"} ]; } } }); /* end-public-data-members */ module.exports = DomainScope;
/* * DomainScope module * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-28 */ var Scope = require('./scope'); /** * DomainScope * @constructor */ function DomainScope() { "use strict"; Scope.call(this, null, Scope.DOMAIN_SCOPE_NAME, Scope.DOMAIN_TYPE, null); } DomainScope.prototype = Object.create(Scope.prototype); Object.defineProperty(DomainScope.prototype, 'constructor', { value: DomainScope }); /* start-public-data-members */ Object.defineProperties(DomainScope.prototype, { /** * Array of build-in objects * @type {Array} * @memberof DomainScope.prototype * @inheritdoc */ builtInObjects: { get: function () { "use strict"; /* manual */ return [ {name: "localStorage", def: "localStorage"} ]; } } }); /* end-public-data-members */ module.exports = DomainScope;
Refactor to be constructed without parameters
Refactor to be constructed without parameters
JavaScript
mit
chengfulin/dujs,chengfulin/dujs
1624dadd1dd621ae631e73db85385dce79138d71
lib/material/endgame.js
lib/material/endgame.js
'use strict'; var generate = require('../generate'); exports.endgames = [ 'nefarious purposes', 'a Washington takeover', 'a terrorist plot', 'world domination', 'a plot against the queen' ]; exports.get = generate.random(exports.endgames);
'use strict'; var generate = require('../generate'); exports.endgames = [ 'a plot against the queen', 'a terrorist plot', 'a Washington takeover', 'nefarious purposes', 'world domination', ]; exports.get = generate.random(exports.endgames);
Make sorting and trailing commas consistent
Make sorting and trailing commas consistent
JavaScript
mit
rowanmanning/conspire
8e44baa3db6723dd83cf8bd5d9686c3d2eb33be1
src/lib/Knekt.js
src/lib/Knekt.js
/** * Created by Alex on 29/01/2017. */ import Hapi from 'hapi'; export class Knekt { constructor() { this._server = new Hapi.Server(); this.plugins = []; } setConnection(host, port) { this._server.connection({host: host, port: port}); } listen() { this._server.start((err) => { if (err) { throw err; } console.log(`Knekt running at ${this._server.info.uri} !`); }); } register(plugins) { plugins.forEach((plugin) => { this.plugins.push(new plugin(this)); }); } addRoute(parameters) { this._server.route(parameters); } }
/** * Created by Alex on 29/01/2017. */ import Hapi from 'hapi'; //core routes import Descriptor from './routes/descriptor'; export class Knekt { constructor() { this._server = new Hapi.Server(); this.plugins = []; } setConnection(host, port) { this._server.connection({host: host, port: port}); } listen() { this._server.start((err) => { if (err) { throw err; } this._registerCoreRoutes(); console.log(`Knekt running at ${this._server.info.uri} !`); }); } register(plugins) { plugins.forEach((plugin) => { this.plugins.push(new plugin(this).properties); }); } addRoute(parameters) { this._server.route(parameters); } _registerCoreRoutes() { this._server.route(Descriptor(this)); } }
Update to register descriptor route
Update to register descriptor route
JavaScript
mit
goKnekt/Knekt-Server
0575210aeacc6a984df7a9b9224154a5900d3ad8
src/components/PlaylistManager/Panel/ShufflePlaylistButton.js
src/components/PlaylistManager/Panel/ShufflePlaylistButton.js
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setTimeout(() => { setLoading(false); }, 10000); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setLoading(false); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
Remove setTimeout left over from debugging.
Remove setTimeout left over from debugging.
JavaScript
mit
u-wave/web,u-wave/web
202038131d2843815c5062950e4dd14dfb8cac6c
src/app/relay/TeamMenuRelay.js
src/app/relay/TeamMenuRelay.js
import React, { Component, PropTypes } from 'react'; import Relay from 'react-relay'; import TeamRoute from './TeamRoute'; import Can from '../components/Can'; import CheckContext from '../CheckContext'; import { teamSubdomain } from '../helpers'; class TeamMenu extends Component { render() { const { team } = this.props; const history = new CheckContext(this).getContextStore().history; return ( <Can permissions={team.permissions} permission="update Team"> <li className="header-actions__menu-item" onClick={history.push.bind(this, '/members')}>Manage team...</li> </Can> ); } } TeamMenu.contextTypes = { store: React.PropTypes.object }; const TeamMenuContainer = Relay.createContainer(TeamMenu, { fragments: { team: () => Relay.QL` fragment on Team { id, dbid, name, permissions, } ` }, }); class TeamMenuRelay extends Component { render() { if (teamSubdomain()) { const route = new TeamRoute({ teamId: '' }); return (<Relay.RootContainer Component={TeamMenuContainer} route={route} />); } else { return null; } } } export default TeamMenuRelay;
import React, { Component, PropTypes } from 'react'; import Relay from 'react-relay'; import TeamRoute from './TeamRoute'; import Can from '../components/Can'; import CheckContext from '../CheckContext'; import { teamSubdomain } from '../helpers'; class TeamMenu extends Component { render() { const { team } = this.props; const history = new CheckContext(this).getContextStore().history; return ( <Can permissions={team.permissions} permission="update Team"> <li className="header-actions__menu-item" onClick={history.push.bind(this, '/members')}>Manage team</li> </Can> ); } } TeamMenu.contextTypes = { store: React.PropTypes.object }; const TeamMenuContainer = Relay.createContainer(TeamMenu, { fragments: { team: () => Relay.QL` fragment on Team { id, dbid, name, permissions, } ` }, }); class TeamMenuRelay extends Component { render() { if (teamSubdomain()) { const route = new TeamRoute({ teamId: '' }); return (<Relay.RootContainer Component={TeamMenuContainer} route={route} />); } else { return null; } } } export default TeamMenuRelay;
Update copy for team management link
Update copy for team management link
JavaScript
mit
meedan/check-web,meedan/check-web,meedan/check-web
c19971d7e5d141af526645118f9e909545178047
client.js
client.js
var CodeMirror = require('codemirror') , bindCodemirror = require('gulf-codemirror') module.exports = setup module.exports.consumes = ['editor'] module.exports.provides = [] function setup(plugin, imports, register) { var editor = imports.editor editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor' , function(editorEl) { var cm = CodeMirror(function(el) { editorEl.appendChild(el) el.style['height'] = '100%' el.style['width'] = '100%' }) editorEl.style['height'] = '100%' return bindCodemirror(cm) }) register() }
var CodeMirror = require('codemirror') , bindCodemirror = require('gulf-codemirror') module.exports = setup module.exports.consumes = ['editor'] module.exports.provides = [] function setup(plugin, imports, register) { var editor = imports.editor editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor' , function(editorEl) { var cm = CodeMirror(function(el) { editorEl.appendChild(el) el.style['height'] = '100%' el.style['width'] = '100%' }) editorEl.style['height'] = '100%' return Promise.resolve(bindCodemirror(cm)) }) register() }
Fix setup function: Should return promise
Fix setup function: Should return promise
JavaScript
mpl-2.0
hivejs/hive-editor-text-codemirror
f066554b77700604f9f5e8de76e2c976d91ab7b0
feature-detects/css/shapes.js
feature-detects/css/shapes.js
define(['Modernizr', 'createElement', 'docElement'], function( Modernizr, createElement, docElement ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = Modernizr.prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return Modernizr.testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
Add testStyles and prefixed to the depedencies.
Add testStyles and prefixed to the depedencies.
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
60cda85ccf90bae9911ba49a710f2f10f79dab3c
funnel/assets/js/rsvp_list.js
funnel/assets/js/rsvp_list.js
import 'footable'; $(() => { $('.participants').footable({ sorting: { enabled: true, }, }); });
import 'footable'; $(() => { $('.participants').footable({ paginate: false, sorting: true, }); });
Disable pagination in rsvp page
Disable pagination in rsvp page
JavaScript
agpl-3.0
hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel
b98a7e399a90115907fd13e5edbeb28475c4ed3e
public/scripts/global.js
public/scripts/global.js
App.populator('feed', function (page, data) { $(page).find('.app-title').text(data.title); $.getJSON('/data/feed/' + data.id + '/articles', function (articles) { articles.forEach(function (article) { var li = $('<li class="app-button">' + article.title + '</li>'); li.on('click', function () { App.load('article', article); }); $(page).find('.app-list').append(li); }); }); }); App.populator('article', function (page, data) { $(page).find('.app-title').text(data.title.substring(0, 20)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' + '<a href="' + article.url + '">' + article.url + '</a></p>' + article.content; $(page).find('.app-content').html(content); }); });
App.populator('feed', function (page, data) { $(page).find('.app-title').text(data.title); $.getJSON('/data/feed/' + data.id + '/articles', function (articles) { articles.forEach(function (article) { var li = $('<li class="app-button">' + article.title + '</li>'); li.on('click', function () { App.load('article', article); }); $(page).find('.app-list').append(li); }); }); }); App.populator('article', function (page, data) { $(page).find('.app-title').text(data.title.substring(0, 30)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' + '<a href="' + article.url + '">' + article.url + '</a></p>' + article.content; $(page).find('.app-content').html(content); }); });
Change title limit to 30 chars.
Change title limit to 30 chars.
JavaScript
mit
cliffano/feedpaper,cliffano/feedpaper,cliffano/feedpaper
26c03b575dad5dbe4720b147279bdadde24f0748
packages/postcss-merge-longhand/src/index.js
packages/postcss-merge-longhand/src/index.js
import postcss from 'postcss'; import margin from './lib/decl/margin'; import padding from './lib/decl/padding'; import borders from './lib/decl/borders'; import columns from './lib/decl/columns'; const processors = [ margin, padding, borders, columns, ]; export default postcss.plugin('postcss-merge-longhand', () => { return css => { let abort = false; css.walkRules(rule => { processors.forEach(p => { const res = p.explode(rule); if (res === false) { abort = true; } }); if (abort) { return; } processors.slice().reverse().forEach(p => p.merge(rule)); }); }; });
import postcss from 'postcss'; import margin from './lib/decl/margin'; import padding from './lib/decl/padding'; import borders from './lib/decl/borders'; import columns from './lib/decl/columns'; const processors = [ margin, padding, borders, columns, ]; export default postcss.plugin('postcss-merge-longhand', () => { return css => { css.walkRules(rule => { let abort = false; processors.forEach(p => { const res = p.explode(rule); if (typeof res === 'boolean') { abort = true; } }); if (abort) { return; } processors.slice().reverse().forEach(p => p.merge(rule)); }); }; });
Resolve issue with running plugin on multiple rules.
Resolve issue with running plugin on multiple rules.
JavaScript
mit
ben-eb/cssnano
28320eeeb420ce13c5e00d670a82aab889ecc5c6
app/assets/javascripts/main.js
app/assets/javascripts/main.js
"use strict"; $(document).on("turbolinks:load", function() { //equivalent of $(document).ready() console.log("JS loaded.") addSpace(); var $grid = initMasonry(); // layout Masonry after each image loads $grid.imagesLoaded().progress( function() { $grid.masonry('layout'); }); }); function initMasonry() { return $('.masonry-grid').masonry({ //returns the jquery masonry grid to be stored as a variable // options itemSelector: '.card', // columnWidth: 280, //with no columnWidth set, will take size of first element in grid horizontalOrder: true, isFitWidth: true, //breaks columns like media queries gutter: 20, transitionDuration: '0.3s' }); } function addSpace() { var spaceBetween = $(".custom-footer").offset().top - $(".navbar").offset().top; //get space between header and footer var target = 600; if (spaceBetween < target) { //if space between header and footer < x var numOfSpaces = (target - spaceBetween) / 35; for(var i = 0; i < numOfSpaces; i++) { $("#main-container").append("<p>&nbsp</p>"); //add space above footer } } }
"use strict"; $(document).on("ready turbolinks:load", function() { //equivalent of $(document).ready() console.log("JS loaded.") addSpace(); var $grid = initMasonry(); // layout Masonry after each image loads $grid.imagesLoaded().progress( function() { $grid.masonry('layout'); }); }); function initMasonry() { return $('.masonry-grid').masonry({ //returns the jquery masonry grid to be stored as a variable // options itemSelector: '.card', // columnWidth: 280, //with no columnWidth set, will take size of first element in grid horizontalOrder: true, isFitWidth: true, //breaks columns like media queries gutter: 20, transitionDuration: '0.3s' }); } function addSpace() { var spaceBetween = $(".custom-footer").offset().top - $(".navbar").offset().top; //get space between header and footer var target = 600; if (spaceBetween < target) { //if space between header and footer < x var numOfSpaces = (target - spaceBetween) / 35; for(var i = 0; i < numOfSpaces; i++) { $("#main-container").append("<p>&nbsp</p>"); //add space above footer } } }
Adjust JS document ready function
Adjust JS document ready function
JavaScript
mit
MitulMistry/rails-storyplan,MitulMistry/rails-storyplan,MitulMistry/rails-storyplan
8d3779a37df7d199753e350b83bbe884fdae8fa8
sencha-workspace/SlateAdmin/app/model/person/progress/NoteRecipient.js
sencha-workspace/SlateAdmin/app/model/person/progress/NoteRecipient.js
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.model.person.progress.NoteRecipient', { extend: 'Ext.data.Model', idProperty: 'ID', groupField: 'RelationshipGroup', fields: [ 'FullName', 'Email', 'Label', 'Status', { name: 'selected', type: 'boolean', convert: function (v, record) { var selected = !Ext.isEmpty(record.get('Status')); return selected; } }, { name: 'PersonID', type: 'integer' }, { name: 'RelationshipGroup', convert: function (v) { return v ? v : 'Other'; } }, { name: 'ID', type: 'integer' } ], proxy: { type: 'slaterecords', api: { read: '/notes/progress/recipients', update: '/notes/save', create: '/notes/save', destory: '/notes/save' }, reader: { type: 'json', rootProperty: 'data' }, writer: { type: 'json', rootProperty: 'data', writeAllFields: false, allowSingle: false } } });
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.model.person.progress.NoteRecipient', { extend: 'Ext.data.Model', idProperty: 'ID', groupField: 'RelationshipGroup', fields: [ 'FullName', 'Email', 'Label', 'Status', { name: 'selected', type: 'boolean', convert: function (v, record) { var selected = !Ext.isEmpty(record.get('Status')); return selected; } }, { name: 'PersonID', type: 'integer' }, { name: 'RelationshipGroup', convert: function (v) { return v ? v : 'Other'; } }, { name: 'ID', type: 'integer' } ], proxy: { type: 'slaterecords', startParam: null, limitParam: null, api: { read: '/notes/progress/recipients', update: '/notes/save', create: '/notes/save', destory: '/notes/save' }, reader: { type: 'json', rootProperty: 'data' }, writer: { type: 'json', rootProperty: 'data', writeAllFields: false, allowSingle: false } } });
Disable start/limit params on recipients request
Disable start/limit params on recipients request
JavaScript
mit
SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate-admin,SlateFoundation/slate-admin
c0227b60be16470032ab03ff29ae88047fca7479
src/formatISODuration/index.js
src/formatISODuration/index.js
import requiredArgs from '../_lib/requiredArgs/index.js' /** * @name formatISODuration * @category Common Helpers * @summary Format a Duration Object according to ISO 8601 Duration standards (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) * * @param {Duration} duration * * @returns {String} The ISO 8601 Duration string * @throws {TypeError} Requires 1 argument * @throws {Error} Argument must be an object * * @example * // Get the ISO 8601 Duration between January 15, 1929 and April 4, 1968. * const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }) * // => 'P39Y2M20DT0H0M0S' */ export default function formatISODuration(duration) { requiredArgs(1, arguments) if (typeof duration !== 'object') throw new Error('Duration must be an object') const { years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0 } = duration return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S` }
import requiredArgs from '../_lib/requiredArgs/index.js' /** * @name formatISODuration * @category Common Helpers * @summary Format a duration object according as ISO 8601 duration string * * @description * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm) * * @param {Duration} duration - the duration to format * * @returns {String} The ISO 8601 duration string * @throws {TypeError} Requires 1 argument * @throws {Error} Argument must be an object * * @example * // Format the given duration as ISO 8601 string * const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }) * // => 'P39Y2M20DT0H0M0S' */ export default function formatISODuration(duration) { requiredArgs(1, arguments) if (typeof duration !== 'object') throw new Error('Duration must be an object') const { years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0 } = duration return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S` }
Fix formatISODuration documentation (ci skip)
Fix formatISODuration documentation (ci skip)
JavaScript
mit
date-fns/date-fns,date-fns/date-fns,date-fns/date-fns
951638fe79b179096c11912d3a15283bc0b13dd8
app/services/data/get-caseload-progress.js
app/services/data/get-caseload-progress.js
const config = require('../../../knexfile').web const knex = require('knex')(config) const orgUnitFinder = require('../helpers/org-unit-finder') module.exports = function (id, type) { var orgUnit = orgUnitFinder('name', type) var table = orgUnit.caseProgressView return knex(table) .where(table + '.id', id) .select(table + '.community_last_16_weeks AS communityLast16Weeks', table + '.license_last_16_weeks AS licenseLast16Weeks', table + '.total_cases AS totalCases', table + '.warrants_total AS warrantsTotal', table + '.overdue_terminations_total AS overdueTerminationsTotal', table + '.unpaid_work_total AS unpaidWorkTotal') .then(function (results) { return results }) }
const config = require('../../../knexfile').web const knex = require('knex')(config) const orgUnitFinder = require('../helpers/org-unit-finder') module.exports = function (id, type) { var orgUnit = orgUnitFinder('name', type) var table = orgUnit.caseProgressView return knex(table) .where('id', id) .select('name', 'community_last_16_weeks AS communityLast16Weeks', 'license_last_16_weeks AS licenseLast16Weeks', 'total_cases AS totalCases', 'warrants_total AS warrantsTotal', 'overdue_terminations_total AS overdueTerminationsTotal', 'unpaid_work_total AS unpaidWorkTotal') .then(function (results) { return results }) }
Update case progress query to include name
636: Update case progress query to include name
JavaScript
mit
ministryofjustice/wmt-web,ministryofjustice/wmt-web
739f618adf2fa1a971092ce6bedd913c95cc2600
assets/js/components/surveys/SurveyQuestionSingleSelectChoice.js
assets/js/components/surveys/SurveyQuestionSingleSelectChoice.js
/** * SurveyQuestionSingleSelectChoice component. * * Site Kit by Google, Copyright 2021 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. */ const SurveyQuestionSingleSelectChoice = () => { return <div>SurveyQuestionSingleSelectChoice</div>; }; export default SurveyQuestionSingleSelectChoice;
/** * SurveyQuestionSingleSelectChoice component. * * Site Kit by Google, Copyright 2021 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. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import Radio from '../Radio'; /* eslint-disable camelcase */ const SurveyQuestionSingleSelectChoice = ( { value, setValue, // writeIn, // setWriteIn, choice, } ) => { const { answer_ordinal, text } = choice; const isChecked = value === answer_ordinal; return ( <Radio value={ answer_ordinal } checked={ isChecked } name={ text } onClick={ () => setValue( answer_ordinal ) } /> ); }; SurveyQuestionSingleSelectChoice.propTypes = { value: PropTypes.string.isRequired, setValue: PropTypes.func.isRequired, writeIn: PropTypes.string.isRequired, setWriteIn: PropTypes.func.isRequired, choice: PropTypes.shape( { answer_ordinal: PropTypes.oneOfType( [ PropTypes.string, PropTypes.number, ] ), text: PropTypes.string, write_in: PropTypes.bool, } ), }; export default SurveyQuestionSingleSelectChoice;
Add radio button and link up to state.
Add radio button and link up to state.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
7782fc4d22078f0b741d20678143bd8d80876609
git/routes.js
git/routes.js
var router = require("express").Router(); var db = require("./db"); router.get("/", function (req, res) { var o = { map: function () { if (this.parents.length === 1) { for (var i = 0; i < this.files.length; i++) { emit(this.author, { additions: this.files[i].additions, deletions: this.files[i].deletions }); } } }, reduce: function (key, values) { var obj = {additions: 0, deletions: 0}; values.map(function (value) { obj.additions += value.additions; obj.deletions += value.deletions; }); return obj; } }; db.Commit.mapReduce(o, function (err, results) { if (err) { res.send(err); } else { res.send(results); } }); }); module.exports = router;
var router = require("express").Router(); var db = require("./db"); router.get("/", function (req, res) { var o = { map: function () { if (this.parents.length === 1) { for (var i = 0; i < this.files.length; i++) { emit(this.author, { additions: this.files[i].additions, deletions: this.files[i].deletions }); } } }, reduce: function (key, values) { var obj = {additions: 0, deletions: 0}; values.map(function (value) { obj.additions += value.additions; obj.deletions += value.deletions; }); return obj; }, out: { replace: 'PersonReduce' } }; db.Commit.mapReduce(o, function (err, model) { if (err) { res.send(err); } else { model.find().populate({ path: "_id", model: "Person" }).exec(function (err, results) { if (err) { res.send(err); } else { var data = results.map(function (result) { return { author: result._id.name, additions: result.value.additions, deletions: result.value.deletions }; }); res.send(data); } }); } }); }); module.exports = router;
Return more sane data through API
Return more sane data through API
JavaScript
mit
bjornarg/dev-dashboard,bjornarg/dev-dashboard