commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
90d29f9b4968cb4b3f2175847954cb76bee9825b
app/selectors/containers/searchPageSelector.js
app/selectors/containers/searchPageSelector.js
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import searchFiltersSelector from 'selectors/searchFiltersSelector'; import searchResultsSelector from 'selectors/searchResultsSelector'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const unitsSelector = (state) => state.data.units; const searchPageSelector = createSelector( requestIsActiveSelectorFactory(ActionTypes.API.RESOURCES_GET_REQUEST), searchFiltersSelector, searchResultsSelector, unitsSelector, ( isFetchingSearchResults, searchFilters, searchResults, units ) => { return { filters: searchFilters, isFetchingSearchResults, results: searchResults, units, }; } ); export default searchPageSelector;
import { createSelector } from 'reselect'; import ActionTypes from 'constants/ActionTypes'; import searchFiltersSelector from 'selectors/searchFiltersSelector'; import searchResultsSelector from 'selectors/searchResultsSelector'; import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory'; const unitsSelector = (state) => state.data.units; const searchPageSelector = createSelector( requestIsActiveSelectorFactory(ActionTypes.API.SEARCH_RESULTS_GET_REQUEST), searchFiltersSelector, searchResultsSelector, unitsSelector, ( isFetchingSearchResults, searchFilters, searchResults, units ) => { return { filters: searchFilters, isFetchingSearchResults, results: searchResults, units, }; } ); export default searchPageSelector;
Fix search page loading spinner
Fix search page loading spinner
JavaScript
mit
fastmonkeys/respa-ui
94a36fed0967ce47563c8b7b0dd31261bc4253e4
data/bouquets-data.js
data/bouquets-data.js
const Basedata = require('./base-data'); const BouquetModel = require('./models/bouquete-model'); class BouquetsData extends Basedata { constructor(db) { super(db, BouquetModel, BouquetModel); } } module.exports = BouquetsData;
const Basedata = require('./base-data'); const BouquetModel = require('./models/bouquete-model'); class BouquetsData extends Basedata { constructor(db) { super(db, BouquetModel, BouquetModel); } // override base create(bouqueteModel) { bouqueteModel.dateCreated = new Date(); bouqueteModel.viewsCount = 0; return super.create(bouqueteModel); } } module.exports = BouquetsData;
Set new properties on bouquets
Set new properties on bouquets
JavaScript
mit
viktoria-flowers/ViktoriaFlowers,viktoria-flowers/ViktoriaFlowers
b3972a05472f510278dbd5d94e95bde4ae14e6cc
packages/vulcan-admin/lib/modules/fragments.js
packages/vulcan-admin/lib/modules/fragments.js
import { registerFragment } from 'meteor/vulcan:lib'; // ------------------------------ Vote ------------------------------ // // note: fragment used by default on the UsersProfile fragment registerFragment(` fragment UsersAdmin on User { _id username createdAt isAdmin displayName email emailHash slug groups services avatarUrl } `);
import { registerFragment } from 'meteor/vulcan:lib'; // ------------------------------ Vote ------------------------------ // // note: fragment used by default on the UsersProfile fragment registerFragment(` fragment UsersAdmin on User { _id username createdAt isAdmin displayName email emailHash slug groups services avatarUrl pageUrl pagePath } `);
Add pageUrl and pagePath to user fragment;
Add pageUrl and pagePath to user fragment;
JavaScript
mit
VulcanJS/Vulcan,VulcanJS/Vulcan
3b2be9fe350de22a5a4e466287dade2ab983c9ac
lib/component.js
lib/component.js
!function(exports) { 'use strict'; var RunQueue = exports.RunQueue; function Component() { this.next = new RunQueue; this.end = new RunQueue; } Component.extend = function(constructorFn) { var scope = this; if(!constructorFn) constructorFn = function() { scope.call(this); }; constructorFn.prototype = new Component; constructorFn.prototype.constructor = constructorFn; constructorFn.prototype.proto = constructorFn.prototype; return constructorFn; } Component.prototype.init = stub(); Component.prototype.destroy = stub(); Component.prototype.before = stub(); Component.prototype.update = stub(); Component.prototype.after = stub(); Component.prototype.preprocess = stub(); Component.prototype.render = stub(); Component.prototype.postprocess = stub(); function stub() { return function(delta, x, y, z) {}; } /* * Export * ------ */ exports.Component = Component; }(seine);
!function(exports) { 'use strict'; var RunQueue = exports.RunQueue; function Component() { this.next = new RunQueue; this.end = new RunQueue; } Component.extend = function(constructorFn) { var prop, scope = this; if(!constructorFn) constructorFn = function() { scope.call(this); }; constructorFn.prototype = new Component; constructorFn.prototype.constructor = constructorFn; constructorFn.prototype.proto = constructorFn.prototype; for(prop in scope) { if(scope.hasOwnProperty(prop)) constructorFn[prop] = scope[prop]; } return constructorFn; } Component.prototype.init = stub(); Component.prototype.destroy = stub(); Component.prototype.before = stub(); Component.prototype.update = stub(); Component.prototype.after = stub(); Component.prototype.preprocess = stub(); Component.prototype.render = stub(); Component.prototype.postprocess = stub(); function stub() { return function(delta, x, y, z) {}; } /* * Export * ------ */ exports.Component = Component; }(seine);
Include class methods in extend()
[FIX] Include class methods in extend()
JavaScript
mit
reissbaker/gamekernel,reissbaker/gamekernel
7bca0c33e145e79e368f0a2dd216ea424130c312
installer/app/src/router.js
installer/app/src/router.js
import Router from 'marbles/router'; import WizardComponent from './views/wizard'; import Dispatcher from './dispatcher'; var MainRouter = Router.createClass({ routes: [ { path: '', handler: 'landingPage' }, { path: '/install/:install_id', handler: 'landingPage' } ], willInitialize: function () { Dispatcher.register(this.handleEvent.bind(this)); }, beforeHandler: function (event) { Dispatcher.dispatch({ name: 'LOAD_INSTALL', id: event.params[0].install_id || '' }); }, landingPage: function (params, opts, context) { var props = { dataStore: context.dataStore }; context.render(WizardComponent, props); }, handleEvent: function (event) { var installID; switch (event.name) { case 'INSTALL_EXISTS': installID = this.history.pathParams[0].install_id; if ( !event.exists && (!event.id || event.id === installID) ) { this.history.navigate('/'); } else if (event.exists && installID !== event.id) { this.history.navigate('/install/'+ event.id); } break; case 'LAUNCH_INSTALL_SUCCESS': installID = event.res.id; this.history.navigate('/install/'+ installID); break; } } }); export default MainRouter;
import Router from 'marbles/router'; import WizardComponent from './views/wizard'; import Dispatcher from './dispatcher'; var MainRouter = Router.createClass({ routes: [ { path: '', handler: 'landingPage' }, { path: '/install/:install_id', handler: 'landingPage' } ], willInitialize: function () { Dispatcher.register(this.handleEvent.bind(this)); }, beforeHandler: function (event) { Dispatcher.dispatch({ name: 'LOAD_INSTALL', id: event.params[0].install_id || '' }); }, landingPage: function (params, opts, context) { var props = { dataStore: context.dataStore }; context.render(WizardComponent, props); }, handleEvent: function (event) { var installID; switch (event.name) { case 'INSTALL_EXISTS': installID = this.history.pathParams[0].install_id; if ( !event.exists && (!event.id || event.id === installID) ) { this.history.navigate('/', { replace: true }); } else if (event.exists && installID !== event.id) { this.history.navigate('/install/'+ event.id, { replace: true }); } break; case 'LAUNCH_INSTALL_SUCCESS': installID = event.res.id; this.history.navigate('/install/'+ installID, { replace: true }); break; } } }); export default MainRouter;
Use replaceState for updating the URL
installer: Use replaceState for updating the URL Disables back button. The other option is to allow navigating between steps using the browser's back/forward, but that overlaps with the current behaviour of picking up an existing install process using the base URL. This is a temporary fix and will be revisited soon. refs #1337 Signed-off-by: Jesse Stuart <a5c95b3d7cb4d0ae05a15c79c79ab458dc2c8f9e@jessestuart.ca>
JavaScript
bsd-3-clause
Brandywine2161/flynn,felixrieseberg/flynn,benbjohnson/flynn,whouses/flynn,shads196770/flynn,lmars/flynn,ozum/flynn,rikur/flynn,tonicbupt/flynn,josephglanville/flynn,arekkas/flynn,josephglanville/flynn,ozum/flynn,benbjohnson/flynn,jzila/flynn,rikur/flynn,schatt/flynn,kgrz/flynn,shads196770/flynn,GrimDerp/flynn,justintung/flynn,pkdevbox/flynn,supermario/flynn,Brandywine2161/flynn,schatt/flynn,schatt/flynn,Brandywine2161/flynn,felixrieseberg/flynn,kgrz/flynn,justintung/flynn,whouses/flynn,tonicbupt/flynn,justintung/flynn,jzila/flynn,flynn/flynn,justintung/flynn,justintung/flynn,jzila/flynn,josephglanville/flynn,GrimDerp/flynn,flynn/flynn,shads196770/flynn,rikur/flynn,flynn/flynn,josephglanville/flynn,kgrz/flynn,arekkas/flynn,benbjohnson/flynn,philiplb/flynn,supermario/flynn,josephglanville/flynn,clifff/flynn,tonicbupt/flynn,TribeMedia/flynn,whouses/flynn,supermario/flynn,GrimDerp/flynn,jzila/flynn,philiplb/flynn,schatt/flynn,jzila/flynn,clifff/flynn,benbjohnson/flynn,pkdevbox/flynn,TribeMedia/flynn,pkdevbox/flynn,justintung/flynn,shads196770/flynn,Brandywine2161/flynn,philiplb/flynn,whouses/flynn,ozum/flynn,technosophos/flynn,GrimDerp/flynn,pkdevbox/flynn,whouses/flynn,clifff/flynn,rikur/flynn,GrimDerp/flynn,felixrieseberg/flynn,flynn/flynn,philiplb/flynn,supermario/flynn,arekkas/flynn,technosophos/flynn,clifff/flynn,tonicbupt/flynn,shads196770/flynn,clifff/flynn,lmars/flynn,Brandywine2161/flynn,philiplb/flynn,pkdevbox/flynn,TribeMedia/flynn,kgrz/flynn,benbjohnson/flynn,technosophos/flynn,rikur/flynn,supermario/flynn,tonicbupt/flynn,josephglanville/flynn,flynn/flynn,arekkas/flynn,rikur/flynn,shads196770/flynn,technosophos/flynn,lmars/flynn,ozum/flynn,TribeMedia/flynn,supermario/flynn,jzila/flynn,TribeMedia/flynn,pkdevbox/flynn,whouses/flynn,TribeMedia/flynn,lmars/flynn,benbjohnson/flynn,GrimDerp/flynn,Brandywine2161/flynn,schatt/flynn,clifff/flynn,ozum/flynn,ozum/flynn,kgrz/flynn,felixrieseberg/flynn,felixrieseberg/flynn,technosophos/flynn,lmars/flynn,kgrz/flynn,schatt/flynn,arekkas/flynn
413d998e9a23cf6dea7653a87fef26e52773a622
client/core/collaborators.js
client/core/collaborators.js
define([ 'hr/utils', 'hr/hr', 'collections/users' ], function (_, hr, Users) { // Collection for all current collaborators var collaborators = new Users(); return collaborators; });
define([ 'hr/utils', 'hr/hr', 'collections/users', 'utils/alerts' ], function (_, hr, Users, alerts) { // Collection for all current collaborators var collaborators = new Users(); collaborators.on("add", function(user) { alerts.show(user.get("name")+" just joined the workspace", 5000); }); collaborators.on("remove", function(user) { alerts.show(user.get("name")+" just left the workspace", 5000); }); return collaborators; });
Add alert message when users joined and left the workspace
Add alert message when users joined and left the workspace
JavaScript
apache-2.0
nobutakaoshiro/codebox,CodeboxIDE/codebox,nobutakaoshiro/codebox,Ckai1991/codebox,rodrigues-daniel/codebox,rajthilakmca/codebox,lcamilo15/codebox,code-box/codebox,etopian/codebox,kustomzone/codebox,smallbal/codebox,kustomzone/codebox,quietdog/codebox,ahmadassaf/Codebox,ronoaldo/codebox,rodrigues-daniel/codebox,Ckai1991/codebox,ahmadassaf/Codebox,listepo/codebox,lcamilo15/codebox,ronoaldo/codebox,LogeshEswar/codebox,rajthilakmca/codebox,LogeshEswar/codebox,blubrackets/codebox,fly19890211/codebox,etopian/codebox,blubrackets/codebox,code-box/codebox,listepo/codebox,indykish/codebox,CodeboxIDE/codebox,fly19890211/codebox,indykish/codebox,smallbal/codebox,quietdog/codebox
39a25f48ec2728f756ae65836d51f15ff7c0f866
examples/public/examples.js
examples/public/examples.js
$(function () { (function fixControlsLength () { $('.form-group').each(function (index) { $('.control-label', this) .addClass('col-xs-4').css({'text-align':'right'}) .next().addClass('col-xs-5') .next().addClass('col-xs-3'); }); $('.control-label:contains(upload)') .next().removeClass('col-xs-5').addClass('col-xs-3') .next().removeClass('col-xs-3').addClass('col-xs-5').css({'overflow':'hidden'}); $('.control-label:contains(textarea)') .removeClass('col-xs-4') .next().removeClass('col-xs-5'); }()); (function disableLinks () { $('.navbar-brand, .breadcrumb a, #controls .btn, footer .text-muted').on('click', function (e) { return false; }); }()); (function fixButtons () { $('#controls button').each(function (index) { $(this).attr('style', 'width: auto !important'); }); }()); });
$(function () { (function disableLinks () { $('.navbar-brand, .breadcrumb a, #controls .btn, footer .text-muted').on('click', function (e) { return false; }); }()); if (!(window.location != window.parent.location)) return; (function fixControlsLength () { $('.form-group').each(function (index) { $('.control-label', this) .addClass('col-xs-4').css({'text-align':'right'}) .next().addClass('col-xs-5') .next().addClass('col-xs-3'); }); $('.control-label:contains(upload)') .next().removeClass('col-xs-5').addClass('col-xs-3') .next().removeClass('col-xs-3').addClass('col-xs-5').css({'overflow':'hidden'}); $('.control-label:contains(textarea)') .removeClass('col-xs-4') .next().removeClass('col-xs-5'); }()); (function fixButtons () { $('#controls button').each(function (index) { $(this).attr('style', 'width: auto !important'); }); }()); });
Disable bootstrap responsive only inside an iframe
Disable bootstrap responsive only inside an iframe
JavaScript
mit
simov/express-admin-site
54f3ce25289725244ff7945559223c7d9cd12cca
src/app/lobby/lobby.controller.js
src/app/lobby/lobby.controller.js
class LobbyController { constructor($scope, $log, $location, GameService, SocketService) { 'ngInject'; this.$log = $log; this.$scope = $scope; this.GameService = GameService; this.SocketService = SocketService; this.game_id = GameService.game_id; this.password = GameService.roomName; this.players = GameService.players; this.mobileAddress = 'fpmobile.bitballoon.com'; SocketService.connect().then((result) => { this.$log.log('success'); this.SocketService.extendedHandler = (message) => { if(message.type === 'join_room') { this.players.push({ name: message.name, id: message.id }); $scope.$apply( () =>{ $scope.players = this.players; }); } //TODO: handle player disconnect }; SocketService.createRoom(this.password); }); } isPlayerConnected(number) { return this.players[number] != null; } } export default LobbyController;
class LobbyController { constructor(_, $scope, toastr, $log, $location, GameService, SocketService) { 'ngInject'; this._ = _; this.$log = $log; this.$scope = $scope; this.toastr = toastr; this.GameService = GameService; this.SocketService = SocketService; this.game_id = GameService.game_id; this.password = GameService.roomName; this.players = GameService.players; this.mobileAddress = 'fpmobile.bitballoon.com'; SocketService.connect().then((result) => { this.$log.log('success'); this.SocketService.extendedHandler = (message) => { if (message.type === 'join_room') { this.players.push({ name: message.name, id: message.id }); toastr.success(message.name + ' has connected.'); $scope.$apply(() => { $scope.players = this.players; }); } if (message.type === 'player_disconnect') { const _ = this._; const index = _.chain(this.players) .map((n) => n.id) .indexOf(message.id) .value(); if (index != -1) { toastr.warning(this.players[index].name + ' has disconnected.'); _.remove(this.players, (n) => n.id === message.id); $scope.$apply(() => { $scope.players = this.players; }); } else { this.$log.error('Player with id ' + message.id + ' not found!'); } } }; SocketService.createRoom(this.password); }); } isPlayerConnected(number) { return this.players[number] != null; } } export default LobbyController;
Modify players list when player disconnects
Modify players list when player disconnects
JavaScript
mit
hendryl/Famous-Places-Web,hendryl/Famous-Places-Web
36d6a9c69feb8b13289c8f15ab517a0667b60fdb
addons/storyshots/storyshots-core/src/index.js
addons/storyshots/storyshots-core/src/index.js
import Stories2SnapsConverter from './Stories2SnapsConverter'; import api from './api'; export * from './test-bodies'; export { Stories2SnapsConverter }; export default api;
import Stories2SnapsConverter from './Stories2SnapsConverter'; import api from './api'; import { snapshotWithOptions, multiSnapshotWithOptions, renderOnly, renderWithOptions, shallowSnapshot, snapshot, } from './test-bodies'; export { Stories2SnapsConverter, snapshotWithOptions, multiSnapshotWithOptions, renderOnly, renderWithOptions, shallowSnapshot, snapshot, }; export default api;
Change "export * from x" to manually importing and exporting named exports.
Change "export * from x" to manually importing and exporting named exports.
JavaScript
mit
storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook
118261e590c58a5c69daced92aae03144a98500b
frappe/public/js/frappe/form/controls/html.js
frappe/public/js/frappe/form/controls/html.js
frappe.ui.form.ControlHTML = frappe.ui.form.Control.extend({ make: function() { this._super(); this.disp_area = this.wrapper; }, refresh_input: function() { var content = this.get_content(); if(content) this.$wrapper.html(content); }, get_content: function() { return this.df.options || ""; }, html: function(html) { this.$wrapper.html(html || this.get_content()); }, set_value: function(html) { if(html.appendTo) { // jquery object html.appendTo(this.$wrapper.empty()); } else { // html this.df.options = html; this.html(html); } } });
frappe.ui.form.ControlHTML = frappe.ui.form.Control.extend({ make: function() { this._super(); this.disp_area = this.wrapper; this.frm.$wrapper.on('blur change', () => { setTimeout(() => this.refresh_input(), 500); }); }, refresh_input: function() { var content = this.get_content(); if(content) this.$wrapper.html(content); }, get_content: function() { var content = this.df.options || ""; return frappe.render(content, this); }, html: function(html) { this.$wrapper.html(html || this.get_content()); }, set_value: function(html) { if(html.appendTo) { // jquery object html.appendTo(this.$wrapper.empty()); } else { // html this.df.options = html; this.html(html); } } });
Enable using templates inside ControlHTML
Enable using templates inside ControlHTML This change would enable showing computed data based on other fields in the same doc, without storing the computed data (which avoid unnecessary redundancy).
JavaScript
mit
yashodhank/frappe,manassolanki/frappe,paurosello/frappe,frappe/frappe,neilLasrado/frappe,tmimori/frappe,vjFaLk/frappe,RicardoJohann/frappe,saurabh6790/frappe,ESS-LLP/frappe,mhbu50/frappe,ESS-LLP/frappe,mhbu50/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,mbauskar/frappe,tundebabzy/frappe,yashodhank/frappe,yashodhank/frappe,maxtorete/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,paurosello/frappe,paurosello/frappe,vjFaLk/frappe,maxtorete/frappe,chdecultot/frappe,manassolanki/frappe,vjFaLk/frappe,bohlian/frappe,tundebabzy/frappe,saurabh6790/frappe,frappe/frappe,mbauskar/frappe,bohlian/frappe,RicardoJohann/frappe,maxtorete/frappe,frappe/frappe,neilLasrado/frappe,mbauskar/frappe,StrellaGroup/frappe,mhbu50/frappe,adityahase/frappe,RicardoJohann/frappe,manassolanki/frappe,tmimori/frappe,almeidapaulopt/frappe,bohlian/frappe,tmimori/frappe,adityahase/frappe,saurabh6790/frappe,manassolanki/frappe,vjFaLk/frappe,bohlian/frappe,ESS-LLP/frappe,tmimori/frappe,paurosello/frappe,mbauskar/frappe,chdecultot/frappe,yashodhank/frappe,chdecultot/frappe,RicardoJohann/frappe,ESS-LLP/frappe,adityahase/frappe,neilLasrado/frappe,chdecultot/frappe,maxtorete/frappe,saurabh6790/frappe,tundebabzy/frappe,tundebabzy/frappe,adityahase/frappe,neilLasrado/frappe,StrellaGroup/frappe,mhbu50/frappe
85b2d4790c23204545d0c12d145b6aea1e0f408d
server/app.js
server/app.js
/** * Module dependencies. */ var express = require('express'); var path = require('path'); var api = require('./lib/api'); var app = module.exports = express(); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('change this value to something unique')); app.use(express.cookieSession()); app.use(express.compress()); app.use(api); app.use(express.static(path.join(__dirname, '../build'))); app.use(app.router); if ('development' === app.get('env')) { app.use(express.errorHandler()); }
/** * Module dependencies. */ var express = require('express'); var path = require('path'); var api = require('./lib/api'); var app = module.exports = express(); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('change this value to something unique')); app.use(express.cookieSession()); app.use(express.compress()); app.use(api); app.use(express.static(path.join(__dirname, '../build'))); app.use(app.router); if ('development' === app.get('env')) { app.use(express.errorHandler()); } // catch all which sends all urls to index page, thus starting our app // @note that because Express routes are registered in order, and we already defined our api routes // this catch all will not effect prior routes. app.use(function(req, res, next) { app.get('*', function(req, res, next) { //return res.ok('catch all'); res.redirect('/#' + req.url); }); });
Add a catch-all route to the server, which converts non-hash routes into hashed routes.
Add a catch-all route to the server, which converts non-hash routes into hashed routes.
JavaScript
mit
brettshollenberger/rootstrikers,brettshollenberger/rootstrikers
93664c46cc6d4c98ba1143016df5915d685a1c5a
web_external/views/widgets/DatasetInfoWidget.js
web_external/views/widgets/DatasetInfoWidget.js
import View from '../view'; import template from '../../templates/widgets/datasetInfoWidget.pug'; import '../../stylesheets/widgets/datasetInfoWidget.styl'; /** * This widget is used to diplay minerva metadata for a dataset. */ const DatasetInfoWidget = View.extend({ initialize: function (settings) { this.dataset = settings.dataset; this.normalizeMetaInfo = this.normalizeMetaInfo.bind(this); }, render: function () { var modal = this.$el.html(template(this)) .girderModal(this); modal.trigger($.Event('ready.girder.modal', { relatedTarget: modal })); return this; }, normalizeMetaInfo() { var meta = this.dataset.get('meta').minerva; var name = meta.original_files ? meta.original_files[0].name : meta.geojson_file.name; var output = { Name: name, Source: 'file' }; switch (meta.dataset_type) { case 'geojson': output.Type = 'GeoJSON'; if (meta.postgresGeojson) { output.Source = 'PostgreSQL'; } break; case 'geotiff': output.Type = 'GeoTiff'; break; } return output; } }); export default DatasetInfoWidget;
import View from '../view'; import template from '../../templates/widgets/datasetInfoWidget.pug'; import '../../stylesheets/widgets/datasetInfoWidget.styl'; /** * This widget is used to diplay minerva metadata for a dataset. */ const DatasetInfoWidget = View.extend({ initialize: function (settings) { this.dataset = settings.dataset; this.normalizeMetaInfo = this.normalizeMetaInfo.bind(this); }, render: function () { var modal = this.$el.html(template(this)) .girderModal(this); modal.trigger($.Event('ready.girder.modal', { relatedTarget: modal })); return this; }, normalizeMetaInfo() { var meta = this.dataset.get('meta').minerva; var output = { Name: this.dataset.get('name'), Source: 'file' }; if (meta.original_files && meta.original_files[0] && meta.original_files[0].name) { output['Original name'] = meta.original_files[0].name; } else if (meta.geojson_file && meta.geojson_file.name) { output['Original name'] = meta.geojson_file.name; } switch (meta.dataset_type) { case 'geojson': output.Type = 'GeoJSON'; if (meta.postgresGeojson) { output.Source = 'PostgreSQL'; } break; case 'geotiff': output.Type = 'GeoTiff'; break; } return output; } }); export default DatasetInfoWidget;
Make the query of dataset name more reliable on different kind datasets
Make the query of dataset name more reliable on different kind datasets Some datasets are created at runtime, so it could be missing fields Also prepare for dataset rename feature
JavaScript
apache-2.0
Kitware/minerva,Kitware/minerva,Kitware/minerva
91faa0f9e1e9d211b7be72b254b18578d2bdb3b3
www/timelines.js
www/timelines.js
function load_timelines() { $.getJSON('/time_series.json',function(data) { var options = { xaxis: { mode: "time" }, series: { points: { show: "true" }, lines: { show: "true" } }, grid: { }, yaxis: { min: 29.5, max: 40 } }; $.plot('#psnr_graph',[data[0].sort()],options); options.yaxis.min = 29; options.yaxis.max = 40; $.plot('#psnrhvs_graph',[data[1].sort()],options); options.yaxis.min = 9; options.yaxis.max = 20; $.plot('#ssim_graph',[data[2].sort()],options); options.yaxis.min = 11; options.yaxis.max = 30; $.plot('#fastssim_graph',[data[3].sort()],options); }); }
var wd; function load_timelines() { load_timelines_watermark(); } function load_timelines_watermark() { $.getJSON('/watermark.json', function(data) { wd = data; load_time_series(); } } function load_time_series() { $.getJSON('/time_series.json',function(data) { var options = { xaxis: { mode: "time" }, series: { points: { show: "true" }, lines: { show: "true" } }, grid: { markings: [ { yaxis: { from: wd.x265.psnr, to: wd.x265.psnr}, color: "#ff0000"}, { yaxis: { from: wd.x264.psnr, to: wd.x264.psnr}, color: "#00ff00"} ] }, yaxis: { min: 29.5, max: 40 } }; $.plot('#psnr_graph',[data[0].sort()],options); options.yaxis.min = 29; options.yaxis.max = 40; $.plot('#psnrhvs_graph',[data[1].sort()],options); options.yaxis.min = 9; options.yaxis.max = 20; $.plot('#ssim_graph',[data[2].sort()],options); options.yaxis.min = 11; options.yaxis.max = 30; $.plot('#fastssim_graph',[data[3].sort()],options); }); }
Refactor timeline support to load watermarks from json file
Refactor timeline support to load watermarks from json file
JavaScript
mit
tdaede/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,tdaede/awcy,mdinger/awcy,mdinger/awcy
fe5bd0dedb1d5dba919bfe9f7b9aaa721e1598f9
instance_introspection/static/src/js/tests.js
instance_introspection/static/src/js/tests.js
(function() { 'use strict'; openerp.Tour.register({ id: 'test_instance_introspection', name: 'Complete a basic order trough the Front-End', path: '/instance_introspection', mode: 'test', steps: [ { title: 'Wait for the main screen', waitFor: 'h3:contains("Addons Paths")', element: '.btn-reload', wait: 200, }, { title: 'Load Repositories', waitFor: '#accordion.results', }, ], }); })();
(function() { 'use strict'; openerp.Tour.register({ id: 'test_instance_introspection', name: 'Complete a basic order trough the Front-End', path: '/instance_introspection', mode: 'test', steps: [ { title: 'Wait for the main screen', waitFor: 'h3:contains("Addons Paths"),#accordion.results', element: '.btn-reload', wait: 200, }, { title: 'Load Repositories', waitFor: '#accordion.results', }, ], }); })();
Test expecting results also since the begining
[IMP] Test expecting results also since the begining
JavaScript
agpl-3.0
vauxoo-dev/server-tools,vauxoo-dev/server-tools,vauxoo-dev/server-tools
535e980c271e6e39514857c54189339a2cb7f70d
weckan/static/js/dataset.js
weckan/static/js/dataset.js
/** * Dataset page specific features */ (function($, swig){ "use strict"; var COW_URL = $('link[rel="cow"]').attr('href'), COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking'; $(function() { var name = $('meta[name="dataset-name"]').attr('content'), url = COW_API_URL.replace('{name}', name); // Fetch ranking $.get(url, function(data) { var weight = data.value.weight.toFixed(3), tpl = swig.compile($('#quality-template').text()); $('#infos-list').append(tpl({ weight: weight})); }); }); }(window.jQuery, window.swig));
/** * Dataset page specific features */ (function($, swig){ "use strict"; var QUALITY_PRECISION = 2, COW_URL = $('link[rel="cow"]').attr('href'), COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking'; $(function() { var name = $('meta[name="dataset-name"]').attr('content'), url = COW_API_URL.replace('{name}', name); // Fetch ranking $.get(url, function(data) { var weight = data.value.weight, tpl = swig.compile($('#quality-template').text()); if (weight) { $('#infos-list').append(tpl({ weight: weight.toFixed(QUALITY_PRECISION) })); } }); }); }(window.jQuery, window.swig));
Set quality precision at 2 digits and handle no weight case
Set quality precision at 2 digits and handle no weight case
JavaScript
agpl-3.0
etalab/weckan,etalab/weckan
4b5444a909d064ec2b8fb1e237001152816b3403
imports/api/collections/posts/publications.js
imports/api/collections/posts/publications.js
import { Meteor } from 'meteor/meteor'; import { Posts } from '../'; Meteor.publish('posts', () => Posts.find({}, { limit: 10 }));
import { Meteor } from 'meteor/meteor'; import { Posts, Comments } from '../'; Meteor.publishComposite('posts', (limit = 10) => { return { find() { return Posts.find({}, { limit, sort: { createdAt: -1, }, }); }, children: [ { find(post) { return Comments.find({ postId: post._id, }, { sort: { createdAt: -1, }, limit: 3, }); }, }, ], }; });
Join comments on posts publication
Join comments on posts publication
JavaScript
apache-2.0
evancorl/portfolio,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio,evancorl/portfolio
ae1cbbc68890a64279ba3a17ba61d8b24cdb0d2d
src/components/HomePage.js
src/components/HomePage.js
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Category from "./Category"; import {getCategories} from "../actions/Category"; import {connect} from "react-redux"; export class HomePage extends Component { componentDidMount() { this.props.getCategories(); } render() { let categories = this.props.categories; return ( <div className="container"> {categories && categories.map((category) => { return ( <div> <Category name={category.name}/> <br/> </div> ) }) } </div> ) } } const mapStateToProps = (state, props) => ({ categories: state.category.categories }); const mapDispatchToProps = dispatch => ({ getCategories: () => dispatch(getCategories()) }); HomePage.propTypes = {}; export default connect( mapStateToProps, mapDispatchToProps )(HomePage)
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Category from "./Category"; import {getCategories} from "../actions/Category"; import {connect} from "react-redux"; export class HomePage extends Component { componentDidMount() { this.props.getCategories(); } render() { let categories = this.props.categories; return ( <div className="container"> {categories && categories.map((category, index) => { return ( <div key={index}> <Category name={category.name}/> <br/> </div> ) }) } </div> ) } } const mapStateToProps = (state, props) => ({ categories: state.category.categories }); const mapDispatchToProps = dispatch => ({ getCategories: () => dispatch(getCategories()) }); HomePage.propTypes = {}; export default connect( mapStateToProps, mapDispatchToProps )(HomePage)
Add key iterator for categories map
fix: Add key iterator for categories map
JavaScript
mit
faridsaud/udacity-readable-project,faridsaud/udacity-readable-project
0a6a8623a2ba76e88718fb733b6f87fffca58dda
src/components/HomeView.js
src/components/HomeView.js
import React, { Component } from 'react'; import { Link } from 'react-router'; class HomeView extends Component { render() { return ( <div> <Link to={"v/1"}>Video Link</Link> </div> ); } } export default HomeView;
import React, { Component } from 'react'; import { Link } from 'react-router'; class HomeView extends Component { constructor() { super(); this.state = { videos: ["hello", "world"] }; } render() { return ( <div> {this.state.videos.map((video, index) => ( <Link to={"v/1"} key={index}>Video Link</Link> ))} </div> ); } } export default HomeView;
Work on Home view links
Work on Home view links
JavaScript
mit
mg4tv/mg4tv-web,mg4tv/mg4tv-web
fba75bcb6bd371d42a22bbe09a34c11631233b21
modules/roles.js
modules/roles.js
"use strict"; /*Their structure is different because of how the commands to use them are invoked.*/ module.exports = { "elevated": { "80773161284538368": "Admins", "80773196516700160": "Mods" }, "user_assignable": { "Coders" : "229748381159915520", "Techies": "229748333114163200", "Players": "222989842739363840", "Destiny": "368565663343706123" } };
"use strict"; /*Their structure is different because of how the commands to use them are invoked.*/ module.exports = { "elevated": { "80773161284538368": "Admins", "80773196516700160": "Mods" }, "user_assignable": { "Coders" : "229748381159915520", "Techies": "229748333114163200", "Players": "222989842739363840", "Destiny": "368565663343706123", "WoW": "371081851240185857" } };
Add support for WoW assigning guild
Add support for WoW assigning guild
JavaScript
mit
izy521/Sera-PCMR
47034634668b0baea5cb0b13a88d2172e7e5a8ac
public/main.js
public/main.js
define(['jquery', 'underscore', 'pullManager', 'appearanceManager', 'module', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager'], function($, _, pullManager, appearanceManager, module, PullFilter, ElementFilter, Column, ConnectionManager) { var spec = View; var globalPullFilter = new PullFilter(spec); var globalElementFilter = new ElementFilter(spec); _.each(spec.columns, function(columnSpec) { var pullFilter = new PullFilter(columnSpec); var elementFilter = new ElementFilter(columnSpec, globalElementFilter); var col = new Column(elementFilter, columnSpec); globalPullFilter.onUpdate(pullFilter.update); pullFilter.onUpdate(col.update); }); pullManager.onUpdate(globalPullFilter.update); //$(appearanceManager.addCollapseSwaps); globalPullFilter.update(pullManager.getPulls()); });
define(['jquery', 'underscore', 'pullManager', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager', 'bootstrap'], // Note that not all of the required items above are represented in the function argument list. Some just need to be loaded, but that's all. function($, _, pullManager, PullFilter, ElementFilter, Column) { var spec = View; var globalPullFilter = new PullFilter(spec); var globalElementFilter = new ElementFilter(spec); _.each(spec.columns, function(columnSpec) { var pullFilter = new PullFilter(columnSpec); var elementFilter = new ElementFilter(columnSpec, globalElementFilter); var col = new Column(elementFilter, columnSpec); globalPullFilter.onUpdate(pullFilter.update); pullFilter.onUpdate(col.update); }); pullManager.onUpdate(globalPullFilter.update); globalPullFilter.update(pullManager.getPulls()); });
Change requirements to reflect reality
Change requirements to reflect reality * Add `bootstrap` so the scripts get loaded * Remove `module` and `appearanceManager` because they aren't used any more * Stop providing variables in function with modules that are only loaded for side effects
JavaScript
mit
iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher
0fdd418274a18fa954510053fd34c4730d2c7267
lib/preload/redir-stdout.js
lib/preload/redir-stdout.js
'use strict' const fs = require('fs') process.stdout.write = ((write) => (chunk, encoding, cb) => { if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { throw new TypeError( 'Invalid data, chunk must be a string or buffer, not ' + typeof chunk); } if (typeof encoding === 'function') { cb = encoding } fs.writeSync(3, chunk) if (typeof cb === 'function') cb() return true })(process.stdout.write.bind(process.stdout))
'use strict' const net = require('net') const socket = new net.Socket({ fd: 3, readable: false, writable: true }) Object.defineProperty(process, 'stdout', { configurable: true, enumerable: true, get: () => socket })
Change process.stdout switcharoo to a full net.Socket instance
Change process.stdout switcharoo to a full net.Socket instance No matter how you write to stdout, this should catch it! The `defineProperty` call uses the same options as the default `process.stdout`.
JavaScript
mit
davidmarkclements/0x
a4f4dd98a2b78ed66af02761d33ebbc8dd5e516d
src/shared/components/libs/ExperimentImages.js
src/shared/components/libs/ExperimentImages.js
import React from "react"; class ExperimentImages extends React.Component { constructor() { super(); } render() { let imageDiv = this.props.images.map(url => { return (<a href={url} target="_blank"><img src={url} alt="experiment image"/></a>) }); return ( <div className="images"> {imageDiv} </div> ); } } module.exports = ExperimentImages;
import React from "react"; class ExperimentImages extends React.Component { constructor() { super(); } render() { let imageDiv = null; if(this.props.images) { imageDiv = this.props.images.map(url => { return (<a href={url} target="_blank"><img src={url} alt="experiment image"/></a>) }); } return ( <div className="images"> {imageDiv} </div> ); } } module.exports = ExperimentImages;
Fix undefined this.props.images. Change between experiments will be smoother
Fix undefined this.props.images. Change between experiments will be smoother
JavaScript
mit
olavvatne/ml-monitor
763e473a5fc126fdbb5d0cf666683c8d9d869e7c
lib/model/classes/StyleSheetExtension.js
lib/model/classes/StyleSheetExtension.js
var props = require("../properties/all.js"); var BaseObj = require("../BaseObj"); var obj = BaseObj.create("XWiki.StyleSheetExtension"); obj.addProp("name", props.XString.create({ "prettyName": "Name", "size": "30" })); obj.addProp("code", props.TextArea.create({ "prettyName": "Code" })); obj.addProp("use", props.StaticList.create({ "prettyName": "Use this extension", "values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki" })); obj.addProp("parse", props.XBoolean.create({ "prettyName": "Parse content" })); obj.addProp("cache", props.StaticList.create({ "prettyName": "Caching policy", "values": "long|short|default|forbid" })); module.exports.create = function () { return obj.instance(); };
var props = require("../properties/all.js"); var BaseObj = require("../BaseObj"); var obj = BaseObj.create("XWiki.StyleSheetExtension"); obj.addProp("cache", props.StaticList.create({ "prettyName": "Caching policy", "values": "long|short|default|forbid" })); obj.addProp("code", props.TextArea.create({ "prettyName": "Code" })); obj.addProp("name", props.XString.create({ "prettyName": "Name", "size": "30" })); obj.addProp("parse", props.XBoolean.create({ "prettyName": "Parse content" })); obj.addProp("use", props.StaticList.create({ "prettyName": "Use this extension", "values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki" })); module.exports.create = function () { return obj.instance(); };
Reorder property to keep XWiki order
Reorder property to keep XWiki order
JavaScript
agpl-3.0
xwiki-contrib/node-xwikimodel
32a7a99b61968f88f1d62c98275b755f3990d1a9
src/styles/Images/assets/index.js
src/styles/Images/assets/index.js
export default { BackgroundsPlus: require("./backgrounds-plus.jpg") };
import React from "react"; import Image from "../../../components/Image" export const BackgroundsPlus = p => <Image {...p} src={require("./backgrounds-plus.jpg")} />
Deploy to GitHub pages
Deploy to GitHub pages [ci skip]
JavaScript
mit
tutti-ch/react-styleguide,tutti-ch/react-styleguide
b8b145fee10b51f99deefc86001fa745cc2e96da
test/resourceful-webhooks-test.js
test/resourceful-webhooks-test.js
var http = require('http'), assert = require('assert'), cb = require('assert-called'), resourceful = require('resourceful'); require('../'); var PORT = 8123, gotCallbacks = 0; function maybeEnd() { if (++gotCallbacks === 2) { server.close(); } } var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { data = JSON.parse(data); if (data.hello === 'world') { res.writeHead(200); res.end(); } else if (data.hello === 'universe') { res.writeHead(400); res.end(); } else { assert(false); } maybeEnd(); }); }).listen(PORT); var Resource = resourceful.define('Resource', function () { this.webhooks({ url: 'http://127.0.0.1:' + PORT.toString(), events: ['create'] }); }); Resource.create({ id: 'resource/good', hello: 'world' }, cb(function goodCb(err) { assert(!err); })); Resource.create({ id: 'resource/bad', hello: 'universe' }, cb(function badCb(err) { assert(err); }));
var http = require('http'), assert = require('assert'), cb = require('assert-called'), resourceful = require('resourceful'); require('../'); var PORT = 8123, gotCallbacks = 0; function maybeEnd() { if (++gotCallbacks === 2) { server.close(); } } var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); assert.equal(req.headers['content-type'], 'application/json'); var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { data = JSON.parse(data); if (data.hello === 'world') { res.writeHead(200); res.end(); } else if (data.hello === 'universe') { res.writeHead(400); res.end(); } else { assert(false); } maybeEnd(); }); }).listen(PORT); var Resource = resourceful.define('Resource', function () { this.webhooks({ url: 'http://127.0.0.1:' + PORT.toString(), events: ['create'] }); }); Resource.create({ id: 'resource/good', hello: 'world' }, cb(function goodCb(err) { assert(!err); })); Resource.create({ id: 'resource/bad', hello: 'universe' }, cb(function badCb(err) { assert(err); }));
Add a failing test for `content-type` header
[test] Add a failing test for `content-type` header
JavaScript
mit
mmalecki/resourceful-webhooks,mmalecki/resourceful-webhooks
b8424424ae7e46f2b0fbc36d16a8a1d41f6e66c5
src/scripts/scanRepliesAndNotify.js
src/scripts/scanRepliesAndNotify.js
import lib from './lib'; import redis from 'src/lib/redisClient'; import addTime from 'date-fns/add'; import Client from 'src/database/mongoClient'; export default async function scanRepliesAndNotify() { const timeOffset = JSON.parse(process.env.REVIEW_REPLY_BUFFER) || {}; const lastScannedAt = (await redis.get('lastScannedAt')) || addTime(new Date(), { days: -90 }).toISOString(); console.log('[notify] lastScannedAt:' + lastScannedAt); const nowWithOffset = addTime(new Date(), timeOffset).toISOString(); const notificationList = await lib.getNotificationList( lastScannedAt, nowWithOffset ); await lib.sendNotification(notificationList); await redis.set('lastScannedAt', nowWithOffset); // disconnect redis and mongodb await redis.quit(); await (await Client.getInstance()).close(); } if (require.main === module) { scanRepliesAndNotify(); }
import lib from './lib'; import redis from 'src/lib/redisClient'; import rollbar from 'src/lib/rollbar'; import addTime from 'date-fns/add'; import Client from 'src/database/mongoClient'; export default async function scanRepliesAndNotify() { const timeOffset = JSON.parse(process.env.REVIEW_REPLY_BUFFER) || {}; const lastScannedAt = (await redis.get('lastScannedAt')) || addTime(new Date(), { days: -90 }).toISOString(); console.log('[notify] lastScannedAt:' + lastScannedAt); const nowWithOffset = addTime(new Date(), timeOffset).toISOString(); const notificationList = await lib.getNotificationList( lastScannedAt, nowWithOffset ); await lib.sendNotification(notificationList); await redis.set('lastScannedAt', nowWithOffset); // disconnect redis and mongodb await redis.quit(); await (await Client.getInstance()).close(); } if (require.main === module) { scanRepliesAndNotify().catch(e => { console.error(e); rollbar.error(e); process.exit(1); }); }
Add error handler and send error to rollbar
Add error handler and send error to rollbar
JavaScript
mit
cofacts/rumors-line-bot,cofacts/rumors-line-bot,cofacts/rumors-line-bot
660dc74cef1a6a3f7da701b57e9f3f71ccd6bb57
app/js/arethusa.core/directives/sentence_list.js
app/js/arethusa.core/directives/sentence_list.js
"use strict"; angular.module('arethusa.core').directive('sentenceList', [ '$compile', 'navigator', function($compile, navigator) { return { restrict: 'A', scope: true, link: function(scope, element, attrs) { scope.n = navigator; function createList() { // We want this to load only once, and only if // a user requests it! if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ <div id="canvas" class="row panel full-height" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\ sentence="s"\ ng-repeat="s in n.sentences">\ </li>\ </ul>\ </div>\ '; navigator.list().append($compile(template)(scope)); navigator.hasList = true; } } scope.$on('viewModeSwitched', createList); element.bind('click', function() { createList(); scope.$apply(function() { navigator.switchView(); }); }); } }; } ]);
"use strict"; angular.module('arethusa.core').directive('sentenceList', [ '$compile', 'navigator', function($compile, navigator) { return { restrict: 'A', scope: true, link: function(scope, element, attrs) { scope.n = navigator; function createList() { // We want this to load only once, and only if // a user requests it! if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ <div id="canvas" class="row panel full-height scrollable" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\ sentence="s"\ ng-repeat="s in n.sentences">\ </li>\ </ul>\ </div>\ '; navigator.list().append($compile(template)(scope)); navigator.hasList = true; } } scope.$on('viewModeSwitched', createList); element.bind('click', function() { createList(); scope.$apply(function() { navigator.switchView(); }); }); } }; } ]);
Make sentenceList scrollable at all times
Make sentenceList scrollable at all times
JavaScript
mit
alpheios-project/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa
dddad05c90b4772a3f4b8c73b5223e044aa65872
app/views/emailConfirmation/emailConfirmation.js
app/views/emailConfirmation/emailConfirmation.js
angular.module("ccj16reg.view.emailConfirmation", ["ngRoute", "ngMaterial", "ccj16reg.registration"]) .config(function($routeProvider) { "use strict"; $routeProvider.when("/confirmpreregistration", { templateUrl: "views/emailConfirmation/emailConfirmation.html", controller: "EmailConfirmationCtrl", }); }) .controller("EmailConfirmationCtrl", function($scope, $location, $mdDialog, $routeParams, Registration) { "use strict"; $scope.verifying = true; $scope.error = false; $scope.email = $routeParams.email; var token = $routeParams.token; if (!angular.isDefined($scope.email) || !angular.isDefined(token)) { $location.path("/register") } else { Registration.confirmEmail($scope.email, token).then(function() { $scope.verifying = false; }, function(resp) { $scope.verifying = false; $scope.error = resp.data.trim(); }); } });
angular.module("ccj16reg.view.emailConfirmation", ["ngRoute", "ngMaterial", "ccj16reg.registration"]) .config(function($routeProvider) { "use strict"; $routeProvider.when("/confirmpreregistration", { templateUrl: "views/emailConfirmation/emailConfirmation.html", controller: "EmailConfirmationCtrl", }); }) .controller("EmailConfirmationCtrl", function($scope, $location, $routeParams, Registration) { "use strict"; $scope.verifying = true; $scope.error = false; $scope.email = $routeParams.email; var token = $routeParams.token; if (!angular.isDefined($scope.email) || !angular.isDefined(token)) { $location.path("/register") } else { Registration.confirmEmail($scope.email, token).then(function() { $scope.verifying = false; }, function(resp) { $scope.verifying = false; $scope.error = resp.data.trim(); }); } });
Remove unnecessary $mdDialog from the EmailConfirmationCtrl.
Remove unnecessary $mdDialog from the EmailConfirmationCtrl.
JavaScript
agpl-3.0
CCJ16/registration,CCJ16/registration,CCJ16/registration
a0ec4aae2d9b4e07f281d49235d11543ffb9066f
cli.js
cli.js
#! /usr/bin/env node const args = process.argv const command = args[2] const config = { app_dir: process.env.HOME + '/.stay' } if (!command) { require('./cli/help')(args, config) process.exit(1) } try { require('./cli/' + command)(args, config) } catch (err) { console.log(err) if (err.code === 'MODULE_NOT_FOUND') { console.log('Command "' + command + '" not found') } else { throw new Error(err) } } const mkdirp = require('mkdirp') mkdirp.sync(config.app_dir)
#! /usr/bin/env node const fs = require('fs') const args = process.argv const command = args[2] const config = { app_dir: process.env.HOME + '/.stay' } try { fs.accessSync(config.app_dir, fs.F_OK) } catch (e) { const mkdirp = require('mkdirp') mkdirp.sync(config.app_dir) } if (!command) { require('./cli/help')(args, config) process.exit(1) } try { require('./cli/' + command)(args, config) } catch (Err) { if (Err.code === 'MODULE_NOT_FOUND') { console.log('Command "' + command + '" not found') } else { throw Err } }
Initialize config only if not exists
Initialize config only if not exists
JavaScript
mit
EverythingStays/stay-cli,EverythingStays/stay-cli
b9835c9a26829fd36917d16a1a6813f9d54e9d3f
client/app/scripts/services/googleMapsService.js
client/app/scripts/services/googleMapsService.js
angular .module('app') .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { /* // Load the Google Maps scripts Asynchronously (function(d){ var js, id = 'google-maps', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"; ref.parentNode.insertBefore(js, ref); }(document)); */ var methods = {}; methods.geo = function(address, type) { //var deferred = $q.defer(); var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results[0]); geoData.lat = results[0].geometry.location.mb; // mb geoData.lng = results[0].geometry.location.nb; // nb // @todo why is this the new format? // did things change on the Google API side? if (!geoData.lat || !geoData.lng) { geoData.lat = results[0].geometry.location.ob; // mb geoData.lng = results[0].geometry.location.pb; // nb } if (!geoData.lat || !geoData.lng) { $rootScope.$broadcast('event:geo-location-failure'); } else { $rootScope.$broadcast('event:geo-location-success', geoData, type); } } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); //alert('Geocode was not successful for the following reason: ' + status); } }; geocoder.geocode({ 'address': address }, handleResult); //return deferred.promise; }; return methods; } ]);
angular .module('app') .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { var methods = {}; methods.geo = function(address, type) { var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var location = results[0].geometry.location; geoData.lng = location.lng(); geoData.lat = location.lat(); $rootScope.$broadcast('event:geo-location-success', geoData, type); } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); //alert('Geocode was not successful for the following reason: ' + status); } }; geocoder.geocode({ 'address': address }, handleResult); }; return methods; } ]);
Make the digestion of the google geo result standardized
Make the digestion of the google geo result standardized
JavaScript
mit
brettshollenberger/mrl001,brettshollenberger/mrl001
2d3954d279f686187369dfeb673f49f6dd050988
lib/server/server_router.js
lib/server/server_router.js
var connect = Npm.require('connect'); var Fiber = Npm.require('fibers'); var root = global; var connectHandlers , connect; if (typeof __meteor_bootstrap__.app !== 'undefined') { connectHandlers = __meteor_bootstrap__.app; } else { connectHandlers = WebApp.connectHandlers; } ServerRouter = RouterUtils.extend(IronRouter, { constructor: function () { var self = this; ServerRouter.__super__.constructor.apply(this, arguments); this.start(); }, onRun: function (controller, context, options) { var response = context.options.response; try { this.runController(controller, context); } finally { response.end(); } }, start: function () { connectHandlers .use(connect.query()) .use(connect.bodyParser()) .use(_.bind(this.onRequest, this)); }, onRequest: function (req, res, next) { var self = this; Fiber(function () { self.dispatch(req.url, { request: req, response: res, next: next }); }).run(); }, stop: function () { }, onUnhandled: function (path, options) { options.next(); }, onRouteNotFound: function (path, options) { options.next(); } }); Router = new ServerRouter;
var connect = Npm.require('connect'); var Fiber = Npm.require('fibers'); var root = global; var connectHandlers , connect; if (typeof __meteor_bootstrap__.app !== 'undefined') { connectHandlers = __meteor_bootstrap__.app; } else { connectHandlers = WebApp.connectHandlers; } ServerRouter = RouterUtils.extend(IronRouter, { constructor: function () { var self = this; ServerRouter.__super__.constructor.apply(this, arguments); Meteor.startup(function () { setTimeout(function () { if (self.options.autoStart !== false) self.start(); }); }); }, onRun: function (controller, context, options) { var response = context.options.response; try { this.runController(controller, context); } finally { response.end(); } }, start: function () { connectHandlers .use(connect.query()) .use(connect.bodyParser()) .use(_.bind(this.onRequest, this)); }, onRequest: function (req, res, next) { var self = this; Fiber(function () { self.dispatch(req.url, { request: req, response: res, next: next }); }).run(); }, stop: function () { }, onUnhandled: function (path, options) { options.next(); }, onRouteNotFound: function (path, options) { options.next(); } }); Router = new ServerRouter;
Allow apps to kill the server router.
Allow apps to kill the server router.
JavaScript
mit
Aaron1992/iron-router,Sombressoul/iron-router,leoetlino/iron-router,abhiaiyer91/iron-router,Aaron1992/iron-router,assets1975/iron-router,TechplexEngineer/iron-router,Hyparman/iron-router,jg3526/iron-router,tianzhihen/iron-router,jg3526/iron-router,firdausramlan/iron-router,iron-meteor/iron-router,DanielDornhardt/iron-router-2,snamoah/iron-router,ecuanaso/iron-router,DanielDornhardt/iron-router-2,snamoah/iron-router,iron-meteor/iron-router,firdausramlan/iron-router,sean-stanley/iron-router,ecuanaso/iron-router,TechplexEngineer/iron-router,sean-stanley/iron-router,Hyparman/iron-router,tianzhihen/iron-router,abhiaiyer91/iron-router,appoets/iron-router,assets1975/iron-router,appoets/iron-router,Sombressoul/iron-router
d58e398584d35be2ff852d241dbdd0af439f5716
packages/truffle-core/index.js
packages/truffle-core/index.js
var pkg = require("./package.json"); module.exports = { build: require("./lib/build"), create: require("./lib/create"), compiler: require("truffle-compile"), config: require("./lib/config"), console: require("./lib/repl"), contracts: require("./lib/contracts"), require: require("truffle-require"), init: require("./lib/init"), migrate: require("truffle-migrate"), package: require("./lib/package"), serve: require("./lib/serve"), sources: require("truffle-contract-sources"), test: require("./lib/test"), version: pkg.version };
var pkg = require("./package.json"); module.exports = { build: require("./lib/build"), create: require("./lib/create"), config: require("./lib/config"), console: require("./lib/repl"), contracts: require("./lib/contracts"), init: require("./lib/init"), package: require("./lib/package"), serve: require("./lib/serve"), test: require("./lib/test"), version: pkg.version };
Remove references to items that have been pulled out into their own modules.
Remove references to items that have been pulled out into their own modules.
JavaScript
mit
ConsenSys/truffle
326466c2a866cd27749d6d5561f23b674840fd67
packages/jest-environment-enzyme/src/setup.js
packages/jest-environment-enzyme/src/setup.js
/* eslint-disable global-require */ export const exposeGlobals = () => { let dep; switch (global.enzymedepDescriptor) { case 'react13': dep = 'enzyme-adapter-react-13'; break; case 'react14': dep = 'enzyme-adapter-react-14'; break; case 'react15': dep = 'enzyme-adapter-react-15'; break; case 'react15.4': dep = 'enzyme-adapter-react-15.4'; break; case 'react16': default: dep = 'enzyme-adapter-react-16'; } let Adapter; try { Adapter = require(dep); } catch (e) { console.error( ` Requiring the proper enzyme-adapter during jest-enzyme setup failed. This most likely happens when your application does not properly list the adapter in your devDependencies. Run this line to add the correct adapter: > yarn add --dev ${dep} or with npm > npm i --save-dev ${dep} ` ); return; } const { configure, mount, render, shallow } = require('enzyme'); // Setup Enzyme Adapter configure({ adapter: new Adapter() }); global.shallow = shallow; global.mount = mount; global.render = render; global.React = require('react'); };
/* eslint-disable global-require */ // eslint-disable-next-line import/prefer-default-export export const exposeGlobals = () => { let dep; switch (global.enzymeAdapterDescriptor) { case 'react13': dep = 'enzyme-adapter-react-13'; break; case 'react14': dep = 'enzyme-adapter-react-14'; break; case 'react15': dep = 'enzyme-adapter-react-15'; break; case 'react15.4': dep = 'enzyme-adapter-react-15.4'; break; case 'react16': default: dep = 'enzyme-adapter-react-16'; } let Adapter; try { // eslint-disable-next-line import/no-dynamic-require Adapter = require(dep); } catch (e) { // eslint-disable-next-line no-console console.error( ` Requiring the proper enzyme-adapter during jest-enzyme setup failed. This most likely happens when your application does not properly list the adapter in your devDependencies. Run this line to add the correct adapter: > yarn add --dev ${dep} or with npm > npm i --save-dev ${dep} ` ); return; } const { configure, mount, render, shallow } = require('enzyme'); // Setup Enzyme Adapter configure({ adapter: new Adapter() }); global.shallow = shallow; global.mount = mount; global.render = render; global.React = require('react'); };
Use correct global when resolving enzymeAdapter
fix: Use correct global when resolving enzymeAdapter
JavaScript
mit
blainekasten/enzyme-matchers
7d8efe71af7abf4bc21f400fd06bc3f2247be4c1
centreon-frontend/centreon-ui/src/Title/index.js
centreon-frontend/centreon-ui/src/Title/index.js
import React from "react"; import classnames from 'classnames'; import styles from './custom-title.scss'; const Title = ({ icon, label, titleColor, customTitleStyles, onClick, style, labelStyle, children }) => ( <div className={classnames(styles["custom-title"], customTitleStyles ? styles["custom-title-styles"] : '')} onClick={onClick} style={style} > {icon ? ( <span className={classnames(styles["custom-title-icon"], {[styles[`custom-title-icon-${icon}`]]: true})}/> ) : null} <div className={styles["custom-title-label-container"]}> <span className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])} style={labelStyle} > {label} </span> {children} </div> </div> ); export default Title;
import React from "react"; import classnames from 'classnames'; import styles from './custom-title.scss'; const Title = ({ icon, label, titleColor, customTitleStyles, onClick, style, labelStyle, children }) => ( <div className={classnames(styles["custom-title"], customTitleStyles ? styles["custom-title-styles"] : '')} onClick={onClick} style={style} > {icon ? ( <span className={classnames(styles["custom-title-icon"], {[styles[`custom-title-icon-${icon}`]]: true})}/> ) : null} <div className={styles["custom-title-label-container"]}> <span className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])} style={labelStyle} title={label} > {label} </span> {children} </div> </div> ); export default Title;
Add label to the title component.
fix(extensions): Add label to the title component.
JavaScript
apache-2.0
centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon
776ee9c3d3dd199f5c3ef746cf948bd7c06e162b
test-projects/multi-page-test-project/gulpfile.js
test-projects/multi-page-test-project/gulpfile.js
var gulp = require('gulp'); var defs = [ { title: 'Test Index Title', path: '', description: 'Test index description', twitterImage: '20euro.png', openGraphImage: '50euro.png', schemaImage: '100euro.png' }, { path: '/subpage', title: 'Test Subpage Title', description: 'Test subpage description', twitterImage: '100euro.png', openGraphImage: '50euro.png', schemaImage: '20euro.png' } ]; var opts = { publishFromFolder: 'dist', assetContext: 'test-path/', pageDefs: defs, embedCodes: false, iframeResize: false, entryPoint: path.resolve('src/js/entry-point.jsx'), } var builder = require('../../index.js'); // lucify-component-builder builder(gulp, opts);
var gulp = require('gulp'); var path = require('path'); var defs = [ { title: 'Test Index Title', path: '', description: 'Test index description', twitterImage: '20euro.png', openGraphImage: '50euro.png', schemaImage: '100euro.png' }, { path: '/subpage', title: 'Test Subpage Title', description: 'Test subpage description', twitterImage: '100euro.png', openGraphImage: '50euro.png', schemaImage: '20euro.png' } ]; var opts = { publishFromFolder: 'dist', assetContext: 'test-path/', pageDefs: defs, embedCodes: false, iframeResize: false, entryPoint: path.resolve('src/js/entry-point.jsx'), } var builder = require('../../index.js'); // lucify-component-builder builder(gulp, opts);
Add missing require to test project
Add missing require to test project
JavaScript
mit
lucified/lucify-component-builder,lucified/lucify-component-builder,lucified/lucify-component-builder
d9e92fb56f73f8415f4ca9ed791a27e511faee36
root/include/news_look_up.js
root/include/news_look_up.js
function yql_lookup(query, cb_function) { var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true'; //alert(url); $.getJSON(url, cb_function); } function look_up_news() { var feed_url = 'http://mediacloud.org/blog/feed/'; //alert(google_url); yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) { var results = response.query.results; var news_items = $('#news_items'); //console.log(results); news_items.children().remove(); news_items.html(''); $.each(results.item, function (index, element) { var title = element.title; var link = element.link; news_items.append($('<a/>', { 'href': link }).text(title)).append('<br/>'); }); }); }
function yql_lookup(query, cb_function) { var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true'; //alert(url); $.getJSON(url, cb_function); } function look_up_news() { // TEMPORARY HACK //mediacloud.org is password protected so we can't pull from it directly // instead we pull from 'https://blogs.law.harvard.edu/mediacloud2/feed/' and dynamically rewrite the URLs to point to mediacloud.org/blog; var feed_url = 'https://blogs.law.harvard.edu/mediacloud2/feed/'; //alert(google_url); yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) { var results = response.query.results; var news_items = $('#news_items'); //console.log(results); news_items.children().remove(); news_items.html(''); $.each(results.item, function (index, element) { var title = element.title; var link = element.link; link = link.replace('https://blogs.law.harvard.edu/mediacloud2/', 'http://www.mediacloud.org/blog/'); news_items.append($('<a/>', { 'href': link }).text(title)).append('<br/>'); }); }); }
Add work around for the mediacloud.org/blog page being password protected so we can still display the news dynamically on the front page.
Add work around for the mediacloud.org/blog page being password protected so we can still display the news dynamically on the front page.
JavaScript
agpl-3.0
berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud
f6259eb662610e8d140028661d41e223d619293d
frontend/src/SubmitButton.js
frontend/src/SubmitButton.js
import React, { Component } from "react"; import styled from "styled-components"; class SubmitButton extends Component { render() { const { isShowingPositive, onNegativeClick, onPositiveClick, disabled, positiveText, negativeText } = this.props; return ( <StyledSubmitButton disabled={disabled} type="button" value={isShowingPositive ? positiveText : negativeText} onClick={isShowingPositive ? onPositiveClick : onNegativeClick} /> ); } } export const StyledSubmitButton = styled.input` background-color: #00a8e2; transition: background-color 0.25s ease-out, color 0.25s ease-out; color: #fff; border: none; outline: none; padding: 15px 45px; font-size: 1.1em; :hover { cursor: pointer; background-color: #0090c2; } :active { background-color: #006b8f; } :disabled { background-color: #c4c4c4; } `; export default SubmitButton;
import React, { Component } from "react"; import styled from "styled-components"; class SubmitButton extends Component { render() { const { isShowingPositive, onNegativeClick, onPositiveClick, disabled, positiveText, negativeText } = this.props; return ( <StyledSubmitButton disabled={disabled} type="button" value={isShowingPositive ? positiveText : negativeText} onClick={isShowingPositive ? onPositiveClick : onNegativeClick} /> ); } } export const StyledSubmitButton = styled.input` -webkit-appearance: none; background-color: #00a8e2; transition: background-color 0.25s ease-out, color 0.25s ease-out; color: #fff; border: none; outline: none; padding: 15px 45px; font-size: 1.1em; :hover { cursor: pointer; background-color: #0090c2; } :active { background-color: #006b8f; } :disabled { background-color: #c4c4c4; } `; export default SubmitButton;
Set webkit-appearance to none on submit button.
Set webkit-appearance to none on submit button.
JavaScript
mit
Tejpbit/talarlista,Tejpbit/talarlista,Tejpbit/talarlista
6fec68f130beffcc842ad79efa94f85eba1009fc
schema/groupofuniquenames.js
schema/groupofuniquenames.js
// Copyright 2012 Joyent, Inc. All rights reserved. var util = require('util'); var ldap = require('ldapjs'); var Validator = require('../lib/schema/validator'); ///--- Globals var ConstraintViolationError = ldap.ConstraintViolationError; ///--- API function GroupOfUniqueNames() { Validator.call(this, { name: 'groupofuniquenames', required: { uniquemember: 1000000 }, optional: { description: 1 }, strict: true }); } util.inherits(GroupOfUniqueNames, Validator); GroupOfUniqueNames.prototype.validate = function validate(entry, callback) { var members = entry.attributes.uniquemember; members.sort(); for (var i = 0; i < members.length; i++) { if (members.indexOf(members[i], i + 1) !== -1) { return callback(new ConstraintViolationError(members[i] + ' is not unique')); } } return callback(); }; ///--- Exports module.exports = { createInstance: function createInstance() { return new GroupOfUniqueNames(); } };
// Copyright 2013 Joyent, Inc. All rights reserved. var util = require('util'); var ldap = require('ldapjs'); var Validator = require('../lib/schema/validator'); ///--- Globals var ConstraintViolationError = ldap.ConstraintViolationError; ///--- API function GroupOfUniqueNames() { Validator.call(this, { name: 'groupofuniquenames', optional: { uniquemember: 1000000, description: 1 }, strict: true }); } util.inherits(GroupOfUniqueNames, Validator); GroupOfUniqueNames.prototype.validate = function validate(entry, callback) { var members = entry.attributes.uniquemember || []; members.sort(); for (var i = 0; i < members.length; i++) { if (members.indexOf(members[i], i + 1) !== -1) { return callback(new ConstraintViolationError(members[i] + ' is not unique')); } } return callback(); }; ///--- Exports module.exports = { createInstance: function createInstance() { return new GroupOfUniqueNames(); } };
Allow creation of empty user groups
CAPI-219: Allow creation of empty user groups
JavaScript
mpl-2.0
joyent/sdc-ufds,arekinath/sdc-ufds,arekinath/sdc-ufds,joyent/sdc-ufds
df2cf92d8667a3a598aecb37c86c45c82804d089
app/assets/javascripts/active_admin_pro/components/link.js
app/assets/javascripts/active_admin_pro/components/link.js
App.ready(function() { "use strict"; var body = $('body'); var links = $('a:not([data-method="delete"]):not(.has_many_add):not(.dropdown_menu_button):not([target="_blank"])'); // Add active class on click to style while loading via turbolinks // and add loading class to the body element. links.click(function() { body.addClass('loading'); $(this).addClass('active'); }); // Remove loading and active classes on page load body.removeClass('loading'); links.removeClass('active'); });
App.ready(function() { "use strict"; var body = $('body'); var links = $('a:not([data-method="delete"]):not(.has_many_add):not(.dropdown_menu_button):not([target="_blank"])'); // Add active class on click to style while loading via turbolinks // and add loading class to the body element. links.click(function() { body.addClass('loading'); $(this).addClass('active'); }); // Remove loading and active classes on page load body.removeClass('loading'); links.removeClass('active'); // We also need to make sure to remove the loading classes when the // page is restored by Turbolinks when using the back button document.addEventListener('page:restore', function() { body.removeClass('loading'); links.removeClass('active'); }); });
Fix issue with back button and loading indicators
Fix issue with back button and loading indicators
JavaScript
mit
codelation/active_admin_pro,codelation/active_admin_pro,codelation/activeadmin_pro,codelation/activeadmin_pro
07688d877058ed228ffb776b927138fc2ad1ed8d
addon/index.js
addon/index.js
import Ember from 'ember'; const { RSVP } = Ember; function preloadRecord(record, toPreload) { return preloadAll([record], toPreload).then(() => { return record; }); } function preloadAll(records, toPreload) { switch(Ember.typeOf(toPreload)) { case 'object': const properties = Object.keys(toPreload); return RSVP.all(properties.map((p) => { return RSVP.all(records.map((record) => { return record.get(p); })).then((data) => { const subRecords = data.reduce((prev, cur) => prev.concat(cur.toArray()), []); return preloadAll(subRecords, toPreload[p]); }); })).then(() => records); case 'string': return RSVP.all(records.map((record) => record.get(toPreload))) .then(() => records); default: throw 'Illegal Argument'; } } function preload(thing, toPreload) { if (thing.then) { return thing.then(() => { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } else { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); } } export default preload;
import Ember from 'ember'; const { RSVP } = Ember; function getPromise(object, property) { return RSVP.resolve(Ember.get(object, property)); } function preloadRecord(record, toPreload) { if (!record) { return RSVP.resolve(record); } switch(Ember.typeOf(toPreload)) { case 'string': return getPromise(record, toPreload).then(() => record); case 'array': return RSVP.all(toPreload.map((p) => preloadRecord(record, p))).then(() => record); case 'object': return RSVP.all(Object.keys(toPreload).map((p) => getPromise(record, p).then((data) => preload(data, toPreload[p])))).then(() => record); default: throw 'Illegal Argument'; } } function preloadAll(records, toPreload) { return RSVP.all(records.map((record) => preload(record, toPreload))); } function preload(thing, toPreload) { return RSVP.resolve(thing).then(() => { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } export default preload;
Refactor preload to handle more cases
Refactor preload to handle more cases
JavaScript
mit
levanto-financial/ember-data-preload,levanto-financial/ember-data-preload
7d81ece0291bb469f1bea3bcf2c9225f74eab7d6
server/game/cards/events/01/puttothetorch.js
server/game/cards/events/01/puttothetorch.js
const DrawCard = require('../../../drawcard.js'); class PutToTheTorch extends DrawCard { canPlay(player, card) { if(player !== this.controller || this !== card) { return false; } var currentChallenge = this.game.currentChallenge; if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attacker !== this.controller || currentChallenge.strengthDifference < 5 || currentChallenge.challengeType !== 'military') { return false; } return true; } play(player) { if(this.controller !== player) { return; } this.game.promptForSelect(player, { activePromptTitle: 'Select a location to discard', waitingPromptTitle: 'Waiting for opponent to use ' + this.name, cardCondition: card => card.inPlay && card.controller !== player && card.getType() === 'location', onSelect: (p, card) => this.onCardSelected(p, card) }); } onCardSelected(player, card) { card.controller.moveCard(card, 'discard pile'); this.game.addMessage('{0} uses {1} to discard {2}', player, this, card); return true; } } PutToTheTorch.code = '01042'; module.exports = PutToTheTorch;
const DrawCard = require('../../../drawcard.js'); class PutToTheTorch extends DrawCard { canPlay(player, card) { if(player !== this.controller || this !== card) { return false; } var currentChallenge = this.game.currentChallenge; if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attackingPlayer !== this.controller || currentChallenge.strengthDifference < 5 || currentChallenge.challengeType !== 'military') { return false; } return true; } play(player) { if(this.controller !== player) { return; } this.game.promptForSelect(player, { activePromptTitle: 'Select a location to discard', waitingPromptTitle: 'Waiting for opponent to use ' + this.name, cardCondition: card => card.inPlay && card.controller !== player && card.getType() === 'location', onSelect: (p, card) => this.onCardSelected(p, card) }); } onCardSelected(player, card) { card.controller.discardCard(card); this.game.addMessage('{0} uses {1} to discard {2}', player, this, card); return true; } } PutToTheTorch.code = '01042'; module.exports = PutToTheTorch;
Fix put to the torch and allow it to use saves
Fix put to the torch and allow it to use saves
JavaScript
mit
Antaiseito/throneteki_for_doomtown,jeremylarner/ringteki,jeremylarner/ringteki,samuellinde/throneteki,cavnak/throneteki,cryogen/gameteki,jbrz/throneteki,cryogen/throneteki,gryffon/ringteki,cryogen/throneteki,Antaiseito/throneteki_for_doomtown,cryogen/gameteki,jeremylarner/ringteki,ystros/throneteki,gryffon/ringteki,DukeTax/throneteki,DukeTax/throneteki,jbrz/throneteki,cavnak/throneteki,samuellinde/throneteki,gryffon/ringteki
9cb2f8d9efef1d47ddaec2266bcc203baa1990bc
test/index.js
test/index.js
var readFile = require('fs').readFile; var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; // Test the expected output. exec('node .', function(err, stdout, stderr) { if (err) { throw err; } readFile(join(__dirname, 'expected.txt'), 'UTF-8', function(err, exp) { if (err) { throw err; } var expected = exp.split('\r\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) { assert.equal(actual[i], expected[i], "Expected '" + actual[i] + "' to be '" + expected[i] + "' on line " + (i + 1) + "."); } console.log('All tests pass!'); }); });
var readFile = require('fs').readFile; var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; var platform = require('os').platform; // Test the expected output. exec('node .', function(err, stdout, stderr) { if (err) { throw err; } readFile(join(__dirname, 'expected.txt'), 'UTF-8', function(err, exp) { if (err) { throw err; } var expected = platform() == 'win32' ? exp.split('\r\n') : exp.split('\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) { assert.equal(actual[i], expected[i], "Expected '" + actual[i] + "' to be '" + expected[i] + "' on line " + (i + 1) + "."); } console.log('All tests pass!'); }); });
Add test support for Windows
Add test support for Windows
JavaScript
isc
unioncollege-webtech/fizzbuzz
7e355008d3bc810b84ca4818e4aeecf494a89d20
assets/components/checkblock/js/inputs/checkblock.js
assets/components/checkblock/js/inputs/checkblock.js
// Wrap your stuff in this module pattern for dependency injection (function ($, ContentBlocks) { // Add your custom input to the fieldTypes object as a function // The dom variable contains the injected field (from the template) // and the data variable contains field information, properties etc. ContentBlocks.fieldTypes.checkblock = function(dom, data) { var input = { // Some optional variables can be defined here }; // Do something when the input is being loaded input.init = function() { } // Get the data from this input, it has to be a simple object. input.getData = function() { return { value:$(document.getElementById('checkblock_' + data.generated_id)).is(':checked') } } // Always return the input variable. return input; } })(vcJquery, ContentBlocks);
// Wrap your stuff in this module pattern for dependency injection (function ($, ContentBlocks) { // Add your custom input to the fieldTypes object as a function // The dom variable contains the injected field (from the template) // and the data variable contains field information, properties etc. ContentBlocks.fieldTypes.checkblock = function(dom, data) { var input = { // Some optional variables can be defined here }; // Do something when the input is being loaded input.init = function() { $(dom.find('#checkblock_' + data.generated_id)).prop('checked', data.value); } // Get the data from this input, it has to be a simple object. input.getData = function() { return { value:$(dom.find('#checkblock_' + data.generated_id)).is(':checked') } } // Always return the input variable. return input; } })(vcJquery, ContentBlocks);
Fix checkboxes not ticking themselves
Fix checkboxes not ticking themselves Closes #1
JavaScript
mit
jpdevries/checkblock,jpdevries/checkblock
53db7bd5313293b436d9664d90080eee18315165
sample/core.js
sample/core.js
enchant(); window.onload = function () { var core = new Core(320, 320); core.onload = function () { core.rootScene.backgroundColor = '#eee'; var field = new TextField(160, 24); field.x = (core.width - field.width) / 2; field.y = 64; field.placeholder = 'what is your name ?'; field.style.border = '2px solid #f6c'; field.style.borderRadius = '4px'; field.onfocus = function () { label.text = 'onfocus called!!'; }; field.onblur = function () { label.text = 'onblur called!!'; }; field.onreturn = function () { label.text = 'onreturn called!!<br>' + this.value + '!!'; }; core.rootScene.addChild(field); var label = new Label(); label.font = '32px Arial'; label.width = 320; label.height = 32; label.x = 0; label.y = core.height - label.height * 2; label.textAlign = 'center'; core.rootScene.addChild(label); }; core.start(); };
enchant(); window.onload = function () { var core = new Core(320, 320); core.onload = function () { core.rootScene.backgroundColor = '#eee'; // Create an instance of enchant.TextField var textField = new TextField(160, 24); // Set position textField.x = (core.width - textField.width) / 2; textField.y = 64; // Set placeholder textField.placeholder = 'what is your name ?'; // Set styles textField.style.border = '2px solid #f6c'; textField.style.borderRadius = '4px'; // Define events textField.onfocus = function () { label.text = 'onfocus called!!'; }; textField.onblur = function () { label.text = 'onblur called!!'; }; textField.onreturn = function () { label.text = 'onreturn called!!<br>' + this.value + '!!'; }; // Add to the scene core.rootScene.addChild(textField); var label = new Label(); label.font = '32px Arial'; label.width = 320; label.height = 32; label.x = 0; label.y = core.height - label.height * 2; label.textAlign = 'center'; core.rootScene.addChild(label); }; core.start(); };
Add some comments and rename TextField instance
Add some comments and rename TextField instance
JavaScript
mit
131e55/textField.enchant.js
3b9af3bf12b4ec3790caf898900b94d3d49aee00
elemental-ca.js
elemental-ca.js
var w = 300, gens = 10; var c = document.getElementById('cs'); var ctx = c.getContext('2d'); var ruleset = [0,1,0,1,1,0,1,0].reverse(); var cells = []; for (var i=0; i<w; i++) { cells[i] = 0; } cells[Math.ceil(w/2)] = 1; function rules(l,c,r) { var rule = '' + l + c + r; return ruleset[parseInt(rule, 2)]; } function draw(h) { var size=2; for (var i =0; i < cells.length; i++) { if (cells[i] === 0) { ctx.fillStyle = 'rgb(200,200,100)'; } else { ctx.fillStyle = 'rgb(0,155,100)'; console.log(i); } ctx.fillRect(i*size,h*size,size,size); } } function generate() { var newgen = []; for(var i=0; i < cells.length; i++) { l = cells[i-1]; c = cells[i]; r = cells[i+1]; newgen[i] = rules(l, c, r); } cells = newgen; } for (var i=0; i < gens; i++) { draw(i); generate(); }
var w = 600, gens = 800; var c = document.getElementById('cs'); var ctx = c.getContext('2d'); var ruleset = [0,1,0,1,1,0,1,0].reverse(); var cells = []; for (var i=0; i<w; i++) { cells[i] = 0; } cells[Math.ceil(w/2)] = 1; function rules(l,c,r) { var rule = '' + l + c + r; return ruleset[parseInt(rule, 2)]; } function draw(h) { var size=1; for (var i =0; i < cells.length; i++) { if (cells[i] === 0) { ctx.fillStyle = 'rgb(100,200,200)'; } else { ctx.fillStyle = 'rgb(100,55,100)'; } ctx.fillRect(i*size,h*size,size,size); } } function generate() { var newgen = []; for(var i=0; i < cells.length; i++) { l = cells[i-1]; c = cells[i]; r = cells[i+1]; newgen[i] = rules(l, c, r); } cells = newgen; } for (var i=0; i < gens; i++) { draw(i); generate(); }
Tweak the color and size a bit
Tweak the color and size a bit
JavaScript
mit
mmcfarland/canvas-renderings
4c1987b918d353f849ad1aaad174db797525ee10
scripts/app.js
scripts/app.js
var ko = require('knockout-client'), vm = require('./viewModel'); vm.wtf(); ko.applyBindings(vm);
var ko = require('knockout-client'), vm = require('./viewModel'); ko.applyBindings(vm);
Remove increment on refresh / initial visit
Remove increment on refresh / initial visit
JavaScript
mit
joshka/countw.tf,joshka/countw.tf,joshka/countw.tf,joshka/countw.tf
c70bb59f3a7357f7d2711f0de20c1cd1717fec70
react/gameday2/components/EmbedTwitch.js
react/gameday2/components/EmbedTwitch.js
import React from 'react' import { webcastPropType } from '../utils/webcastUtils' const EmbedTwitch = (props) => { const channel = props.webcast.channel const iframeSrc = `https://player.twitch.tv/?channel=${channel}` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" /> ) } EmbedTwitch.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedTwitch
import React from 'react' import { webcastPropType } from '../utils/webcastUtils' const EmbedTwitch = (props) => { const channel = props.webcast.channel const iframeSrc = `https://player.twitch.tv/?channel=${channel}` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" allowFullScreen /> ) } EmbedTwitch.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedTwitch
Fix gameday2 not allowing fullscreen Twitch
Fix gameday2 not allowing fullscreen Twitch
JavaScript
mit
nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance
66e5f23ae0283fd89d313b802c3ed20ea52137ed
app/public/app.js
app/public/app.js
$(function () { $(document).on({ ajaxStart: function() { $('body').addClass("loading"); }, ajaxStop: function() { $('body').removeClass("loading"); } }) $( "#request_form" ).submit(function( event ) { event.preventDefault(); $('.results_container').slideUp( "slow"); $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); $.each(data, function(key, value) { $('.results_container .results').append("<div class='result'>"+value+"</div>"); }); $('.results_container').slideDown( "slow"); }); }); });
$(function () { $(document).on({ ajaxStart: function() { $('body').addClass("loading"); }, ajaxStop: function() { $('body').removeClass("loading"); } }) $( "#request_form" ).submit(function( event ) { event.preventDefault(); $('.results_container').slideUp( "slow"); $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); if (data) { $.each(data, function(key, value) { $('.results_container .results').append("<div class='result'>"+value+"</div>"); }); } else { $('.results_container .results').append("<div class='result'>None</div>"); } $('.results_container').slideDown( "slow"); }); }); });
Fix view for empty response
Fix view for empty response
JavaScript
mit
nezhar/PictureChallenge,nezhar/PictureChallenge
4be53761875922cc8d27e54363624cd1ae34bc16
app/containers/Main/index.js
app/containers/Main/index.js
import React, { Component, PropTypes } from 'react'; import fetchData from '../../actions/fetchData'; import Toast from '../../components/Toast'; import Modals from '../Modals'; import types from '../../utils/types'; import SocketEvents from '../../utils/socketEvents'; import './Main.scss'; import MainNav from '../MainNav'; export default class Main extends Component { static propTypes = { ...types.entries, ...types.sections, site: PropTypes.object.isRequired, socket: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, user: PropTypes.object.isRequired, location: PropTypes.object.isRequired, children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; componentDidMount() { const { dispatch, socket } = this.props; fetchData(); const events = new SocketEvents(socket, dispatch); events.listen(); } render() { const { user, entries, sections, fields, assets, ui, dispatch, site } = this.props; if (user.isFetching || entries.isFetching || sections.isFetching || assets.isFetching || fields.isFetching) return null; return ( <main className="main"> <MainNav siteName={site.siteName} /> {React.cloneElement(this.props.children, { ...this.props, key: this.props.location.pathname, })} <div className="toasts"> {ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)} </div> <Modals {...this.props} /> </main> ); } }
import React, { Component, PropTypes } from 'react'; import fetchData from '../../actions/fetchData'; import Toast from '../../components/Toast'; import Modals from '../Modals'; import types from '../../utils/types'; import SocketEvents from '../../utils/socketEvents'; import './Main.scss'; import MainNav from '../MainNav'; export default class Main extends Component { static propTypes = { ...types.entries, ...types.sections, site: PropTypes.object.isRequired, socket: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, user: PropTypes.object.isRequired, location: PropTypes.object.isRequired, children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; componentDidMount() { const { dispatch, socket } = this.props; fetchData(); const events = new SocketEvents(socket, dispatch); events.listen(); } render() { const { ui, dispatch, site } = this.props; if (Object.keys(this.props).some(key => this.props[key].isFetching)) return null; return ( <main className="main"> <MainNav siteName={site.siteName} /> {React.cloneElement(this.props.children, { ...this.props, key: this.props.location.pathname, })} <div className="toasts"> {ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)} </div> <Modals {...this.props} /> </main> ); } }
Check for isFetching with .some
:wrench: Check for isFetching with .some
JavaScript
mit
JasonEtco/flintcms,JasonEtco/flintcms
779157a8fb6076e35fce4edcb2eb7a7a55ccdade
js/characters-list.js
js/characters-list.js
var Character = require('./character'); var React = require('react'); var _ = require('underscore') var CharactersList = React.createClass({ render: function () { return ( <div> { this.props.items.map(function(item, index) { var name = item.name; var image = item.image; var description = item.description; return <Character key={index} name={name} image={image} description={description}/>; }) } </div> ); } }); module.exports = CharactersList;
var Character = require('./character'); var React = require('react'); var _ = require('underscore') var CharactersList = React.createClass({ render: function () { return ( <div> { this.props.items.map(function(item, index) { var name = item.name; var image = item.thumbnail.path+'.'+item.thumbnail.extension; var description = item.description; return <Character key={index} name={name} image={image} description={description}/>; }) } </div> ); } }); module.exports = CharactersList;
Fix for the image prop of the character
Fix for the image prop of the character
JavaScript
mit
adrrian17/excelsior
a942d28c315f59428a80d2fd0b268cd99bbe3b66
common/src/configureStore.js
common/src/configureStore.js
import appReducer from './app/reducer'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import injectDependencies from './lib/injectDependencies'; import promiseMiddleware from 'redux-promise-middleware'; import stateToJS from './lib/stateToJS'; import validate from './validate'; import {applyMiddleware, createStore} from 'redux'; export default function configureStore(initialState) { const dependenciesMiddleware = injectDependencies( {fetch}, {validate} ); const middlewares = [ dependenciesMiddleware, promiseMiddleware ]; if (process.env.NODE_ENV !== 'production') { // eslint-disable-line no-undef const logger = createLogger({ collapsed: () => true, transformer: stateToJS }); middlewares.push(logger); } const store = applyMiddleware(...middlewares)(createStore)( appReducer, initialState); if (module.hot) { // eslint-disable-line no-undef // Enable Webpack hot module replacement for reducers. module.hot.accept('./app/reducer', () => { // eslint-disable-line no-undef const nextAppReducer = require('./app/reducer'); // eslint-disable-line no-undef store.replaceReducer(nextAppReducer); }); } return store; }
import appReducer from './app/reducer'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import injectDependencies from './lib/injectDependencies'; import promiseMiddleware from 'redux-promise-middleware'; import stateToJS from './lib/stateToJS'; import validate from './validate'; import {applyMiddleware, createStore} from 'redux'; export default function configureStore(initialState) { const dependenciesMiddleware = injectDependencies( {fetch}, {validate} ); const middlewares = [ dependenciesMiddleware, promiseMiddleware ]; const loggerEnabled = process.env.IS_BROWSER && // eslint-disable-line no-undef process.env.NODE_ENV !== 'production'; // eslint-disable-line no-undef if (loggerEnabled) { const logger = createLogger({ collapsed: () => true, transformer: stateToJS }); middlewares.push(logger); } const store = applyMiddleware(...middlewares)(createStore)( appReducer, initialState); if (module.hot) { // eslint-disable-line no-undef // Enable Webpack hot module replacement for reducers. module.hot.accept('./app/reducer', () => { // eslint-disable-line no-undef const nextAppReducer = require('./app/reducer'); // eslint-disable-line no-undef store.replaceReducer(nextAppReducer); }); } return store; }
Enable Flux logger only for dev
Enable Flux logger only for dev
JavaScript
mit
puzzfuzz/othello-redux,christophediprima/este,XeeD/este,abelaska/este,skyuplam/debt_mgmt,AugustinLF/este,TheoMer/Gyms-Of-The-World,skyuplam/debt_mgmt,langpavel/este,XeeD/test,robinpokorny/este,aindre/este-example,christophediprima/este,SidhNor/este-cordova-starter-kit,robinpokorny/este,glaserp/Maturita-Project,christophediprima/este,AlesJiranek/este,sikhote/davidsinclair,blueberryapps/este,TheoMer/Gyms-Of-The-World,XeeD/test,TheoMer/Gyms-Of-The-World,syroegkin/mikora.eu,zanj2006/este,este/este,TheoMer/este,puzzfuzz/othello-redux,vacuumlabs/este,estaub/my-este,cjk/smart-home-app,AlesJiranek/este,skallet/este,neozhangthe1/framedrop-web,GarrettSmith/schizophrenia,este/este,aindre/este-example,neozhangthe1/framedrop-web,nezaidu/este,GarrettSmith/schizophrenia,amrsekilly/updatedEste,skallet/este,neozhangthe1/framedrop-web,amrsekilly/updatedEste,amrsekilly/updatedEste,este/este,zanj2006/este,este/este,neozhangthe1/framedrop-web,nason/este,glaserp/Maturita-Project,XeeD/este,abelaska/este,TheoMer/este,syroegkin/mikora.eu,steida/este,ViliamKopecky/este,estaub/my-este,syroegkin/mikora.eu,neozhangthe1/framedrop-web,steida/este,robinpokorny/este,vacuumlabs/este,blueberryapps/este,estaub/my-este,Brainfock/este,abelaska/este,sikhote/davidsinclair,TheoMer/este,langpavel/este,sikhote/davidsinclair,GarrettSmith/schizophrenia,christophediprima/este,shawn-dsz/este,AugustinLF/este,skallet/este
43f0a5cefb43be20ae8f48deb2fa886540528b2d
lib/indie-registry.js
lib/indie-registry.js
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.emitter.on('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.emitter.on('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } has(indieLinter) { return this.indieLinters.has(indieLinter) } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.emitter.on('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.emitter.on('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
Add a new has method
:new: Add a new has method
JavaScript
mit
Arcanemagus/linter,e-jigsaw/Linter,atom-community/linter,AtomLinter/Linter,steelbrain/linter
dcf5dde3cb5833fde7430a0238e3c9436e796dc0
lib/score-combiner.js
lib/score-combiner.js
/** * checks if there are scores which can be combined */ function checkValidity (scores) { if (scores == null) { throw new Error('There must be a scores object parameter') } if (Object.keys(scores).length <= 0) { throw new Error('At least one score must be passed') } } /** * Score canidate based on the mean value of two or more parent Qs. */ class MeanQ { /** * Returns the mean value of the given scores. * @param scores - obect that contains the keys and scores * for each used scoring method * @return mean value of given scores */ combine (scores) { checkValidity(scores) var sum = 0 Object.keys(scores).map((key, index, arr) => { sum += scores[key] }) return sum / Object.keys(scores).length } } /** * Chooses the biggest score out of all possible scores */ class LargestQ { /** * combines all scores by choosing the largest score */ combine (scores) { checkValidity(scores) var largest = 0.0 Object.keys(scores).map((key, index, arr) => { if (scores[key] >= largest) { largest = scores[key] } }) return largest } } module.exports = { Mean: MeanQ, Largest: LargestQ }
/** * checks if there are scores which can be combined */ function checkValidity (scores) { if (scores == null) { throw new Error('There must be a scores object parameter') } if (Object.keys(scores).length <= 0) { throw new Error('At least one score must be passed') } } /** * Score canidate based on the mean value of two or more parent Qs. */ class MeanQ { /** * Returns the mean value of the given scores. * @param scores - obect that contains the keys and scores * for each used scoring method * @return mean value of given scores */ combine (scores) { checkValidity(scores) var sum = 0 Object.keys(scores).map((key, index, arr) => { sum += scores[key] }) return sum / Object.keys(scores).length } } /** * Chooses the biggest score out of all possible scores */ class LargestQ { /** * combines all scores by choosing the largest score */ combine (scores) { checkValidity(scores) return Math.max.apply(null, Object.values(scores)) } } module.exports = { Mean: MeanQ, Largest: LargestQ }
Refactor LargestQ.combine() to use built-ins.
Refactor LargestQ.combine() to use built-ins.
JavaScript
agpl-3.0
amos-ws16/amos-ws16-arrowjs-server,amos-ws16/amos-ws16-arrowjs,amos-ws16/amos-ws16-arrowjs,amos-ws16/amos-ws16-arrowjs,amos-ws16/amos-ws16-arrowjs-server
73b274515279466e125e658e539b1863301c5759
lib/windshaft/models/dummy_mapconfig_provider.js
lib/windshaft/models/dummy_mapconfig_provider.js
var util = require('util'); var MapStoreMapConfigProvider = require('./mapstore_mapconfig_provider'); function DummyMapConfigProvider(mapConfig, params) { if (!(this instanceof DummyMapConfigProvider)) { return new DummyMapConfigProvider(mapConfig, params); } MapStoreMapConfigProvider.call(this, undefined, params); this.mapConfig = mapConfig; } util.inherits(DummyMapConfigProvider, MapStoreMapConfigProvider); module.exports = DummyMapConfigProvider; DummyMapConfigProvider.prototype.getMapConfig = function(callback) { return callback(null, this.mapConfig, this.params, {}); };
var util = require('util'); var MapStoreMapConfigProvider = require('./mapstore_mapconfig_provider'); function DummyMapConfigProvider(mapConfig, params) { MapStoreMapConfigProvider.call(this, undefined, params); this.mapConfig = mapConfig; } util.inherits(DummyMapConfigProvider, MapStoreMapConfigProvider); module.exports = DummyMapConfigProvider; DummyMapConfigProvider.prototype.getMapConfig = function(callback) { return callback(null, this.mapConfig, this.params, {}); };
Remove instance check as it's an internal class and have full control
Remove instance check as it's an internal class and have full control
JavaScript
bsd-3-clause
CartoDB/Windshaft,wsw0108/Windshaft,CartoDB/Windshaft,CartoDB/Windshaft,wsw0108/Windshaft,wsw0108/Windshaft
969cc51155d7be88f97e27f305bf678836fa9220
packages/server/src/__tests__/jestSetup.js
packages/server/src/__tests__/jestSetup.js
const root = __dirname + '/../../../..'; require('@babel/register')({ root, cwd: root, configFile: root + '/packages/server/babel.config.js', extensions: ['.js', '.jsx', '.ts', '.tsx'] }); require.extensions['.scss'] = () => {}; require.extensions['.css'] = () => {}; require.extensions['.less'] = () => {}; Object.assign(global, require('../../jest.config').globals); const { setup } = require('@gqlapp/testing-server-ts'); require('..'); module.exports = setup;
const root = __dirname + '/../../../..'; require('@babel/register')({ root, cwd: root, configFile: root + '/packages/server/babel.config.js', extensions: ['.js', '.jsx', '.ts', '.tsx'], cache: false }); require.extensions['.scss'] = () => {}; require.extensions['.css'] = () => {}; require.extensions['.less'] = () => {}; Object.assign(global, require('../../jest.config').globals); const { setup } = require('@gqlapp/testing-server-ts'); require('..'); module.exports = setup;
Work around babel-plugin-import-graphql caching intolerance
Work around babel-plugin-import-graphql caching intolerance
JavaScript
mit
sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-fullstack-starter-kit
36ae9ccc7f43445485a6baacc4dc18834d61cda2
pretty-seconds.js
pretty-seconds.js
function quantify(data, unit, value) { if (value) { if (value > 1 || value < -1) unit += 's'; data.push(value + ' ' + unit); } return data; } module.exports = function prettySeconds(seconds) { var prettyString = '', data = []; if (typeof seconds === 'number') { data = quantify(data, 'day', parseInt(seconds / 86400)); data = quantify(data, 'hour', parseInt((seconds % 86400) / 3600)); data = quantify(data, 'minute', parseInt((seconds % 3600) / 60)); data = quantify(data, 'second', seconds % 60); var length = data.length, i; for (i = 0; i < length; i++) { if (prettyString.length > 0) if (i == length - 1) prettyString += ' and '; else prettyString += ', '; prettyString += data[i]; } } return prettyString; };
function quantify(data, unit, value) { if (value) { if (value > 1 || value < -1) unit += 's'; data.push(value + ' ' + unit); } return data; } module.exports = function prettySeconds(seconds) { var prettyString = '', data = []; if (typeof seconds === 'number') { data = quantify(data, 'day', parseInt(seconds / 86400)); data = quantify(data, 'hour', parseInt((seconds % 86400) / 3600)); data = quantify(data, 'minute', parseInt((seconds % 3600) / 60)); data = quantify(data, 'second', Math.floor(seconds % 60)); var length = data.length, i; for (i = 0; i < length; i++) { if (prettyString.length > 0) if (i == length - 1) prettyString += ' and '; else prettyString += ', '; prettyString += data[i]; } } return prettyString; };
Trim decimal places off seconds
Trim decimal places off seconds
JavaScript
mit
binarykitchen/pretty-seconds
438e6b49e171e8db87e1982677861b6c61dfcdad
scripts/nummer.js
scripts/nummer.js
// Description: // Pick and tag a random user that has to do shitty work, replies when the bot // hears @noen. This script also supports mentions of @aktive and @nye. const _ = require('lodash'); const members = require('../lib/members'); const prefixes = [ 'Time to shine', "The work doesn't do itself", 'Get going', 'lol rekt', 'About time you got picked', 'RIP', 'Move it' ]; const createMention = username => `@${username}`; module.exports = robot => { robot.hear(/@noen-nye/i, msg => { members('?new=true') .then(members => { if (!members.length) { return; } const luckyMember = _.sample(members); const mention = createMention(luckyMember.slack); const cheesyPrefix = _.sample(prefixes); msg.send(`${cheesyPrefix} ${mention}`); }) .catch(error => msg.send(error.message)); }); robot.hear(/@noen/i, msg => { // Reply with a cheesy message and a random picked mention. members('?active=true') .then(members => { if (!members.length) { return; } const luckyMember = _.sample(members); const mention = createMention(luckyMember.slack); const cheesyPrefix = _.sample(prefixes); msg.send(`${cheesyPrefix} ${mention}`); }) .catch(error => msg.send(error.message)); }); robot.hear(/@aktive|@active/i, msg => { // Reply with a message containing mentions of all active users. members('?active=true') .then(members => { if (members.length === 0) { return; } msg.send(members.map(member => createMention(member.slack)).join(', ')); }) .catch(error => msg.send(error.message)); }); robot.hear(/@nye/i, msg => { members('?new=true') .then(members => { if (members.length === 0) { return; } msg.send(members.map(member => createMention(member.slack)).join(', ')); }) .catch(error => msg.send(error.message)); }); };
// Description: // Get all phone numbers for active members const _ = require('lodash'); const members = require('../lib/members'); module.exports = robot => { robot.respond(/nummer/i, msg => { members('?active=true') .then(members => { if (members.length === 0) { return; } msg.send( members .map( m => `*${m.name}*:${'\t'} ${m.phone_number.substr( 0, 3 )} ${m.phone_number .substr(3) .match(/.{1,2}/g) .join(' ')}` ) .sort() .join('\n') ); }) .catch(error => msg.send(error.message)); }); };
Remove duplicate posts by ababot
Remove duplicate posts by ababot
JavaScript
mit
webkom/ababot,webkom/ababot
1aef53ef94e4031cb23e9c79c1b677299307284b
app/renderer/js/utils/domain-util.js
app/renderer/js/utils/domain-util.js
'use strict'; const {app} = require('electron').remote; const JsonDB = require('node-json-db'); class DomainUtil { constructor() { this.db = new JsonDB(app.getPath('userData') + '/domain.json', true, true); } getDomains() { return this.db.getData('/domains'); } addDomain() { const servers = { url: 'https://chat.zulip.org', alias: 'Zulip 2', avatar: 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png' } db.push("/domains[]", servers, true); } } module.exports = DomainUtil;
'use strict'; const {app} = require('electron').remote; const JsonDB = require('node-json-db'); class DomainUtil { constructor() { this.db = new JsonDB(app.getPath('userData') + '/domain.json', true, true); } getDomains() { return this.db.getData('/domains'); } addDomain() { const servers = { url: 'https://chat.zulip.org', alias: 'Zulip 2333', icon: 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png' } this.db.push("/domains[]", servers, true); } removeDomains() { this.db.delete("/domains"); } } module.exports = DomainUtil;
Change domain config schema and update DomainUtil.
Change domain config schema and update DomainUtil.
JavaScript
apache-2.0
zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-electron,zulip/zulip-desktop
e91e43feeddafb7d674f67f18cb2c0748a395006
packages/fela-bindings/src/extractUsedProps.js
packages/fela-bindings/src/extractUsedProps.js
/* @flow */ export default function extractUsedProps( rule: Function, theme: Object = {} ): Array<string> { const usedProps = [] // if the browser doesn't support proxies // we simply return an empty props object // see https://github.com/rofrischmann/fela/issues/468 if (typeof Proxy === 'undefined') { return usedProps } const handler = props => ({ get(target, key) { if (typeof target[key] === 'object' && target[key] !== null) { props.push(key) return target[key] } props.push(key) return target[key] }, }) const proxy = new Proxy({ theme }, handler(usedProps)) rule(proxy) return usedProps }
/* @flow */ export default function extractUsedProps( rule: Function, theme: Object = {} ): Array<string> { const usedProps = [] // if the browser doesn't support proxies // we simply return an empty props object // see https://github.com/rofrischmann/fela/issues/468 if (typeof Proxy === 'undefined') { return usedProps } const handler = props => ({ get(target, key) { if (typeof target[key] === 'object' && target[key] !== null) { props.push(key) return target[key] } props.push(key) return target[key] }, }) const proxy = new Proxy({ theme }, handler(usedProps)) try { rule(proxy) return usedProps } catch (err) { return [] } }
Handle exception extracting used props
Handle exception extracting used props Fix #595
JavaScript
mit
risetechnologies/fela,rofrischmann/fela,risetechnologies/fela,rofrischmann/fela,risetechnologies/fela,rofrischmann/fela
8bc778f740fa3fa77a49328739265e5d4edd9e54
modules/slider/Gruntfile.js
modules/slider/Gruntfile.js
module.exports = function(grunt) { grunt.config.merge({ imagemin: { slider: { files: [{ expand: true, cwd: 'cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }] } } }); grunt.registerTask('build-slider', ['imagemin:slider']); };
module.exports = function(grunt) { grunt.config.merge({ imagemin: { slider: { files: [{ expand: true, cwd: 'bower_components/cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }] } } }); grunt.registerTask('build-slider', ['imagemin:slider']); };
Update path of slider images.
Update path of slider images.
JavaScript
mit
aptuitiv/cacao
49965cc87d2f9ebf8ce7b0601845533b4721ecff
test/spec/sanity-checks.js
test/spec/sanity-checks.js
/* global describe, it, before */ var request = require('supertest') var assert = require('assert') var path = require('path') var fs = require('fs') /** * Basic sanity checks on the dev server */ describe('The prototype kit', function () { var app before(function (done) { app = require('../../server') done() }) it('should generate assets into the /public folder', function () { assert.doesNotThrow(function () { fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js')) fs.accessSync(path.resolve(__dirname, '../../public/images/favicon.ico')) fs.accessSync(path.resolve(__dirname, '../../public/stylesheets/application.css')) }) }) it('should send with a well formed response for the index page', function (done) { request(app) .get('/') .expect('Content-Type', /text\/html/) .expect(200, done) }) })
/* eslint-env mocha */ var request = require('supertest') var app = require('../../server.js') var path = require('path') var fs = require('fs') var assert = require('assert') /** * Basic sanity checks on the dev server */ describe('The prototype kit', function () { it('should generate assets into the /public folder', function () { assert.doesNotThrow(function () { fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js')) fs.accessSync(path.resolve(__dirname, '../../public/images/favicon.ico')) fs.accessSync(path.resolve(__dirname, '../../public/stylesheets/application.css')) }) }) it('should send with a well formed response for the index page', function (done) { request(app) .get('/') .expect('Content-Type', /text\/html/) .expect(200) .end(function (err, res) { if (err) { done(err) } else { done() } }) }) })
Simplify the sanity test check
Simplify the sanity test check App doesn't need to listen in the test script as supertest accepts the app variable and handles the listening and un-listening itself. This also removes the needs for the after block to stop the server.
JavaScript
mit
hannalaakso/accessible-timeout-warning,alphagov/govuk_prototype_kit,nhsbsa/ppc-prototype,joelanman/govuk_prototype_kit,davedark/proto-timeline,companieshouse/ch-accounts-prototype,Demwunz/esif-prototype,danblundell/verify-local-patterns,Demwunz/esif-prototype,abbott567/govuk_prototype_kit,dwpdigitaltech/ejs-prototype,chrishanes/pvb_prisoner_proto,abbott567/govuk_prototype_kit,nhsbsa/ppc-prototype,arminio/govuk_prototype_kit,dwpdigitaltech/hrt-prototype,samwake/hoddat-cofc-caseworking,danblundell/verify-local-patterns,tsmorgan/marx,hannalaakso/accessible-timeout-warning,arminio/govuk_prototype_kit,gavinwye/govuk_prototype_kit,DilwoarH/GDS-Prototype-DM-SavedSearch,kenmaddison-scc/verify-local-patterns,benjeffreys/hmcts-idam-proto,hannalaakso/accessible-timeout-warning,dwpdigitaltech/ejs-prototype,davedark/proto-timeline,dwpdigitaltech/hrt-prototype,BucksCountyCouncil/verify-local-patterns,davedark/proto-timeline,tsmorgan/marx,benjeffreys/hmcts-idam-proto,paulpod/invgov,alphagov/govuk_prototype_kit,joelanman/govuk_prototype_kit,danblundell/verify-local-patterns,DilwoarH/GDS-Prototype-DM-SavedSearch,kenmaddison-scc/verify-local-patterns,chrishanes/pvb_prisoner_proto,dwpdigitaltech/hrt-prototype,arminio/govuk_prototype_kit,samwake/hoddat-cofc-caseworking,BucksCountyCouncil/verify-local-patterns,samwake/hoddat-cofc-caseworking,tsmorgan/marx,joelanman/govuk_prototype_kit,alphagov/govuk_prototype_kit,abbott567/govuk_prototype_kit,DilwoarH/GDS-Prototype-DM-SavedSearch,chrishanes/pvb_prisoner_proto,benjeffreys/hmcts-idam-proto,gavinwye/govuk_prototype_kit,nhsbsa/ppc-prototype,BucksCountyCouncil/verify-local-patterns,kenmaddison-scc/verify-local-patterns,Demwunz/esif-prototype,dwpdigitaltech/ejs-prototype,paulpod/invgov,paulpod/invgov,companieshouse/ch-accounts-prototype
f4ef68a267821b41409b60d1f3efe51e7a8cd588
tests/dujs/modelfactory.js
tests/dujs/modelfactory.js
/** * Created by ChengFuLin on 2015/6/10. */ var factoryAnalyzedCFG = require('../../lib/dujs').factoryAnalyzedCFG, should = require('should'); describe('ModelFactory', function () { "use strict"; describe('Factory Method', function () { it('should support to create empty Model', function () { var analyzedCFG = factoryAnalyzedCFG.create(); should.not.exist(analyzedCFG._testonly_._graph); should.exist(analyzedCFG._testonly_._relatedScopes); analyzedCFG._testonly_._relatedScopes.length.should.eql(0); should.exist(analyzedCFG._testonly_._dupairs); analyzedCFG._testonly_._dupairs.size.should.eql(0); }); }); });
/* * Test cases for ModelFactory * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-08-14 */ var factoryModel = require('../../lib/dujs/modelfactory'); var should = require('should'); describe('ModelFactory', function () { "use strict"; describe('public methods', function () { describe('create', function () { it('should support to create empty Model', function () { var model = factoryModel.create(); should.not.exist(model._testonly_._graph); should.exist(model._testonly_._relatedScopes); model._testonly_._relatedScopes.length.should.eql(0); should.exist(model._testonly_._dupairs); model._testonly_._dupairs.size.should.eql(0); }); }); }); });
Refactor test cases for ModelFactory
Refactor test cases for ModelFactory
JavaScript
mit
chengfulin/dujs,chengfulin/dujs
1a71a91e9b143625d5863c21dc9de039e38541a2
src/user/components/online_payments.js
src/user/components/online_payments.js
import React from 'react' import CreaditCardPayment from './credit_card_payment.js' import Paypal from './paypal.js' export default (props) => { return props.user_payments.payment_sent ? SuccessfulPayment(props) : (props.user_payments.braintree_error ? Error() : PaymentOptions(props)) } const Error = () => <div>There has been a network error. Please refresh the browser.</div> const PaymentOptions = (props) => <div className='make-payment'> <h1 className='title'>Online Payment</h1> <h3 className='subtitle'>If you would prefer to pay by PayPal</h3> <h3 className='subtitle'>Alternatively pay by card</h3> <CreaditCardPayment {...props} /> </div> // <Paypal {...props} /> const SuccessfulPayment = ({ user_payments }) => <div className='make-payment'> <h1 className='title'>Successful Payment</h1> <h3 className='subtitle'> Thank you for your payment of £{user_payments.amount_entered}. Your reference for that payment is {user_payments.payment_sent.reference}. </h3> </div>
import React from 'react' import CreaditCardPayment from './credit_card_payment.js' import Paypal from './paypal.js' export default (props) => { return props.user_payments.payment_sent ? SuccessfulPayment(props) : (props.user_payments.braintree_error ? Error() : PaymentOptions(props)) } const Error = () => <div>There has been a network error. Please refresh the browser.</div> const PaymentOptions = (props) => <div className='make-payment'> <h1 className='title'>Online Payment</h1> <h3 className='subtitle'>Pay using PayPal</h3> <Paypal {...props} /> <h3 className='subtitle'>Alternatively pay by card</h3> <CreaditCardPayment {...props} /> </div> const SuccessfulPayment = ({ user_payments }) => <div className='make-payment'> <h1 className='title'>Successful Payment</h1> <h3 className='subtitle'> Thank you for your payment of £{user_payments.amount_entered}. Your reference for that payment is {user_payments.payment_sent.reference}. </h3> </div>
Add paypal component to online payments.
Add paypal component to online payments.
JavaScript
mit
foundersandcoders/sail-back,foundersandcoders/sail-back
d23aed5fd0e19b5a6612211810ebce796af3db58
sieve-of-eratosthenes.js
sieve-of-eratosthenes.js
// Sieve of Eratosthenes /*RULES: Function takes one parameter Return an array of all prime numbers from 0-parameter */ /*PSEUDOCODE: 1) Find square root of parameter 2) Create an array of numbers from 0-parameter 3) Loop through numbers, but stop until square root (if a float, stop after number rounded up?) 4) Return array */ function sieveOfEratosthenes(num){ var squareRoot = Math.sqrt(num); }
// Sieve of Eratosthenes /*RULES: Function takes one parameter Return an array of all prime numbers from 0-parameter */ /*PSEUDOCODE: 1) Find square root of parameter 2) Create an array of numbers from 0-parameter 3) Loop through numbers, but stop until square root (if a float, stop after number rounded up?) 4) Return array */ function sieveOfEratosthenes(num){ var squareRoot = Math.sqrt(num); var arr = [...Array(num + 1)].map((x, i) => i) }
Create var arr that creates the needed array depending on the given param
Create var arr that creates the needed array depending on the given param
JavaScript
mit
benjaminhyw/javascript_algorithms
2b5f19052395fd6364bd488b85e37f15b9a9bda9
cmds/create.js
cmds/create.js
'use strict'; /* * /create [name] - Creates a voice-chat channel. Optionally names it, otherwise names it Username-[current game] * */ class Create{ constructor (bot, config) { this.bot = bot; this.config = config; } get command () { return 'create' } // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { console.log("Got command, sending"); this.bot.sendMessage({ to: cid, message: 'Hello ' + username + ' [' + message + ']', }, (err, res) => { console.log('CB', err, res); }); var split = message.split(' '); var givenName = 'Temporary Channel'; if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName; console.log('Creating channel', channelName); this.bot.createTemporaryChannel(channelName, gid); } checkUserPermissions(uid, server) { return true; } } module.exports = Create;
'use strict'; /* * /create [name] - Creates a voice-chat channel. Optionally names it, otherwise names it Username-[current game] * */ class Create{ constructor (bot, config) { this.bot = bot; this.config = config; } get command () { return 'create' } // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { var split = message.split(' '); var givenName = 'Temporary Channel'; // Check if user is in game, then name it that var user = this.bot.users[uid]; if (user.game !== null) { givenName = user.game.name; } // Check if name is defined, use that if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName; console.log('Creating channel', channelName); this.bot.createTemporaryChannel(channelName, gid); } checkUserPermissions(uid, server) { return true; } } module.exports = Create;
Add temp channel init with game name
Add temp channel init with game name
JavaScript
mit
Just-Fans-Of/Impromp2
9d7c0cf74c1f7c1791cfe9ec8a36edca7a2b646d
sms-notifier/LambdaFunction.js
sms-notifier/LambdaFunction.js
// Sample Lambda Function to send notifications via text when an AWS Health event happens var AWS = require('aws-sdk'); var sns = new AWS.SNS(); // define configuration const phoneNumber =''; // Insert phone number here. For example, a U.S. phone number in E.164 format would appear as +1XXX5550100 //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { if (err) { const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); callback(null, snsPublishSuccessMessage); //return success } }); };
// Sample Lambda Function to send notifications via text when an AWS Health event happens var AWS = require('aws-sdk'); var sns = new AWS.SNS(); //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { //get phone number from Env Variable var phoneNumber = process.env.PHONE_NUMBER; //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { if (err) { const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); callback(null, snsPublishSuccessMessage); //return success } }); };
Switch phone number to Environment Variable (instead of const)
Switch phone number to Environment Variable (instead of const)
JavaScript
apache-2.0
chetankrishna08/aws-health-tools,robperc/aws-health-tools,robperc/aws-health-tools,chetankrishna08/aws-health-tools
6387ed56e8b5e41aa51a7994ca9f1db5b68a5644
app/assets/javascripts/multi-part.js
app/assets/javascripts/multi-part.js
// Javascript specific to guide admin $(function() { var sortable_opts = { axis: "y", handle: "a.accordion-toggle", stop: function(event, ui) { $('.part').each(function (i, elem) { $(elem).find('input.order').val(i + 1); ui.item.find("a.accordion-toggle").addClass("highlight"); setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) }); } } $('#parts').sortable(sortable_opts) .find("a.accordion-toggle").css({cursor: 'move'}); $('input.title'). on('change', function () { var elem = $(this); var value = elem.val(); // Set slug on change. var slug_field = elem.closest('.part').find('.slug'); if (slug_field.text() === '') { slug_field.val(GovUKGuideUtils.convertToSlug(value)); } // Set header on change. var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); });
// Javascript specific to guide admin // When we add a new part, ensure we add the auto slug generator handler $(document).on('nested:fieldAdded:parts', function(event){ addAutoSlugGeneration(); }); function addAutoSlugGeneration() { $('input.title'). on('change', function () { var elem = $(this); var value = elem.val(); // Set slug on change. var slug_field = elem.closest('.part').find('.slug'); if (slug_field.text() === '') { slug_field.val(GovUKGuideUtils.convertToSlug(value)); } // Set header on change. var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); } $(function() { var sortable_opts = { axis: "y", handle: "a.accordion-toggle", stop: function(event, ui) { $('.part').each(function (i, elem) { $(elem).find('input.order').val(i + 1); ui.item.find("a.accordion-toggle").addClass("highlight"); setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) }); } } $('#parts').sortable(sortable_opts) .find("a.accordion-toggle").css({cursor: 'move'}); addAutoSlugGeneration(); });
Fix auto slug generation for newly added parts
Fix auto slug generation for newly added parts Since moving to use nested forms, we now need to listen for a nested field added event and attach the auto slug generator handler accordingly.
JavaScript
mit
theodi/publisher,telekomatrix/publisher,alphagov/publisher,theodi/publisher,theodi/publisher,telekomatrix/publisher,alphagov/publisher,leftees/publisher,telekomatrix/publisher,leftees/publisher,leftees/publisher,theodi/publisher,alphagov/publisher,leftees/publisher,telekomatrix/publisher
940624b8bbd2d18fa4072808cb3037078d5820d3
public/javascripts/App/Search/SearchPanel.ui.js
public/javascripts/App/Search/SearchPanel.ui.js
App.Search.SearchPanelUi = Ext.extend(Ext.form.FormPanel, { title: 'Search criteria', labelWidth: 100, labelAlign: 'left', layout: 'form', tbar: { xtype: 'toolbar', items: [{ text: 'Add language', icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' }, '-', { text: 'Save search', icon: urlRoot + 'images/disk.png' }, { text: 'Saved searches', icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png' }, '-', { text: '<b>Search</b>', icon: urlRoot + 'images/zoom.png' }] }, initComponent: function() { App.Search.SearchPanelUi.superclass.initComponent.call(this); this.setupSubcomponents(); }, /* Setup */ setupSubcomponents: function() { this.addLanguageButton.on('click', this.onAddLanguageClicked, this); }, /* Event handlers */ onAddLanguageClicked: function() { alert('hei'); } });
App.Search.SearchPanelUi = Ext.extend(Ext.form.FormPanel, { title: 'Search criteria', labelWidth: 100, labelAlign: 'left', layout: 'form', tbar: { xtype: 'toolbar', items: [{ text: 'Add language', icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' //}, '-', { //text: 'Save search', //icon: urlRoot + 'images/disk.png' //}, { //text: 'Saved searches', //icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png' }, '-', { text: '<b>Search</b>', icon: urlRoot + 'images/zoom.png' }] }, initComponent: function() { App.Search.SearchPanelUi.superclass.initComponent.call(this); this.setupSubcomponents(); }, /* Setup */ setupSubcomponents: function() { this.addLanguageButton.on('click', this.onAddLanguageClicked, this); }, /* Event handlers */ onAddLanguageClicked: function() { alert('hei'); } });
Hide search saving buttons for now
Hide search saving buttons for now
JavaScript
mit
textlab/glossa,textlab/rglossa,textlab/rglossa,textlab/rglossa,textlab/glossa,textlab/rglossa,textlab/glossa,textlab/glossa,textlab/glossa,textlab/rglossa
6fe782fcd362e3cd330d22dbd17e270f26ebcf1b
app/js/arethusa/.version_template.js
app/js/arethusa/.version_template.js
'use strict'; angular.module('arethusa').constant('VERSION', { revision: '<%= sha %>', date: '<%= new Date().toJSON() %>' });
'use strict'; angular.module('arethusa').constant('VERSION', { revision: '<%= sha %>', date: '<%= new Date().toJSON() %>', repository: 'http://github.com/latin-language-toolkit/arethusa' });
Add the repo to the version CONSTANT
Add the repo to the version CONSTANT
JavaScript
mit
fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa
f972dfc1091d58884b0a5b656f0e2cf02d94ba1d
tests/integration/components/loading-bar-test.js
tests/integration/components/loading-bar-test.js
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; module('Integration | Component | loading bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const bar = '.bar'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); await later(() => { assert.equal(find(bar).getAttribute('value').trim(), 0); }, 2000); }, 1000); }); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find, waitFor } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; module('Integration | Component | loading bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const bar = '.bar'; const emptyBar = '.bar[value="0"]'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); await waitFor(bar); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); await waitFor(emptyBar); assert.equal(find(bar).getAttribute('value').trim(), 0); }, 500); }); });
Improve async loading bar test
Improve async loading bar test The waitFor helper is allows us to wait for what we are actually testing instead of a time which sometimes blocks the rendering and causes the test to be flaky.
JavaScript
mit
dartajax/frontend,thecoolestguy/frontend,djvoa12/frontend,dartajax/frontend,thecoolestguy/frontend,djvoa12/frontend,jrjohnson/frontend,ilios/frontend,ilios/frontend,jrjohnson/frontend
1bbb5f18d567cc45f10b4d1a3b943ccdf93fb7d2
test/unit/analysis/camshaft-reference.spec.js
test/unit/analysis/camshaft-reference.spec.js
var camshaftReference = require('../../../src/analysis/camshaft-reference'); describe('src/analysis/camshaft-reference', function () { describe('.getSourceNamesForAnalysisType', function () { it('should return the source names for a given analyses type', function () { expect(camshaftReference.getSourceNamesForAnalysisType('source')).toEqual([]); expect(camshaftReference.getSourceNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getSourceNamesForAnalysisType('trade-area')).toEqual(['source']); }); }); describe('.getParamNamesForAnalysisType', function () { it('should return the params names for a given analyses type', function () { expect(camshaftReference.getParamNamesForAnalysisType('source')).toEqual(['query']); expect(camshaftReference.getParamNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getParamNamesForAnalysisType('trade-area')).toEqual([ 'source', 'kind', 'time', 'isolines', 'dissolved', 'provider' ]); }); }); });
var camshaftReference = require('../../../src/analysis/camshaft-reference'); describe('src/analysis/camshaft-reference', function () { describe('.getSourceNamesForAnalysisType', function () { it('should return the source names for a given analyses type', function () { expect(camshaftReference.getSourceNamesForAnalysisType('source')).toEqual([]); expect(camshaftReference.getSourceNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getSourceNamesForAnalysisType('trade-area')).toEqual(['source']); }); }); describe('.getParamNamesForAnalysisType', function () { it('should return the params names for a given analyses type', function () { expect(camshaftReference.getParamNamesForAnalysisType('source')).toEqual(['query']); expect(camshaftReference.getParamNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getParamNamesForAnalysisType('trade-area')).toEqual([ 'source', 'kind', 'time', 'isolines', 'dissolved' ]); }); }); });
Remove expected/optional param as it was removed from reference
Remove expected/optional param as it was removed from reference
JavaScript
bsd-3-clause
splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js
9c11b6de5181e4825a345c103add725a2f487926
lib/curry-provider.js
lib/curry-provider.js
'use babel'; import completions from '../data/completions'; class CurryProvider { constructor() { this.scopeSelector = '.source.curry'; this.disableForScopeSelector = '.source.curry .comment'; this.suggestionPriority = 2; this.filterSuggestions = true; this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]); } getSuggestions({prefix}) { if (prefix) { const suggestions = []; for (const module of completions) { for (const [key, type] of this.acpTypes) { const createSugg = this.createSuggestion.bind(null, module.name, type); const matches = module[key].map(createSugg); suggestions.push(...matches); } } return suggestions; } return null; } createSuggestion(module, type, suggestion) { return { text: suggestion.name, description: suggestion.description, type: type, leftLabel: module, rightLabel: suggestion.typeSig }; } } export default new CurryProvider();
'use babel'; import completions from '../data/completions'; class CurryProvider { constructor() { this.scopeSelector = '.source.curry'; this.disableForScopeSelector = '.source.curry .comment'; this.suggestionPriority = 2; this.filterSuggestions = true; this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]); } getSuggestions({prefix}) { if (!prefix) { return null; } const suggestions = []; for (const module of completions) { for (const [key, type] of this.acpTypes) { const createSugg = this.createSuggestion.bind(null, module.name, type); const matches = module[key].map(createSugg); suggestions.push(...matches); } } return suggestions; } createSuggestion(module, type, suggestion) { return { text: suggestion.name, description: suggestion.description, type: type, leftLabel: module, rightLabel: suggestion.typeSig }; } } export default new CurryProvider();
Return null as early as possible if the prefix is invalid
Return null as early as possible if the prefix is invalid
JavaScript
mit
matthesjh/autocomplete-curry
0da59ee8c95f2d065b6f0b600f4d6cffd654437e
packages/ddp-client/common/getClientStreamClass.js
packages/ddp-client/common/getClientStreamClass.js
import { Meteor } from 'meteor/meteor'; // In the client and server entry points, we make sure the // bundler loads the correct thing. Here, we just need to // make sure that we require the right one. export default function getClientStreamClass() { // The static analyzer of the bundler specifically looks // for direct calls to 'require', so it won't treat the // below calls as a request to include that module. const notRequire = require; if (Meteor.isClient) { return notRequire('../client/stream_client_sockjs').default; } else { /* Meteor.isServer */ return notRequire('../server/stream_client_nodejs').default; } }
import { Meteor } from 'meteor/meteor'; // In the client and server entry points, we make sure the // bundler loads the correct thing. Here, we just need to // make sure that we require the right one. export default function getClientStreamClass() { // The static analyzer of the bundler specifically looks // for static calls to 'require', so it won't treat the // below calls as a request to include that module. // // That means stream_client_nodejs won't be included on // the client, as desired. const modulePath = Meteor.isClient ? '../client/stream_client_sockjs' : '../server/stream_client_nodejs'; return require(modulePath).default; }
Switch to more concise require as suggested by Ben
Switch to more concise require as suggested by Ben
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
db1c42b80ee59bc6ab4b9757c37172a0dab55d0e
examples/index.js
examples/index.js
'use strict'; var Harmonia = require('harmonia'); // Create a new server that listens to a given queue var harmonia = new Harmonia.Server('rpc'); harmonia.route({ method : 'math.add', module : './math/add.js' }); harmonia.route({ method : 'math.subtract', module : './math/subtract.js', }); harmonia.route({ method : 'math.divide', module : './math/divide.js', }); // Start the server harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client var client = Harmonia.Client.createClient('amqp://localhost', 'request', 'math.add'); client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); });
'use strict'; var Harmonia = require('harmonia'); // Create a new server that listens to a given queue var harmonia = new Harmonia.Server('rpc'); harmonia.route({ method : 'math.add', module : './math/add.js' }); harmonia.route({ method : 'math.subtract', module : './math/subtract.js', }); harmonia.route({ method : 'math.divide', module : './math/divide.js', }); // Start the server harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client var client = Harmonia.Client.createClient('amqp://localhost', 'request'); client.then(function(client) { client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); }); });
Update Harmonia client example to reflect changes in 0.4
Update Harmonia client example to reflect changes in 0.4
JavaScript
mit
linearregression/harmonia,colonyamerican/harmonia
4af7e62397088ab5e49f022f1f60f2347249920a
gulpfile.js
gulpfile.js
var gulp = require('gulp'), csslint = require('gulp-csslint'), jshint = require('gulp-jshint'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), autoprefixer = require('gulp-autoprefixer'), minifyCSS = require('gulp-minify-css'), stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()) }); gulp.task('minify:css', function () { return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], cascade: false })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css')) .pipe(gulp.dest('dist/')); }); gulp.task('jshint', function () { return gulp.src('src/imagelightbox.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('minify:js', function () { return gulp.src('src/imagelightbox.js') .pipe(uglify()) .pipe(rename('imagelightbox.min.js')) .pipe(gulp.dest('dist/')); }); gulp.task('default', ['csslint', 'minify:css', 'jshint', 'minify:js']);
var gulp = require('gulp'), csslint = require('gulp-csslint'), jshint = require('gulp-jshint'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), autoprefixer = require('gulp-autoprefixer'), minifyCSS = require('gulp-minify-css'), stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()) }); gulp.task('minify:css', function () { return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], cascade: false, })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css')) .pipe(gulp.dest('dist/')); }); gulp.task('jshint', function () { return gulp.src('src/imagelightbox.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('minify:js', function () { return gulp.src('src/imagelightbox.js') .pipe(uglify()) .pipe(rename('imagelightbox.min.js')) .pipe(gulp.dest('dist/')); }); gulp.task('default', ['csslint', 'minify:css', 'jshint', 'minify:js']);
Remove code alignment, add trailing comma, add EOF newline
Remove code alignment, add trailing comma, add EOF newline
JavaScript
mit
Lochlan/imagelightbox,Lochlan/imagelightbox
61ab0adcfc8750dda6f5aae5552cb5c282fc5282
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var react = require('gulp-react'); var git = require('gulp-git'); var fs = require('fs'); var shell = require('gulp-shell') gulp.task('brew', function () { if (fs.existsSync('homebrew')) { git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) { if (err) throw err; }); } else { git.clone('https://github.com/Homebrew/homebrew', function (err) { if (err) throw err; }); } }); gulp.task('collect', shell.task([ './bin/collect homebrew' ])); gulp.task('rank', shell.task([ './bin/rank' ])); gulp.task('dump', shell.task([ './bin/dump > dist/formulae.json' ])); gulp.task('copy', function () { return gulp.src('src/index.html') .pipe(gulp.dest('dist')) }) gulp.task('default', [ 'brew', 'collect', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist')); });
var gulp = require('gulp'); var react = require('gulp-react'); var git = require('gulp-git'); var fs = require('fs'); var shell = require('gulp-shell') gulp.task('brew', function () { if (fs.existsSync('homebrew')) { git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) { if (err) throw err; }); } else { git.clone('https://github.com/Homebrew/homebrew', function (err) { if (err) throw err; }); } }); gulp.task('collect', shell.task([ './bin/collect homebrew' ])); gulp.task('info', shell.task([ './bin/info homebrew' ])); gulp.task('rank', shell.task([ './bin/rank' ])); gulp.task('dump', shell.task([ './bin/dump > dist/formulae.json' ])); gulp.task('copy', function () { return gulp.src('src/index.html') .pipe(gulp.dest('dist')) }) gulp.task('default', [ 'brew', 'collect', 'info', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist')); });
Add automatic running of info script
Add automatic running of info script
JavaScript
mit
zharley/ferment,zharley/ferment,zharley/ferment,zharley/ferment
670474a38b8114afd4e990ad3689f50e868ea356
resources/public/crel.min.js
resources/public/crel.min.js
(e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],o(l=a.attrMap[l]||l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(()=>e):this.crel=e});
(e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],l=a.attrMap[l]||l,o(l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(e):this.crel=e});
Update crel to latest version from github.com/KoryNunn/crel
Update crel to latest version from github.com/KoryNunn/crel
JavaScript
mit
xSke/Pxls,xSke/Pxls,xSke/Pxls,xSke/Pxls
5ab7f8deedf44a29dffa468ffdbed7a406b46458
app/assets/javascripts/analytics/_init.js
app/assets/javascripts/analytics/_init.js
(function() { "use strict"; var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3'; GOVUK.Analytics.load(); GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain, receiveCrossDomainTracking: true }); GOVUK.analytics.trackPageview(); GOVUK.analytics.addLinkedTrackerDomain('digitalservicesstore.service.gov.uk'); })();
(function() { "use strict"; var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = 'UA-49258698-1'; GOVUK.Analytics.load(); GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain, receiveCrossDomainTracking: true }); GOVUK.analytics.trackPageview(); GOVUK.analytics.addLinkedTrackerDomain('digitalservicesstore.service.gov.uk'); })();
Use a single UA code for Buyer App analytics
Use a single UA code for Buyer App analytics Missed out of this story (which only changed the Supplier App): https://www.pivotaltracker.com/story/show/106115458
JavaScript
mit
AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
3bbb177681f8c05443f001721ebd50dfd205c4f5
ui/src/pages/blog/index.js
ui/src/pages/blog/index.js
import React from 'react' import Link from 'gatsby-link' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Blog</h2> </header> {data.allMarkdownRemark.edges.map(({ node }) => ( <section key={node.id} className="blog-preview"> <article > <Link to={node.frontmatter.path}><h3>{node.frontmatter.title}</h3></Link> <h4>{node.frontmatter.date}</h4> <p>{node.excerpt}</p> </article> </section> ))} </div> </section> ) } export const query = graphql` query BlogListQuery { allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}) { edges { node { id frontmatter { date title path } excerpt(pruneLength: 300) } } } } `
import React from 'react' import Link from 'gatsby-link' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Blog</h2> </header> {data.allMarkdownRemark.edges.map(({ node }) => ( <section key={node.id} className="blog-preview"> <article > <Link to={node.frontmatter.path}><h3>{node.frontmatter.title}</h3></Link> <h4>{node.frontmatter.date}</h4> <p>{node.excerpt}</p> </article> </section> ))} </div> </section> ) } export const query = graphql` query BlogListQuery { allMarkdownRemark( filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}, sort: {fields: [frontmatter___date], order: DESC} ) { edges { node { id frontmatter { date title path } excerpt(pruneLength: 300) } } } } `
Sort blog entries by date.
Sort blog entries by date.
JavaScript
mit
danielbh/danielhollcraft.com,danielbh/danielhollcraft.com,danielbh/danielhollcraft.com-gatsbyjs,danielbh/danielhollcraft.com
c13d87bfb90bd3a7a1951305795c586be6afde98
lib/pick-chain-url.js
lib/pick-chain-url.js
const MAIN_API_URL = 'https://api.etherscan.io'; const OTHER_API_URL_MAP = { ropsten: 'https://api-ropsten.etherscan.io', kovan: 'https://api-kovan.etherscan.io', rinkeby: 'https://api-rinkeby.etherscan.io', homestead: 'https://api.etherscan.io', arbitrum: 'https://api.arbiscan.io', arbitrum_rinkeby: 'https://api-testnet.arbiscan.io' }; /** * gets the correct urls of the backend * @param {string} chain * @returns Url of backend */ function pickChainUrl(chain) { if (!chain || !OTHER_API_URL_MAP[chain]) { return MAIN_API_URL; } return OTHER_API_URL_MAP[chain]; } module.exports = pickChainUrl;
const MAIN_API_URL = 'https://api.etherscan.io'; const OTHER_API_URL_MAP = { ropsten: 'https://api-ropsten.etherscan.io', kovan: 'https://api-kovan.etherscan.io', rinkeby: 'https://api-rinkeby.etherscan.io', goerli: 'https://api-goerli.etherscan.io', sepolia: 'https://api-sepolia.etherscan.io', homestead: 'https://api.etherscan.io', arbitrum: 'https://api.arbiscan.io', arbitrum_rinkeby: 'https://api-testnet.arbiscan.io' }; /** * gets the correct urls of the backend * @param {string} chain * @returns Url of backend */ function pickChainUrl(chain) { if (!chain || !OTHER_API_URL_MAP[chain]) { return MAIN_API_URL; } return OTHER_API_URL_MAP[chain]; } module.exports = pickChainUrl;
Add Goerli and Sepolia to the API list
Add Goerli and Sepolia to the API list Hey @sebs Thanks a lot for this amazing library. I created this PR to include the Sepolia and Goerli API endpoints. Currently I'm creating the client (with `axios.create`) to support those two, but I'd be cool if I have directly included on the library. Thanks!
JavaScript
mit
sebs/etherscan-api
69d52f1cbac1c63a3a6f05aa32f8b8274cf4854f
src/open.js
src/open.js
function readSingleFile(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; reader.readAsText(file); } function TestCall(event, other) { console.log(event); console.log(other); } function displayContents(contents) { var lines = contents.split("\n"), output = [], i; output.push("<thead><tr><th scope=\"col\"><button>" + lines[0].slice(0, -1).split(",").join("</button></th><th scope=\"col\"><button>") + "</button></th></tr></thead>"); for (i = 1; i < lines.length; i++) output.push("<tr><td>" + lines[i].slice(0, -1).split(",").join("</td><td>") + "</td></tr>"); output = "<table>" + output.join("") + "</table>"; var div = document.getElementById('file-content'); div.innerHTML = output; var ths = document.getElementsByTagName("th"); console.log("ths " + ths); for (var i = 0; i < ths.length; i++) { ths[i].onclick = TestCall } // var element = $('#content'); // element.innerHTML = contents; }
let csv = (function () { let buildHeader = function (line) { return "<thead><tr><th scope=\"col\"><button>" + line.slice(0, -1).split(",").join("</button></th><th scope=\"col\"><button>") + "</button></th></tr></thead>" }; let buildAsHtml = function (lines) { let output = [buildHeader(lines[0])]; for (let i = 1; i < lines.length; i++) output.push("<tr><td>" + lines[i].slice(0, -1).split(",").join("</td><td>") + "</td></tr>"); return "<table>" + output.join("") + "</table>"; }; return { buildAsHtml: buildAsHtml }; })(); function readSingleFile(e) { let file = e.target.files[0]; if (!file) { return; } let reader = new FileReader(); reader.onload = function(e) { let contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; reader.readAsText(file); } function TestCall(event, other) { console.log(event); console.log(other); } function displayContents(contents) { var div = document.getElementById('file-content'); div.innerHTML = csv.buildAsHtml(contents.split("\n")); var ths = document.getElementsByTagName("th"); console.log("ths " + ths); for (var i = 0; i < ths.length; i++) { ths[i].onclick = TestCall } // var element = $('#content'); // element.innerHTML = contents; }
Move csv in a module
Move csv in a module
JavaScript
mpl-2.0
aloisdg/kanti,aloisdg/kanti
0d5e7868c1cc1354748af529aca5727ffa9472c4
lib/state-snapshot.js
lib/state-snapshot.js
class StateSnapshot { constructor({ store, initialState, meta, currentState = initialState }) { this.store = store; this.initialState = { ...initialState }; this.items = { ...currentState }; this.meta = meta; this.closed = false; } async dispatchToStateSnapshot(action) { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; const newItems = await this.store.reducer({ ...this.items }, action); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, currentState: newItems, meta: this.meta, }); } async commitStateSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; await this.store.commit({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.items }, meta: this.meta, }); } async discardStateSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; await this.store.discard({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, meta: this.meta, }); } } exports.StateSnapshot = StateSnapshot;
class StateSnapshot { constructor({ store, initialState, meta, currentState = initialState }) { this.store = store; this.initialState = { ...initialState }; this.items = { ...currentState }; this.meta = meta; this.closed = false; } _closeSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; } async dispatchToStateSnapshot(action) { this._closeSnapshot(); const newItems = await this.store.reducer({ ...this.items }, action); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, currentState: newItems, meta: this.meta, }); } async commitStateSnapshot() { this._closeSnapshot(); await this.store.commit({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.items }, meta: this.meta, }); } async discardStateSnapshot() { this._closeSnapshot(); await this.store.discard({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, meta: this.meta, }); } } exports.StateSnapshot = StateSnapshot;
Remove code duplication from snapshot closed check
Remove code duplication from snapshot closed check
JavaScript
mit
jay-depot/cloverleaf
8513c39e48ed6bd6ff28b21c898f39d96a9a8259
src/actions/user-actions.js
src/actions/user-actions.js
import db from '../db'; import { createAction } from 'redux-actions'; export const USER_LOGIN = 'USER_LOGIN'; export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'; export const USER_SIGNUP = 'USER_SIGNUP'; export const USER_SIGNUP_SUCCESS = 'USER_SIGNUP_SUCCESS'; export const USER_SIGNUP_FAIL = 'USER_SIGNUP_FAIL'; export const USER_LOGOUT = 'USER_LOGOUT'; export const login = createAction(USER_LOGIN, (username, password) => db.login(username, password));
import db from '../db'; import { createAction } from 'redux-actions'; export const USER_LOGIN = 'USER_LOGIN'; export const USER_SIGNUP = 'USER_SIGNUP'; export const USER_LOGOUT = 'USER_LOGOUT'; export const login = createAction(USER_LOGIN, (username, password) => db.login(username, password)); export const signup = createAction(USER_SIGNUP, (username, password) => db.signup(username, password)); export const logout = createAction(USER_LOGOUT, () => db.logout());
Add actions for user management
Add actions for user management
JavaScript
mit
andrew-filonenko/habit-tracker,andrew-filonenko/habit-tracker
c042d3fcdf6f38fc2a6562d4d4c1b17bcc2da269
client/js/directives/file-uploader-directive.js
client/js/directives/file-uploader-directive.js
"use strict"; angular.module("hikeio"). directive("fileUploader", ["$window", function($window) { return { compile: function(tplElm, tplAttr) { var mulitpleStr = tplAttr.multiple === "true" ? "multiple" : ""; tplElm.after("<input type='file' " + mulitpleStr + " accept='image/png, image/jpeg' style='display: none;'>"); return function(scope, elm, attr) { if (scope.$eval(attr.enabled)) { var input = angular.element(elm[0].nextSibling); input.bind("change", function() { if (input[0].files.length > 0) { scope.$eval(attr.fileUploader, {files: input[0].files}); input[0].value = ""; // Allow the user to select the same file again } }); elm.bind("click", function() { if (input[0].disabled) { $window.alert("Sorry this browser doesn't support file upload."); } input[0].click(); }); elm.css("cursor", "pointer"); } }; }, replace: true, template: "<div data-ng-transclude></div>", transclude: true }; }]);
"use strict"; angular.module("hikeio"). directive("fileUploader", ["$window", function($window) { return { compile: function(tplElm, tplAttr) { var mulitpleStr = tplAttr.multiple === "true" ? "multiple" : ""; tplElm.after("<input type='file' " + mulitpleStr + " accept='image/png, image/jpeg' style='display: none;'>"); return function(scope, elm, attr) { if (scope.$eval(attr.enabled)) { var input = angular.element(elm[0].nextSibling); input.bind("change", function() { if (input[0].files.length > 0) { scope.$eval(attr.fileUploader, {files: input[0].files}); input[0].value = ""; // Allow the user to select the same file again } }); elm.bind("click", function() { if (input[0].disabled || !$window.FileReader || !window.FormData) { $window.alert("Sorry, you cannot upload photos from this browser."); return; } input[0].click(); }); elm.css("cursor", "pointer"); } }; }, replace: true, template: "<div data-ng-transclude></div>", transclude: true }; }]);
Disable file inputs on browsers that don't support FileReader / FormData.
Disable file inputs on browsers that don't support FileReader / FormData.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
0a0e0ce83fba432df1a108925933a2a1e9a8c2f7
src/js/rishson/widget/example/nls/es/Wishlist.js
src/js/rishson/widget/example/nls/es/Wishlist.js
define({ root: { SortBy: "Ordenar por:", Descending: "Descendente", Name: "Nombre", DateAdded: "Fecha de entrada", Price: "Precio", Actions: "Acciones", Add: "Añadir", Remove: "Eliminar", Save: "Guardar" } });
define({ SortBy: "Ordenar por:", Descending: "Descendente", Name: "Nombre", DateAdded: "Fecha de entrada", Price: "Precio", Actions: "Acciones", Add: "Añadir", Remove: "Eliminar", Save: "Guardar" });
Fix mistake in Spanish i18n resource for example widget
Fix mistake in Spanish i18n resource for example widget
JavaScript
isc
rishson/dojoEnterpriseApp,rishson/dojoEnterpriseApp
55effc39da807b77262aca98a8587db369ca19e5
src/js/main.js
src/js/main.js
(function() { "use strict"; // animate moving between anchor links smoothScroll.init({ selector: "a", speed: 500, easing: "easeInOutCubic" }); // better external SVG spiresheet support svg4everybody(); // random placeholders for the contact form fields var form = document.querySelector(".contact"), names = [ "Paul Bunyan", "Luke Skywalker", "Jason Bourne", "James Bond" ], messages = [ "Like what you see? Let me know!", "Want to know more? Get in touch!", "Hey! Did I tickle your fancy?" ]; form.querySelector("[id='name']").placeholder = randomFromArray(names); form.querySelector("[id='message']").placeholder = randomFromArray(messages); function randomFromArray(array) { return array[Math.floor(Math.random() * array.length)]; } })();
(function() { "use strict"; // animate moving between anchor hash links smoothScroll.init({ selector: "a", speed: 500, easing: "easeInOutCubic" }); // better external SVG spritesheet support svg4everybody(); // random placeholders for the contact form fields var names = [ "Paul Bunyan", "Luke Skywalker", "Jason Bourne", "James Bond" ], messages = [ "Like what you see? Let me know!", "Want to know more? Get in touch!", "Hey! Did I tickle your fancy?" ]; document.getElementById("name").placeholder = randomFromArray(names); document.getElementById("message").placeholder = randomFromArray(messages); function randomFromArray(array) { return array[Math.floor(Math.random() * array.length)]; } })();
Fix typo and optimize DOM querying
[js] Fix typo and optimize DOM querying
JavaScript
mit
Pinjasaur/portfolio,Pinjasaur/portfolio
ab3f0d14c998384b161c966b114c4793e1cb2795
src/history/startListener.js
src/history/startListener.js
import { manualChange } from '../redux/actions'; /** * Dispatches a manualChange action once on app start, * and whenever a popstate navigation event occurs. */ function startListener(history, store) { store.dispatch(manualChange(history.location.path)); history.listen((location, action) => { if (action === 'POP') { store.dispatch(manualChange(location.path)); } }); } export { startListener };
import { manualChange } from '../redux/actions'; /** * Dispatches a manualChange action once on app start, * and whenever a popstate navigation event occurs. */ function startListener(history, store) { store.dispatch(manualChange(`${history.location.pathname}${history.location.search}${history.location.hash}`)); history.listen((location, action) => { if (action === 'POP') { store.dispatch(manualChange(`${location.pathname}${location.search}${location.hash}`)); } }); } export { startListener };
Fix location dispatched in history listener
Fix location dispatched in history listener
JavaScript
mit
mksarge/redux-json-router
a6bc03b09d04df24b049fa9f3e5c257b82040078
src/Model/Game/Levels.js
src/Model/Game/Levels.js
function Levels(prng, paletteRange, paletteBuilder) { this.prng = prng; this.paletteRange = paletteRange; this.paletteBuilder = paletteBuilder; } Levels.prototype.get = function(level) { if( typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); var puzzle = new Puzzle(level, board); return new Level(puzzle, levelPalette); };
function Levels(prng, paletteRange, paletteBuilder) { this.prng = prng; this.paletteRange = paletteRange; this.paletteBuilder = paletteBuilder; } Levels.prototype.get = function(level) { if(typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); var puzzle = new Puzzle(level, board); return new Level(puzzle, levelPalette); };
Remove extra space from if statement
Remove extra space from if statement
JavaScript
mit
mnito/factors-game,mnito/factors-game
ee2c4f35fdcf4784b08cc341a0aff77d2f33883e
app/assets/javascripts/toggle_display_with_checked_input.js
app/assets/javascripts/toggle_display_with_checked_input.js
(function(window, $){ window.toggleDisplayWithCheckedInput = function(args){ var $input = args.$input, $element = args.$element, showElement = args.mode === 'show'; var toggleOnChange = function(){ console.log($input); console.log("args.$mode =" + args.$mode); if($input.prop("checked")) { console.log("checked - toggle: " + showElement); $element.toggle(showElement); } else { console.log("unchecked - toggle: " + !showElement); $element.toggle(!showElement); } } $input.change(toggleOnChange); }; })(window, $);
(function(window, $){ window.toggleDisplayWithCheckedInput = function(args){ var $input = args.$input, $element = args.$element, showElement = args.mode === 'show'; var toggleOnChange = function(){ if($input.prop("checked")) { $element.toggle(showElement); } else { $element.toggle(!showElement); } } $input.change(toggleOnChange); }; })(window, $);
Remove console.log debug from toggleDisplayWithCheckedInput JS
Remove console.log debug from toggleDisplayWithCheckedInput JS
JavaScript
mit
alphagov/manuals-publisher,alphagov/manuals-publisher,alphagov/manuals-publisher
f0ccc846a8e1849e3fb37fbdded2de74ce76e1ae
app/components/add-expense.js
app/components/add-expense.js
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Component.extend({ attributeBindings: ['dialog-open'], didInsertElement () { var dialog = document.getElementById(this.$().attr('id')); var showDialogButton = $('[dialog-open]'); console.log(dialog, showDialogButton); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } showDialogButton.click(function () { dialog.showModal(); }); // dialog.querySelector('.close').addEventListener('click', function () { // dialog.close(); // }); $(dialog).on('click', function () { dialog.close(); }); componentHandler.upgradeAllRegistered() } });
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Component.extend({ attributeBindings: ['dialog-open'], expenseCategories: [ 'Charity', 'Clothing', 'Education', 'Events', 'Food', 'Gifts', 'Healthcare', 'Household', 'Leisure', 'Hobbies', 'Trasportation', 'Utilities', 'Vacation' ], didInsertElement () { var dialog = document.getElementById(this.$().attr('id')); var showDialogButton = $('[dialog-open]'); console.log(dialog, showDialogButton); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } showDialogButton.click(function () { dialog.showModal(); }); // dialog.querySelector('.close').addEventListener('click', function () { // dialog.close(); // }); $(dialog).on('click', function () { dialog.close(); }); componentHandler.upgradeAllRegistered() } });
Set expense categories in component
feat: Set expense categories in component
JavaScript
mit
pe1te3son/spendings-tracker,pe1te3son/spendings-tracker
7b6debe0ab1c1b4beb349ec963cb7ff026a8e48a
server/model/Post/schema.js
server/model/Post/schema.js
import {DataTypes as t} from "sequelize" import format from "date-fns/format" import createSlug from "lib/helper/util/createSlug" /** * @const schema * * @type {import("sequelize").ModelAttributes} */ const schema = { id: { type: t.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }, userId: { type: t.INTEGER.UNSIGNED, allowNull: false }, title: { type: t.STRING, allowNull: false, /** * @param {string} value */ set(value) { this.setDataValue("title", value) this.setDataValue( "slug", `${createSlug(value)}-${format(Date.now(), "YYYY-MM-dd")}` ) } }, slug: { type: t.STRING, allowNull: false, unique: true }, text: { type: t.TEXT({length: "medium"}), allowNull: false }, isDraft: { type: t.BOOLEAN, allowNull: false, defaultValue: true } } export default schema
import {DataTypes as t} from "sequelize" import format from "date-fns/format" import createSlug from "lib/helper/util/createSlug" /** * @const schema * * @type {import("sequelize").ModelAttributes} */ const schema = { id: { type: t.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }, userId: { type: t.INTEGER.UNSIGNED, allowNull: false }, title: { type: t.STRING, allowNull: false, /** * @param {string} value */ set(value) { this.setDataValue("title", value) this.setDataValue( "slug", `${format(Date.now(), "YYYY-MM-dd")}/${createSlug(value)}}` ) } }, slug: { type: t.STRING, allowNull: false, unique: true }, text: { type: t.TEXT({length: "medium"}), allowNull: false }, isDraft: { type: t.BOOLEAN, allowNull: false, defaultValue: true } } export default schema
Change slug format in Post model
Change slug format in Post model
JavaScript
mit
octet-stream/eri,octet-stream/eri
cd8a3d11287f247fe3898593f80bf1bdf3840d4f
app/js/services/apihandler.js
app/js/services/apihandler.js
'use strict'; /* * Abstration layer for various RESTful api calls */ var apihandler = angular.module('apihandler', []); apihandler.factory('apiFactory', function ($http, configFactory) { // Private API var url = configFactory.getValue('apiUrl') // Public API return {}; });
'use strict'; /* * Abstration layer for various RESTful API calls */ var apihandler = angular.module('apihandler', []); apihandler.factory('apiFactory', function ($http, configFactory) { // Private API var url = configFactory.getValue('apiUrl'); // Various different kinds of errors that can be returned from the REST API var errorTypes = { VERIFICATION : { USER_EXISTS : 'user_exists', NUMBER_MISSING : 'number_missing' }, REGISTER : { NO_VERIFICATION : 'no_verification', VERIFICATION_EXPIRED : 'verification_expired', VERIFICATION_USED : 'verification_used', REGISTER_FAILED : 'register_failed', }, LOGIN : { USER_NOT_FOUND : 'user_not_found', BCRYPT_ERROR : 'bcrypt_error', WRONG_PASSWORD : 'wrong_password' } }; // Public API return {}; });
Add error types from REST Api
Add error types from REST Api
JavaScript
mit
learning-layers/sardroid,learning-layers/sardroid,learning-layers/sardroid
a5468c3b575dfe2d04e03d72bcec34b8e353e9b7
src/lb/lb.base.js
src/lb/lb.base.js
/* * Namespace: lb.base * Adapter Modules for Base JavaScript Library * * Authors: * o Eric Bréchemier <github@eric.brechemier.name> * o Marc Delhommeau <marc.delhommeau@legalbox.com> * * Copyright: * Eric Bréchemier (c) 2011, Some Rights Reserved * Legal-Box SAS (c) 2010-2011, All Rights Reserved * * License: * BSD License * http://creativecommons.org/licenses/BSD/ * * Version: * 2011-08-14 */ /*global define */ define( [ "./lb" ], function(lb) { // Note: no methods defined at this level currently // Assign to lb.base // for backward-compatibility in browser environment lb.base = { // public API }; return lb.base; } );
/* * Namespace: lb.base * Adapter Modules for Base JavaScript Library * * Authors: * o Eric Bréchemier <github@eric.brechemier.name> * o Marc Delhommeau <marc.delhommeau@legalbox.com> * * Copyright: * Eric Bréchemier (c) 2011-2013, Some Rights Reserved * Legal-Box SAS (c) 2010-2011, All Rights Reserved * * License: * BSD License * http://creativecommons.org/licenses/BSD/ * * Version: * 2013-09-09 */ /*global define */ define( [ "./lb" ], function(lb) { function no( value ) { // Function: no(value): boolean // Check whether given value is null or undefined // // Parameter: // value - any, the value to check // // Returns: // boolean, false when the value is null or undefined, // true otherwise var undef; // do not trust global undefined, which can be set to a value return value === null || value === undef; } // Assign to lb.base // for backward-compatibility in browser environment lb.base = { // public API no: no }; return lb.base; } );
Add implementation of no(), copied from nada project (CC0)
Add implementation of no(), copied from nada project (CC0)
JavaScript
bsd-3-clause
eric-brechemier/lb_js_scalableApp,eric-brechemier/lb_js_scalableApp,eric-brechemier/lb_js_scalableApp
97fc9bbf3ddeeec0d3f3fbae0a08346e6fad0987
app/assets/javascripts/modules/moj.submit-once.js
app/assets/javascripts/modules/moj.submit-once.js
(function () { 'use strict'; moj.Modules.SubmitOnce = { el: '.js-SubmitOnce', init: function () { this.cacheEls(); this.bindEvents(); this.options = { alt: this.$el.data('alt') || 'Please wait…' }; }, cacheEls: function () { this.$el = $(this.el); this.$submit = this.$el.find('[type=submit], button'); }, bindEvents: function () { this.$el.on('submit', $.proxy(this.disable, this)); }, disable: function () { this.$submit[this.$submit[0].tagName === 'INPUT' ? 'val' : 'text'](this.options.alt); this.$submit.prop('disabled', true); } }; }());
(function () { 'use strict'; moj.Modules.SubmitOnce = { el: '.js-SubmitOnce', init: function () { this.cacheEls(); this.bindEvents(); this.options = { alt: this.$el.data('alt') || 'Please wait…' }; }, cacheEls: function () { this.$el = $(this.el); this.$submit = this.$el.find('[type=submit], button'); }, bindEvents: function () { this.$el.on('submit', $.proxy(this.disable, this)); }, disable: function () { switch(this.$submit[0].tagName) { case 'INPUT': case 'BUTTON': this.$submit.val(this.options.alt); break; default: this.$submit.text(this.options.alt); } this.$submit.prop('disabled', true); } }; }());
Fix tagName selection for IE8
Fix tagName selection for IE8
JavaScript
mit
ministryofjustice/prison-visits-public,ministryofjustice/prison-visits-public,ministryofjustice/prison-visits-public,ministryofjustice/prison-visits-public
47382b8696201a939ce1394586701d1715e28ffa
src/js/plugin.js
src/js/plugin.js
// Save the other cropper Cropper.other = $.fn.cropper; // Register as jQuery plugin $.fn.cropper = function (options) { var args = toArray(arguments, 1), result; this.each(function () { var $this = $(this), data = $this.data('cropper'), fn; if (!data) { $this.data('cropper', (data = new Cropper(this, options))); } if (typeof options === 'string' && $.isFunction((fn = data[options]))) { result = fn.apply(data, args); } }); return isUndefined(result) ? this : result; }; $.fn.cropper.Constructor = Cropper; $.fn.cropper.setDefaults = Cropper.setDefaults; // No conflict $.fn.cropper.noConflict = function () { $.fn.cropper = Cropper.other; return this; };
// Save the other cropper Cropper.other = $.fn.cropper; // Register as jQuery plugin $.fn.cropper = function (options) { var args = toArray(arguments, 1), result; this.each(function () { var $this = $(this), data = $this.data('cropper'), fn; if (!data) { if (/destroy/.test(options)) { return; } $this.data('cropper', (data = new Cropper(this, options))); } if (typeof options === 'string' && $.isFunction((fn = data[options]))) { result = fn.apply(data, args); } }); return isUndefined(result) ? this : result; }; $.fn.cropper.Constructor = Cropper; $.fn.cropper.setDefaults = Cropper.setDefaults; // No conflict $.fn.cropper.noConflict = function () { $.fn.cropper = Cropper.other; return this; };
Break destroy calling when not initialized
Break destroy calling when not initialized
JavaScript
mit
Paulyoufu/cropper,samudiogo/cropper,shinygang/cropper,99designs/cropper,liuyan5258/cropper,ashokpant/cropper,iacdingping/cropper,OddPrints/cropper,mesnilgr/cropper,FuYung/cropper,tekinaggul/cropper,bercanozcan/cropper,tekinaggul/cropper,websdotcom/cropper,liuyan5258/cropper,iacdingping/cropper,VANITAX/cropper,itxd/cropper,VANITAX/cropper,guillermomartinez/cropper,VANITAX/cropper,mig1098/cropper,99designs/cropper,samudiogo/cropper,arkomlueng/cropper,websdotcom/cropper,99designs/cropper,un33k/cropper,guillermomartinez/cropper,bercanozcan/cropper,mig1098/cropper,websdotcom/cropper,guillermomartinez/cropper,un33k/cropper,albertonaperijr/cropper,et-soft/cropper,ashokpant/cropper,FuYung/cropper,ndtreviv/cropper,salindalakmal/cropper,OddPrints/cropper,samudiogo/cropper,mesnilgr/cropper,mig1098/cropper,et-soft/cropper,albertonaperijr/cropper,FuYung/cropper,ashokpant/cropper,fengyuanchen/cropper,timothybannister/cropper,arkomlueng/cropper,Paulyoufu/cropper,mesnilgr/cropper,timothybannister/cropper,shinygang/cropper,jemmeliCss/cropper,jemmeliCss/cropper,ndtreviv/cropper,salindalakmal/cropper,itxd/cropper
d58d68a2990c6effd98093957bb7520814508fcd
web/static/js/battle_snake/board_viewer.js
web/static/js/battle_snake/board_viewer.js
import Mousetrap from "mousetrap"; import $ from "jquery"; import socket from "../socket" import "../empties/modal"; const logError = resp => { console.error("Unable to join", resp) }; const init = (gameId) => { if(typeof gameId === "undefined") { return; } const boardViewerChannel = socket.channel(`board_viewer:${gameId}`, {contentType: "html"}); const gameAdminChannel = socket.channel(`game_admin:${gameId}`); boardViewerChannel.on("tick", ({content}) => { $("#board-viewer").html() }); boardViewerChannel. join(). receive("error", logError); gameAdminChannel. join(). receive("error", logError); const cmd = (request) => { console.log(request); gameAdminChannel. push(request). receive("error", e => console.error(`push "${request}" failed`, e)); }; Mousetrap.bind(["q"], () => cmd("stop")); Mousetrap.bind(["h", "left"], () => cmd("prev")); Mousetrap.bind(["j", "up"], () => cmd("resume")); Mousetrap.bind(["k", "down"], () => cmd("pause")); Mousetrap.bind(["l", "right"], () => cmd("next")); Mousetrap.bind("R", () => cmd("replay")); }; export default { init };
import Mousetrap from "mousetrap"; import socket from "../socket" import "../empties/modal"; const logError = resp => { console.error("Unable to join", resp) }; const init = (gameId) => { if(typeof gameId === "undefined") { return; } const boardViewerChannel = socket.channel(`board_viewer:${gameId}`, {contentType: "html"}); const gameAdminChannel = socket.channel(`game_admin:${gameId}`); boardViewerChannel.on("tick", ({content}) => { document.getElementById("board-viewer").innerHTML = content; }); boardViewerChannel. join(). receive("error", logError); gameAdminChannel. join(). receive("error", logError); const cmd = (request) => { console.log(request); gameAdminChannel. push(request). receive("error", e => console.error(`push "${request}" failed`, e)); }; Mousetrap.bind(["q"], () => cmd("stop")); Mousetrap.bind(["h", "left"], () => cmd("prev")); Mousetrap.bind(["j", "up"], () => cmd("resume")); Mousetrap.bind(["k", "down"], () => cmd("pause")); Mousetrap.bind(["l", "right"], () => cmd("next")); Mousetrap.bind("R", () => cmd("replay")); }; export default { init };
Optimize dom replacement for board viewer
Optimize dom replacement for board viewer This one line cuts down the "loading" slice from the chrome timeline from 25% to 3%. jQuery.html performs a very expensive html validation before inserting to into the dom. Because we *hope* that we're sending valid html before hand we don't need to do this. This leaves page redraw and paint as the next largest bottleneck, which cannot be overcome without using something other than svg.
JavaScript
agpl-3.0
Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake
df039b068a097624e99755199ff86d3d4c6365be
app/components/organization/SettingsSection.js
app/components/organization/SettingsSection.js
import React from 'react'; import Relay from 'react-relay'; import SettingsMenu from './SettingsMenu'; const SettingsSection = (props) => <div className="twbs-container"> <div className="clearfix mxn2"> <div className="md-col md-col-3 px2"> <SettingsMenu organization={props.organization} /> </div> <div className="md-col md-col-9 px2"> {props.children} </div> </div> </div> SettingsSection.propTypes = { organization: React.PropTypes.object.isRequired, children: React.PropTypes.node.isRequired }; export default Relay.createContainer(SettingsSection, { fragments: { organization: () => Relay.QL` fragment on Organization { name slug members { count } invitations { count } teams { count } permissions { organizationUpdate { allowed } organizationMemberCreate { allowed } notificationServiceUpdate { allowed } organizationBillingUpdate { allowed } teamAdmin { allowed } } } ` } });
import React from 'react'; import Relay from 'react-relay'; import PageWithMenu from '../shared/PageWithMenu'; import SettingsMenu from './SettingsMenu'; const SettingsSection = (props) => <PageWithMenu> <SettingsMenu organization={props.organization} /> {props.children} </PageWithMenu> SettingsSection.propTypes = { organization: React.PropTypes.object.isRequired, children: React.PropTypes.node.isRequired }; export default Relay.createContainer(SettingsSection, { fragments: { organization: () => Relay.QL` fragment on Organization { name slug members { count } invitations { count } teams { count } permissions { organizationUpdate { allowed } organizationMemberCreate { allowed } notificationServiceUpdate { allowed } organizationBillingUpdate { allowed } teamAdmin { allowed } } } ` } });
Use the new PageWithMenu component
Use the new PageWithMenu component
JavaScript
mit
buildkite/frontend,buildkite/frontend,fotinakis/buildkite-frontend,fotinakis/buildkite-frontend
978425c95077c11682d9f01a378f0e2fd7513f63
src/middleware.js
src/middleware.js
import interceptor from "express-interceptor"; import SVGO from "svgo"; /** * SVGO middleware: optimize any SVG response. */ export function svgo(options) { const svgo = new SVGO(options); return interceptor((req, res) => { return { isInterceptable: function() { return /image\/svg\+xml(;|$)/.test(res.get("content-type")); }, intercept: function(body, send) { svgo.optimize(body, (result) => { send(result.data); }); } }; }); }
import interceptor from "express-interceptor"; import SVGO from "svgo"; /** * SVGO middleware: optimize any SVG response. */ export function svgo(options) { const svgo = new SVGO(options); return interceptor((req, res) => { return { isInterceptable: function() { return /image\/svg\+xml(;|$)/.test(res.get("content-type")); }, intercept: function(body, send) { if (body) { svgo.optimize(body, (result) => { send(result.data); }); } else { send(body); } } }; }); }
Fix HEAD requests breaking SVG responses
Fix HEAD requests breaking SVG responses
JavaScript
mit
exogen/badge-matrix,exogen/badge-matrix,exogen/badge-matrix
c04bab344d7aa2eb6c25e0bcb5492b1405657f07
lib/av-extra.js
lib/av-extra.js
'use strict'; var AV = require('avoscloud-sdk'); var crypto = require('crypto'); AV._config.disableCurrentUser = true; AV.Promise.setPromisesAPlusCompliant(true); // 调用 API 时增加 prod 信息 if (!AV._old_request) { AV._old_request = AV._request; AV._request = function (route, className, objectId, method, dataObject, sessionToken) { if (!dataObject) { dataObject = {}; } dataObject._ApplicationProduction = AV.Cloud.__prod; return AV._old_request(route, className, objectId, method, dataObject, sessionToken); }; } AV.Object.prototype.disableBeforeHook = function() { this.set('__before', signDisableHook('__before_for_' + this.className, new Date().getTime())); }; AV.Object.prototype.disableAfterHook = function() { this.set('__after', signDisableHook('__after_for_' + this.className, new Date().getTime())); }; function signDisableHook(hookName, ts) { var sign = crypto.createHmac('sha1', AV.masterKey) .update(hookName + ':' + ts) .digest('hex'); return ts + ',' + sign; } module.exports = AV;
'use strict'; var AV = require('avoscloud-sdk'); var crypto = require('crypto'); AV._config.disableCurrentUser = true; AV.Promise.setPromisesAPlusCompliant(true); AV._config.applicationProduction = AV.Cloud.__prod; AV.Object.prototype.disableBeforeHook = function() { this.set('__before', signDisableHook('__before_for_' + this.className, new Date().getTime())); }; AV.Object.prototype.disableAfterHook = function() { this.set('__after', signDisableHook('__after_for_' + this.className, new Date().getTime())); }; function signDisableHook(hookName, ts) { var sign = crypto.createHmac('sha1', AV.masterKey) .update(hookName + ':' + ts) .digest('hex'); return ts + ',' + sign; } module.exports = AV;
Set API prod by AV._config.applicationProduction.
Set API prod by AV._config.applicationProduction.
JavaScript
mit
sdjcw/leanengine-node-sdk,leancloud/leanengine-node-sdk,aisk/leanengine-node-sdk
9762b789a4e94d2f4ab7fbb553f1a3d08dcd07df
src/App/Body/AboutButton.js
src/App/Body/AboutButton.js
import React from 'react'; import { version } from 'root/package.json'; import RaisedButton from 'material-ui/lib/raised-button'; import FlatButton from 'material-ui/lib/flat-button'; import Dialog from 'material-ui/lib/dialog'; export default class AboutButton extends React.Component { state = { dialogIsOpen: false }; render() { const okButton = ( <FlatButton label="OK" primary onTouchTap={this.closeDialog} /> ); return ( <div style={style.container}> <RaisedButton label="About" onTouchTap={this.openDialog} /> <Dialog title="About this tool" open={this.state.dialogIsOpen} actions={[okButton]} onRequestClose={this.closeDialog} modal={false} > <p>CAPTIVA License Decoder (version {version})</p> <p> {'Concept and specifications by Jim Smith. Designed and implemented by '} <a href="https://www.linkedin.com/in/ksmithbaylor" target="_blank"> Kevin Smith </a>. </p> </Dialog> </div> ); } closeDialog = () => this.setState({ dialogIsOpen: false }); openDialog = () => this.setState({ dialogIsOpen: true }); } const style = { container: { display: 'inline-block', marginRight: '0.5em' } };
import React from 'react'; import { version } from 'root/package.json'; import RaisedButton from 'material-ui/lib/raised-button'; import FlatButton from 'material-ui/lib/flat-button'; import Dialog from 'material-ui/lib/dialog'; export default class AboutButton extends React.Component { state = { dialogIsOpen: false }; render() { const okButton = ( <FlatButton label="OK" primary onTouchTap={this.closeDialog} /> ); return ( <div style={style.container}> <RaisedButton label="About" onTouchTap={this.openDialog} /> <Dialog title="About this tool" open={this.state.dialogIsOpen} actions={[okButton]} onRequestClose={this.closeDialog} modal={false} > <p>Intelligent Capture License Decoder (version {version})</p> <p> {'Concept and specifications by Jim Smith. Designed and implemented by '} <a href="https://www.linkedin.com/in/ksmithbaylor" target="_blank"> Kevin Smith </a>. </p> </Dialog> </div> ); } closeDialog = () => this.setState({ dialogIsOpen: false }); openDialog = () => this.setState({ dialogIsOpen: true }); } const style = { container: { display: 'inline-block', marginRight: '0.5em' } };
Change one more CAPTIVA to Intelligent Capture
Change one more CAPTIVA to Intelligent Capture
JavaScript
cc0-1.0
ksmithbaylor/emc-license-summarizer,ksmithbaylor/emc-license-summarizer,ksmithbaylor/emc-license-summarizer