commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
c86593d654f2852caad6620510069c63191c3f04
app/index.js
app/index.js
var peer = require('./peer'); var textOT = require('ottypes').text var gulf = require('gulf'); var bindEditor = require('gulf-textarea'); var textarea = document.querySelector('textarea#doc'); var textareaDoc = bindEditor(textarea); var text = 'hello'; var path = 'chat.sock'; // var transport = require('./transports/socket')(path); // var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' }); var transport = require('./transports/webrtc')(); peer(transport).then(stream => { console.log('started'); console.log(stream.server ? 'master' : 'slave'); window.stream = stream; var textareaMaster = textareaDoc.masterLink(); if (stream.server) { // master gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, doc) => { var slave1 = doc.slaveLink(); stream.pipe(slave1).pipe(stream); var slave2 = doc.slaveLink(); textareaMaster.pipe(slave2).pipe(textareaMaster); }); } else { // slave textareaMaster.pipe(stream).pipe(textareaMaster); } });
var peer = require('./peer'); var textOT = require('ottypes').text var gulf = require('gulf'); var text = 'hello'; var doc = require('gulf-textarea')( document.querySelector('textarea#doc') ); var path = 'chat.sock'; // var transport = require('./transports/socket')(path); // var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' }); var transport = require('./transports/webrtc')(); peer(transport).then(stream => { console.log('started'); console.log(stream.server ? 'master' : 'slave'); window.stream = stream; var textareaMaster = doc.masterLink(); if (stream.server) { // master gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, master) => { var slave1 = master.slaveLink(); stream.pipe(slave1).pipe(stream); var slave2 = master.slaveLink(); textareaMaster.pipe(slave2).pipe(textareaMaster); }); } else { // slave textareaMaster.pipe(stream).pipe(textareaMaster); } });
Tidy doc representation into swappable one-liner.
Tidy doc representation into swappable one-liner.
JavaScript
cc0-1.0
nybblr/p2p-experiments,nybblr/p2p-experiments
dc79c6bdd3bae0ed3aa5a5663a55d574ab18379d
app/index.js
app/index.js
import 'babel-core/polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { ReduxRouter } from 'redux-router'; import Immutable from 'seamless-immutable'; import rootReducer from 'reducers/index'; import configureStore from 'store/configureStore'; import 'assets/styles/app.less'; const initialStoreState = createStore(rootReducer, {}).getState(); const initialState = window.__INITIAL_STATE__; const finalState = Immutable(initialStoreState).merge(initialState, { deep: true }); const store = configureStore(finalState); render( <Provider store={store}> <ReduxRouter components={[]} location={{}} params={{}} routes={[]} /> </Provider>, document.getElementById('root') ); if (__DEVTOOLS__) { require('./createDevToolsWindow')(store); }
import 'babel-core/polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { ReduxRouter } from 'redux-router'; import Immutable from 'seamless-immutable'; import rootReducer from 'reducers/index'; import configureStore from 'store/configureStore'; import 'assets/styles/app.less'; const initialStoreState = createStore(rootReducer, {}).getState(); const initialState = window.__INITIAL_STATE__; const finalState = Immutable(initialStoreState).merge(initialState, { deep: true }); const store = configureStore(finalState); render( <Provider store={store}> <ReduxRouter components={[]} location={{}} params={{}} routes={[]} /> </Provider>, document.getElementById('root') ); if (__DEVTOOLS__) { require('./createDevToolsWindow')(store); } // Fix for IE if (!window.location.origin) { window.location.origin = ( window.location.protocol + '//' + window.location.hostname + ( window.location.port ? ':' + window.location.port : '' ) ); }
Fix logout link on IE
Fix logout link on IE Closes #213.
JavaScript
mit
fastmonkeys/respa-ui
6dc0dabebb1ce6bf419cbb53d83c42b017c467a6
src/components/datepicker/utils.js
src/components/datepicker/utils.js
import { DateUtils } from 'react-day-picker/lib/src/index'; export const convertModifiersToClassnames = (modifiers, theme) => { if (!modifiers) { return {}; } return Object.keys(modifiers).reduce((convertedModifiers, key) => { return { ...convertedModifiers, [theme[key]]: modifiers[key], }; }, {}); }; export const isSelectingFirstDay = (from, to, day) => { const isBeforeFirstDay = from && DateUtils.isDayBefore(day, from); const isRangeSelected = from && to; return !from || isBeforeFirstDay || isRangeSelected; };
import { DateUtils } from 'react-day-picker/lib/src/index'; import { DateTime } from 'luxon'; export const convertModifiersToClassnames = (modifiers, theme) => { if (!modifiers) { return {}; } return Object.keys(modifiers).reduce((convertedModifiers, key) => { return { ...convertedModifiers, [theme[key]]: modifiers[key], }; }, {}); }; export const isSelectingFirstDay = (from, to, day) => { const isBeforeFirstDay = from && DateUtils.isDayBefore(day, from); const isRangeSelected = from && to; return !from || isBeforeFirstDay || isRangeSelected; }; export function JSDateToLocaleString(date, locale, format = DateTime.DATE_SHORT) { return DateTime.fromJSDate(date) .setLocale(locale) .toLocaleString(format); }
Add util function to convert a JS date to locale string
Add util function to convert a JS date to locale string
JavaScript
mit
teamleadercrm/teamleader-ui
30c2850e9593738f2059c4c401ac75fd7b2c87fe
src/js/route.js
src/js/route.js
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, paramsArrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, ''); paramsArrayKey++; if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, params = typeof params !== 'object' ? [params] : params, paramsArrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, ''); paramsArrayKey++; if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
Add support for single param instead of array/object.
Add support for single param instead of array/object.
JavaScript
mit
tightenco/ziggy,tightenco/ziggy
72c5934e1f5fde40ef8cdae61b205ebd91bddd3c
website/src/app/project/experiments/experiment/experiment.model.js
website/src/app/project/experiments/experiment/experiment.model.js
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.done = false; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
Add done flag to experiment.
Add done flag to experiment.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
ba39cf7dbc7ec530d0e9556bd819f01ae97f73f3
src/helpers/collection/sort.js
src/helpers/collection/sort.js
exports.sort = function (Handlebars) { return function (array, field, options) { if (arguments.length === 1) { throw new Error('Handlebars Helper "sort" needs 1 parameter'); } options = arguments[arguments.length - 1]; if (arguments.length === 2) { field = undefined; } var results; if (field === undefined) { results = array.sort(); } else { results = array.sort(function (a, b) { return a[field] > b[field]; }); } if (!options.fn) { return results; } else { if (results.length) { var data = Handlebars.createFrame(options.data); return results.map(function (result, i) { data.index = i; data.first = (i === 0); data.last = (i === results.length - 1); return options.fn(result, {data: data}); }).join(''); } else { return options.inverse(this); } } }; };
exports.sort = function (Handlebars) { return function (input, key, options) { if (arguments.length === 1) { throw new Error('Handlebars Helper "sort" needs 1 parameter'); } options = arguments[arguments.length - 1]; if (arguments.length === 2) { key = undefined; } var results = input.concat(); if (key === undefined) { results.sort(); } else { results.sort(function (a, b) { if (typeof a !== 'object' && typeof b !== 'object') return 0; if (typeof a !== 'object') return -1; if (typeof b !== 'object') return 1; return a[key] > b[key]; }); } if (!options.fn) { return results; } else { if (results.length) { var data = Handlebars.createFrame(options.data); return results.map(function (result, i) { data.index = i; data.first = (i === 0); data.last = (i === results.length - 1); return options.fn(result, {data: data}); }).join(''); } else { return options.inverse(this); } } }; };
Sort by key now confirms both inputs are objects before comparing keys.
Sort by key now confirms both inputs are objects before comparing keys.
JavaScript
mit
ChiperSoft/HandlebarsHelperHoard,ChiperSoft/HandlebarsHelperHoard
ec7fa504176d692b3425a9954114189e6428c03e
src/js/ui/counter-indicator.js
src/js/ui/counter-indicator.js
export const counterIndicator = { name: 'counter', order: 5, onInit: (counterElement, pswp) => { pswp.on('change', () => { counterElement.innerHTML = (pswp.currIndex + 1) + pswp.options.indexIndicatorSep + pswp.getNumItems(); }); } };
export const counterIndicator = { name: 'counter', order: 5, onInit: (counterElement, pswp) => { pswp.on('change', () => { counterElement.innerText = (pswp.currIndex + 1) + pswp.options.indexIndicatorSep + pswp.getNumItems(); }); } };
Drop support of HTML for indexIndicatorSep option
Drop support of HTML for indexIndicatorSep option
JavaScript
mit
dimsemenov/PhotoSwipe,dimsemenov/PhotoSwipe
90405067d41afe85eaaa7d9822f40f5ec74b7881
spring-boot-admin-server-ui/modules/applications/services/applicationViews.js
spring-boot-admin-server-ui/modules/applications/services/applicationViews.js
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; module.exports = function ($state, $q) { 'ngInject'; var views = []; this.register = function (view) { views.push(view); }; this.getApplicationViews = function (application) { var applicationViews = []; views.forEach(function (view) { $q.when(!view.show || view.show(application)).then(function (result) { if (result) { view.href = $state.href(view.state, { id: application.id }); applicationViews.push(view); applicationViews.sort(function (v1, v2) { return (v1.order || 0) - (v2.order || 0); }); } }); }); return applicationViews; }; };
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var angular = require('angular'); module.exports = function ($state, $q) { 'ngInject'; var views = []; this.register = function (view) { views.push(view); }; this.getApplicationViews = function (application) { var applicationViews = []; views.forEach(function (view) { $q.when(!view.show || view.show(application)).then(function (result) { if (result) { var appView = angular.copy(view); appView.href = $state.href(view.state, { id: application.id }); applicationViews.push(appView); applicationViews.sort(function (v1, v2) { return (v1.order || 0) - (v2.order || 0); }); } }); }); return applicationViews; }; };
Fix wrong links when listing multiple apps
Fix wrong links when listing multiple apps
JavaScript
apache-2.0
codecentric/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,joshiste/spring-boot-admin,codecentric/spring-boot-admin,codecentric/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,librucha/spring-boot-admin
c3b3b55bcd208f66a2a6e85f1b97d822d815e803
schema/image/proxies/index.js
schema/image/proxies/index.js
module.exports = function() { return require('./embedly').apply(null, arguments); };
const { RESIZING_SERVICE } = process.env; module.exports = function() { if (RESIZING_SERVICE === 'gemini') { return require('./gemini').apply(null, arguments); } else { return require('./embedly').apply(null, arguments); } };
Configure using an ENV variable
Configure using an ENV variable
JavaScript
mit
craigspaeth/metaphysics,mzikherman/metaphysics-1,craigspaeth/metaphysics,mzikherman/metaphysics-1,1aurabrown/metaphysics,artsy/metaphysics,broskoski/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics
fd1b91a2cc219d27318d7b72a213a41c55fd1859
dataviva/static/js/modules/help.js
dataviva/static/js/modules/help.js
$('.sidebar a').on('click', function(){ $('.sidebar a').attr('class',''); $(this).toggleClass('active'); });
$('.sidebar a').on('click', function(){ $('.sidebar a').attr('class',''); $(this).toggleClass('active'); }); $("#home .col-md-6 > .panel-heading > h2 a").on('click', function(){ $('.sidebar a').attr('class',''); $('#sidebar_' + $(this).parent().parent()[0].id).toggleClass('active'); });
Add js funtion that maps tab-content to sidebar-menu.
Add js funtion that maps tab-content to sidebar-menu.
JavaScript
mit
DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site
6055bc4109f4ccc582095f912bf68fb796e6d63e
public/js/chrome/toppanel.js
public/js/chrome/toppanel.js
(function () { /*global jsbin, $, $body*/ 'use strict'; if (jsbin.settings.gui === undefined) { jsbin.settings.gui = {}; } if (jsbin.settings.gui.toppanel === undefined) { jsbin.settings.gui.toppanel = true; } var removeToppanel = function() { $body.addClass('toppanel-close'); $body.removeClass('toppanel'); }; var showToppanel = function() { $body.removeClass('toppanel-close'); $body.addClass('toppanel'); }; // to remove var goSlow = function(e) { $body.removeClass('toppanel-slow'); if (e.shiftKey) { $body.addClass('toppanel-slow'); } }; $('.toppanel-hide').click(function(event) { event.preventDefault(); goSlow(event); jsbin.settings.gui.toppanel = false; removeToppanel(); }); $('.toppanel-logo').click(function(event) { event.preventDefault(); goSlow(event); jsbin.settings.gui.toppanel = true; showToppanel(); }); $document.keydown(function (event) { if (event.which == 27) { if ($body.hasClass('toppanel')) { jsbin.settings.gui.toppanel = false; removeToppanel(); } } }); }());
(function () { /*global jsbin, $, $body, $document*/ 'use strict'; if (jsbin.settings.gui === undefined) { jsbin.settings.gui = {}; } if (jsbin.settings.gui.toppanel === undefined) { jsbin.settings.gui.toppanel = true; localStorage.setItem('settings', JSON.stringify(jsbin.settings)); } var removeToppanel = function() { jsbin.settings.gui.toppanel = false; localStorage.setItem('settings', JSON.stringify(jsbin.settings)); $body.addClass('toppanel-close'); $body.removeClass('toppanel'); }; var showToppanel = function() { jsbin.settings.gui.toppanel = true; localStorage.setItem('settings', JSON.stringify(jsbin.settings)); $body.removeClass('toppanel-close'); $body.addClass('toppanel'); }; // to remove var goSlow = function(e) { $body.removeClass('toppanel-slow'); if (e.shiftKey) { $body.addClass('toppanel-slow'); } }; $('.toppanel-hide').click(function(event) { event.preventDefault(); goSlow(event); removeToppanel(); }); $('.toppanel-logo').click(function(event) { event.preventDefault(); goSlow(event); showToppanel(); }); $document.keydown(function (event) { if (event.which == 27) { if ($body.hasClass('toppanel')) { removeToppanel(); } } }); }());
Save the state in localStorage
Save the state in localStorage
JavaScript
mit
IvanSanchez/jsbin,eggheadio/jsbin,yohanboniface/jsbin,jsbin/jsbin,vipulnsward/jsbin,KenPowers/jsbin,yize/jsbin,thsunmy/jsbin,jamez14/jsbin,martinvd/jsbin,ilyes14/jsbin,svacha/jsbin,remotty/jsbin,yize/jsbin,roman01la/jsbin,kirjs/jsbin,IvanSanchez/jsbin,yohanboniface/jsbin,mlucool/jsbin,kirjs/jsbin,filamentgroup/jsbin,minwe/jsbin,jamez14/jsbin,AverageMarcus/jsbin,mingzeke/jsbin,jasonsanjose/jsbin-app,francoisp/jsbin,thsunmy/jsbin,arcseldon/jsbin,fgrillo21/NPA-Exam,IveWong/jsbin,dennishu001/jsbin,dedalik/jsbin,mlucool/jsbin,pandoraui/jsbin,francoisp/jsbin,simonThiele/jsbin,ctide/jsbin,late-warrior/jsbin,saikota/jsbin,knpwrs/jsbin,blesh/jsbin,mingzeke/jsbin,HeroicEric/jsbin,saikota/jsbin,ctide/jsbin,mcanthony/jsbin,dedalik/jsbin,eggheadio/jsbin,johnmichel/jsbin,IveWong/jsbin,minwe/jsbin,fgrillo21/NPA-Exam,jwdallas/jsbin,juliankrispel/jsbin,y3sh/jsbin-fork,carolineartz/jsbin,vipulnsward/jsbin,roman01la/jsbin,ilyes14/jsbin,KenPowers/jsbin,juliankrispel/jsbin,simonThiele/jsbin,kentcdodds/jsbin,jwdallas/jsbin,knpwrs/jsbin,kentcdodds/jsbin,fend-classroom/jsbin,y3sh/jsbin-fork,johnmichel/jsbin,fend-classroom/jsbin,dhval/jsbin,KenPowers/jsbin,svacha/jsbin,mdo/jsbin,dhval/jsbin,late-warrior/jsbin,dennishu001/jsbin,jsbin/jsbin,AverageMarcus/jsbin,martinvd/jsbin,Freeformers/jsbin,peterblazejewicz/jsbin,carolineartz/jsbin,arcseldon/jsbin,HeroicEric/jsbin,filamentgroup/jsbin,Hamcha/jsbin,Hamcha/jsbin,mcanthony/jsbin,jasonsanjose/jsbin-app,digideskio/jsbin,peterblazejewicz/jsbin,knpwrs/jsbin,Freeformers/jsbin,pandoraui/jsbin,digideskio/jsbin
0a4fba655f4030f0b4b5d244416510086c0ae419
public/main/utils/updates.js
public/main/utils/updates.js
define([ "Underscore", "yapp/yapp", "vendors/socket.io" ], function(_, yapp, io) { var logging = yapp.Logger.addNamespace("updates"); var Updates = new (yapp.Class.extend({ /* Constructor */ initialize: function() { this.url = [window.location.protocol, '//', window.location.host].join(''); logging.log("Connexion to "+this.url); this.socket = io.connect(this.url); // Video streaming stats this.socket.on('stats', function(data) { //logging.log("streaming stats ", data); this.trigger("streaming:stats", data); }); // Remote control connected this.socket.on('remote', _.bind(function() { logging.log("remote is connected"); this.trigger("remote:start"); }, this)); // Touch input from remote this.socket.on('remote_input', _.bind(function(data) { logging.log("remote input ", data); this.trigger("remote:input", data); }, this)); // Search from remote this.socket.on('remote_search', _.bind(function(q) { logging.log("remote search ", q); this.trigger("remote:search", q); yapp.History.navigate("search/:q", { "q": q }); }, this)); // Connexion error this.socket.on('error', _.bind(function(data) { logging.error("error in socket.io") }, this)); return this; }, })); return Updates; });
define([ "Underscore", "yapp/yapp", "vendors/socket.io" ], function(_, yapp, io) { var logging = yapp.Logger.addNamespace("updates"); var Updates = new (yapp.Class.extend({ /* Constructor */ initialize: function() { this.url = [window.location.protocol, '//', window.location.host].join(''); logging.log("Connexion to "+this.url); this.socket = io.connect(this.url); // Video streaming stats this.socket.on('stats', _.bind(function(data) { //logging.log("streaming stats ", data); this.trigger("streaming:stats", data); }, this)); // Remote control connected this.socket.on('remote', _.bind(function() { logging.log("remote is connected"); this.trigger("remote:start"); }, this)); // Touch input from remote this.socket.on('remote_input', _.bind(function(data) { logging.log("remote input ", data); this.trigger("remote:input", data); }, this)); // Search from remote this.socket.on('remote_search', _.bind(function(q) { logging.log("remote search ", q); this.trigger("remote:search", q); yapp.History.navigate("search/:q", { "q": q }); }, this)); // Connexion error this.socket.on('error', _.bind(function(data) { logging.error("error in socket.io") }, this)); return this; }, })); return Updates; });
Correct error in client for streaming
Correct error in client for streaming
JavaScript
apache-2.0
mafintosh/tv.js,thefkboss/tv.js,SamyPesse/tv.js,thefkboss/tv.js,mafintosh/tv.js,SamyPesse/tv.js,thefkboss/tv.js
15607d784bd426fa22789beaf42b6625e0c606c0
src/chart/candlestick/candlestickVisual.js
src/chart/candlestick/candlestickVisual.js
define(function (require) { var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor']; var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0']; var positiveColorQuery = ['itemStyle', 'normal', 'color']; var negativeColorQuery = ['itemStyle', 'normal', 'color0']; return function (ecModel, api) { ecModel.eachRawSeriesByType('candlestick', function (seriesModel) { var data = seriesModel.getData(); data.setVisual({ legendSymbol: 'roundRect' }); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { data.each(function (idx) { var itemModel = data.getItemModel(idx); var sign = data.getItemLayout(idx).sign; data.setItemVisual( idx, { color: itemModel.get( sign > 0 ? positiveColorQuery : negativeColorQuery ), borderColor: itemModel.get( sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery ) } ); }); } }); }; });
define(function (require) { var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor']; var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0']; var positiveColorQuery = ['itemStyle', 'normal', 'color']; var negativeColorQuery = ['itemStyle', 'normal', 'color0']; return function (ecModel, api) { ecModel.eachRawSeriesByType('candlestick', function (seriesModel) { var data = seriesModel.getData(); data.setVisual({ legendSymbol: 'roundRect' }); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { data.each(function (idx) { var itemModel = data.getItemModel(idx); var openVal = data.get('open', idx); var closeVal = data.get('close', idx); var sign = openVal > closeVal ? -1 : openVal < closeVal ? 1 : 0; data.setItemVisual( idx, { color: itemModel.get( sign > 0 ? positiveColorQuery : negativeColorQuery ), borderColor: itemModel.get( sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery ) } ); }); } }); }; });
Remove layout dependency in candlestick visual
Remove layout dependency in candlestick visual
JavaScript
apache-2.0
hexj/echarts,ecomfe/echarts,ecomfe/echarts,apache/incubator-echarts,chenfwind/echarts,hexj/echarts,100star/echarts,chenfwind/echarts,hexj/echarts,starlkj/echarts,starlkj/echarts,starlkj/echarts,apache/incubator-echarts,100star/echarts
5a98f2a4874d47da9e05a56eae3018e911fc30f1
src/components/demos/DigitalLines/index.js
src/components/demos/DigitalLines/index.js
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes } from 'react'; class DigitalLines { static propTypes = { }; canvasRender() { }; componentDidMount() { // Get a reference to the canvas object var canvas = document.getElementById('digitalLinesCanvas'); // Create an empty project and a view for the canvas: paper.setup(canvas); // Create a Paper.js Path to draw a line into it: var path = new paper.Path(); // Give the stroke a color path.strokeColor = 'black'; var start = new paper.Point(100, 100); // Move to start and draw a line from there path.moveTo(start); // Note that the plus operator on Point objects does not work // in JavaScript. Instead, we need to call the add() function: path.lineTo(start.add([ 200, -50 ])); // Draw the view now: paper.view.draw(); }; componentWillUpdate() { }; render() { return ( <div className="DigitalLines"> Hello World! <canvas width="800" height="400" id="digitalLinesCanvas" /> </div> ); } } export default { name: 'Digital Lines', key: 'digitalLines', author: 'Josh', technologies: [], component: DigitalLines };
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes } from 'react'; class Line { constructor() { try { this.path = new paper.Path(); this.path.fillColor = undefined; this.path.strokeColor = 'green'; this.path.strokeWidth = 2; // Left side var cur = new paper.Point(0, Math.random() * 500); this.path.moveTo(cur); while (cur.x < 800) { cur = cur.add(new paper.Point(Math.random() * 50 + 25, Math.random() * 50 - 25)); this.path.lineTo(cur); } this.path.smooth(); }catch (e) { console.log(e); }; } }; class DigitalLines { static propTypes = { }; canvasRender() { }; componentDidMount() { // Get a reference to the canvas object var canvas = document.getElementById('digitalLinesCanvas'), lines = []; // Create an empty project and a view for the canvas: paper.setup(canvas); for (var i = 0; i < 10; i++) lines.push(new Line()); path.view.onFrame = function (event) { }; // Draw the view now: paper.view.draw(); }; componentWillUpdate() { }; render() { return ( <div className="DigitalLines"> Hello World! <canvas width="800" height="400" id="digitalLinesCanvas" /> </div> ); } } export default { name: 'Digital Lines', key: 'digitalLines', author: 'Josh', technologies: [], component: DigitalLines };
Update to DigitalLines. Taking a slight mental transition to learn about Bezier Curves.
Update to DigitalLines. Taking a slight mental transition to learn about Bezier Curves.
JavaScript
mit
jung-digital/jd-demos,jung-digital/jd-demos
c951d161be8d2faf6e497d80e69998aa49a445bd
desktop/tests/database.spec.js
desktop/tests/database.spec.js
const assert = require('assert'); const parse = require('../app/shared/database/parse'); describe('database', () => { describe('parse.js', () => { const testQuery = 'Learn something! @3+2w !'; it('should return correct task text', () => { assert(parse(testQuery).text === 'Learn something!'); }); it('should return correct starting point', () => { assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000); }); it('should return correct ending point', () => { assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000); }); it('should return correct importance', () => { assert(parse(testQuery).importance === 2); }); it('should return correct status', () => { assert(parse(testQuery).status === 0); }); }); });
const assert = require('assert'); const parse = require('../app/shared/database/parse'); describe('database', () => { describe('parse.js', () => { const testQuery = 'Learn something! @3+2w !'; it('should return task text', () => { assert(parse(testQuery).text === 'Learn something!'); }); it('should return starting point', () => { assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000); }); it('should return ending point', () => { assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000); }); it('should return importance', () => { assert(parse(testQuery).importance === 2); }); it('should return status', () => { assert(parse(testQuery).status === 0); }); }); });
Remove "correct" word from test titles
Remove "correct" word from test titles
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
b1f3c2110910665038b5d4738d225009b21530f1
plugins/knowyourmeme.js
plugins/knowyourmeme.js
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'Know Your Meme', version:'0.1', prepareImgLinks:function (callback) { var res = []; hoverZoom.urlReplace(res, 'a img.small', '/small/', '/original/' ); callback($(res)); } });
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'Know Your Meme', version:'0.2', prepareImgLinks:function (callback) { var res = []; hoverZoom.urlReplace(res, 'a img.small', '/small/', '/original/' ); hoverZoom.urlReplace(res, 'img[src]', ['/list/', '/masonry/', '/medium/', '/newsfeed/', '/tiny/'], ['/original/', '/original/', '/original/', '/original/', '/original/'] ); callback($(res), this.name); } });
Update for plug-in : KnowYourMeme
Update for plug-in : KnowYourMeme
JavaScript
mit
extesy/hoverzoom,extesy/hoverzoom
7b52bf19eda8d52be5ae8db7fb1d1544912e1794
client/index.js
client/index.js
var document = require('global/document'); var value = require('observ'); var struct = require('observ-struct'); var Delegator = require('dom-delegator'); var mainLoop = require('main-loop'); var h = require('virtual-hyperscript'); var MultipleEvent = require('geval/multiple'); var changeEvent = require('value-event/change'); var courses = require('./catalog'); var state = struct({ query: value(''), events: MultipleEvent(['change']) }); state.events.change(function(data) { state.query.set(data.query); }); Delegator(); var loop = mainLoop(state(), render); document.body.appendChild(loop.target); state(loop.update); function render(state) { var results = courses.filter(function(course) { return course.name.toLowerCase().indexOf(state.query) >= 0 || course.code.toLowerCase().indexOf(state.query) >= 0; }); var ret = []; var inputField = h('input', { type: 'text', name: 'query', value: String(state.query), 'ev-event': changeEvent(state.events.change), autofocus: true }); results.forEach(function(course) { ret.push(h('li', [ h('h3', [ h('span.code', course.code), h('span', ' ' + course.name) ]), h('p', course.description) ])); }); return h('div', [ inputField, h('ul', ret) ]); }
var document = require('global/document'); var value = require('observ'); var struct = require('observ-struct'); var Delegator = require('dom-delegator'); var mainLoop = require('main-loop'); var h = require('virtual-hyperscript'); var MultipleEvent = require('geval/multiple'); var changeEvent = require('value-event/change'); var courses = require('./catalog'); var state = struct({ query: value(''), events: MultipleEvent(['change']) }); state.events.change(function(data) { state.query.set(data.query); }); Delegator(); var loop = mainLoop(state(), render); document.body.appendChild(loop.target); state(loop.update); function render(state) { var results = courses.filter(function(course) { return course.name.toLowerCase().indexOf(state.query) >= 0 || course.code.toLowerCase().indexOf(state.query) >= 0; }); var ret = []; var inputField = h('input', { type: 'search', name: 'query', value: String(state.query), 'ev-event': changeEvent(state.events.change), autofocus: true }); results.forEach(function(course) { ret.push(h('li', [ h('h3', [ h('span.code', course.code), h('span', ' ' + course.name) ]), h('p', course.description) ])); }); return h('div', [ inputField, h('ul', ret) ]); }
Change search field type to "search"
Change search field type to "search" This is like "text" except that a little "x" button appears so that one can easily clear the field. Also, on mobile browsers, the action button on the keyboard will display "Search" instead of just "Go". Old browsers will gracefully fallback to "text" anyways, so this is a progressive enchancement.
JavaScript
mit
KenanY/course-search,KenanY/course-search
4177d6050ef41c70dc25a34ee32e43984e77f461
visualizer/index.js
visualizer/index.js
'use strict' const fg = require('d3-fg') const render = require('nanohtml') const morphdom = require('morphdom') const debounce = require('debounce') const createActions = require('./actions') const createState = require('./state') const graph = require('./cmp/graph')(render) const ui = require('./cmp/ui')(render) module.exports = function (trees, opts) { opts = opts || {} const { kernelTracing } = opts const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init']) const chart = graph() const tree = trees.unmerged // default view const categorizer = !kernelTracing && graph.v8cats const flamegraph = fg({ categorizer, tree, exclude: Array.from(exclude), element: chart }) const { colors } = flamegraph window.addEventListener('resize', debounce(() => { const width = document.body.clientWidth * 0.89 flamegraph.width(width).update() chart.querySelector('svg').setAttribute('width', width) }, 150)) const state = createState({colors, trees, exclude, kernelTracing, title: opts.title}) const actions = createActions({flamegraph, state}, (state) => { morphdom(iface, ui({state, actions})) }) const iface = ui({state, actions}) document.body.appendChild(chart) document.body.appendChild(iface) }
'use strict' const fg = require('d3-fg') const render = require('nanohtml') const morphdom = require('morphdom') const debounce = require('debounce') const createActions = require('./actions') const createState = require('./state') const graph = require('./cmp/graph')(render) const ui = require('./cmp/ui')(render) module.exports = function (trees, opts) { opts = opts || {} const { kernelTracing } = opts const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init']) const chart = graph() const tree = trees.unmerged // default view const categorizer = !kernelTracing && graph.v8cats const flamegraph = fg({ categorizer, tree, exclude: Array.from(exclude), element: chart, topOffset: 55 }) const { colors } = flamegraph window.addEventListener('resize', debounce(() => { const width = document.body.clientWidth * 0.89 flamegraph.width(width).update() chart.querySelector('svg').setAttribute('width', width) }, 150)) const state = createState({colors, trees, exclude, kernelTracing, title: opts.title}) const actions = createActions({flamegraph, state}, (state) => { morphdom(iface, ui({state, actions})) }) const iface = ui({state, actions}) document.body.appendChild(chart) document.body.appendChild(iface) }
Add top offset to prevent top bar from cropping the top stack
Add top offset to prevent top bar from cropping the top stack
JavaScript
mit
davidmarkclements/0x
e9bd0c16bda4221a420a9206c239e06b44a5911f
addon/index.js
addon/index.js
import Ember from 'ember'; Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, { id: "ember-getowner-polyfill.import" }); export default Ember.getOwner;
import Ember from 'ember'; Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, { id: "ember-getowner-polyfill.import", until: '3.0.0' }); export default Ember.getOwner;
Add option.until to prevent extra deprecation
Add option.until to prevent extra deprecation
JavaScript
mit
rwjblue/ember-getowner-polyfill,rwjblue/ember-getowner-polyfill
5ddc15870172cabe4a362fa338dd804f6b1264e2
src/components/Media/Media.js
src/components/Media/Media.js
import React from 'react'; import classnames from 'classnames'; const Media = (props) => { const children = props.children; return ( <div className={classnames('ui-media')}> {children} </div> ); }; Media.propTypes = { children: React.PropTypes.node, }; export default Media;
import React from 'react'; import classnames from 'classnames'; const Media = ({ compact, children }) => { const className = classnames('ui-media', { 'ui-media-compact': compact, }); return ( <div className={className}> {children} </div> ); }; Media.propTypes = { children: React.PropTypes.node, compact: React.PropTypes.bool, }; Media.defaultProps = { compact: false, children: null, }; export default Media;
Introduce compact prop for media component
Introduce compact prop for media component
JavaScript
mit
wundery/wundery-ui-react,wundery/wundery-ui-react
85367a62999ef6be0e34556cd71d54871c98dc19
worker/index.js
worker/index.js
'use strict'; const config = require('config'); const logger = require('../modules').logger; const rollbarHelper = require('../modules').rollbarHelper; const invalidator = require('./invalidator'); const opendata = require('./opendata'); function shutdown() { logger.info('[WORKER] Ending'); setTimeout(process.exit, config.worker.exit_timeout); } if (!module.parent) { require('../modules').mongooseHelper.connect() .then(() => rollbarHelper.init()) .then(() => { invalidator.start(); opendata.start(); logger.info('[WORKER] Started'); }) .catch(err => { logger.error(err, '[WORKER] Uncaught error'); rollbarHelper.rollbar.handleError(err, '[WORKER] Uncaught exception'); shutdown(); }); process.on('SIGTERM', shutdown); } module.exports = { opendata };
'use strict'; const config = require('config'); const logger = require('../modules').logger; const mongooseHelper = require('../modules').mongooseHelper; const rollbarHelper = require('../modules').rollbarHelper; const invalidator = require('./invalidator'); const opendata = require('./opendata'); function shutdown() { logger.info('[WORKER] Ending'); setTimeout(process.exit, config.worker.exit_timeout); } if (!module.parent) { rollbarHelper.init() .then(() => mongooseHelper.connect()) .then(() => { invalidator.start(); opendata.start(); logger.info('[WORKER] Started'); }) .catch(err => { logger.error(err, '[WORKER] Uncaught error'); rollbarHelper.rollbar.handleError(err, '[WORKER] Uncaught exception'); shutdown(); }); process.on('SIGTERM', shutdown); } module.exports = { opendata };
Initialize rollbar before mongoose in worker
Initialize rollbar before mongoose in worker
JavaScript
mit
carparker/carparker-server
49bd3bf427f57fa65a9b04bcbb5af9d654258120
providers/providers.js
providers/providers.js
var path = require('path'); var _ = require('underscore')._; module.exports = function(app, settings) { var providers = {}; for (var p in settings.providers) { // TODO :express better providers[p] = require('./' + path.join(p, 'index'))(app, settings); } app.get('/provider', function(req, res) { res.send({ status: true, provider: _.keys(settings.providers) }); }); app.get('/provider/:provider', function(req, res) { if (providers[req.params.provider]) { providers[req.params.provider].objects(function(objects) { res.send(objects); }); } else { // @TODO: better error handling here. // Currently allows graceful downgrade of missing S3 information // but ideally client side JS would not request for the S3 provider // at all if it is not enabled. res.send([]); } }); };
var path = require('path'); var _ = require('underscore')._; module.exports = function(app, settings) { var providers = {}; for (var p in settings.providers) { // TODO :express better providers[p] = require('./' + path.join(p, 'index'))(app, settings); } app.get('/provider', function(req, res) { res.send({ status: true, provider: _.keys(settings.providers) }); }); /** * This endpoint is a backbone.js collection compatible REST endpoint * providing datasource model objects. The models provided are read-only * and cannot be created, saved or destroyed back to the server. */ app.get('/provider/:provider', function(req, res) { if (providers[req.params.provider]) { providers[req.params.provider].objects(function(objects) { res.send(objects); }); } else { // @TODO: better error handling here. // Currently allows graceful downgrade of missing S3 information // but ideally client side JS would not request for the S3 provider // at all if it is not enabled. res.send([]); } }); };
Add comment which notes that the provider endpoint is a backbone.js collection endpoint as well.
Add comment which notes that the provider endpoint is a backbone.js collection endpoint as well.
JavaScript
bsd-3-clause
nyimbi/tilemill,mbrukman/tilemill,mbrukman/tilemill,isaacs/tilemill,mbrukman/tilemill,MappingKat/tilemill,paulovieira/tilemill-clima,Zhao-Qi/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,mbrukman/tilemill,paulovieira/tilemill-clima,nyimbi/tilemill,MappingKat/tilemill,makinacorpus/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,isaacs/tilemill,mbrukman/tilemill,tilemill-project/tilemill,tizzybec/tilemill,makinacorpus/tilemill,MappingKat/tilemill,MappingKat/tilemill,florianf/tileoven,Zhao-Qi/tilemill,tizzybec/tilemill,tilemill-project/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,tizzybec/tilemill,fxtentacle/tilemill,fxtentacle/tilemill,paulovieira/tilemill-clima,Zhao-Qi/tilemill,Zhao-Qi/tilemill,fxtentacle/tilemill,Zhao-Qi/tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,Teino1978-Corp/Teino1978-Corp-tilemill,nyimbi/tilemill,fxtentacle/tilemill,isaacs/tilemill,nyimbi/tilemill,tizzybec/tilemill,paulovieira/tilemill-clima,tilemill-project/tilemill,tizzybec/tilemill,florianf/tileoven,nyimbi/tilemill,paulovieira/tilemill-clima,florianf/tileoven,fxtentacle/tilemill,MappingKat/tilemill
a37853c97ad9850e6bae0adf254399b3d6d29424
src/suspense.js
src/suspense.js
import { Component } from './component'; import { createElement } from './create-element'; // having a "custom class" here saves 50bytes gzipped export function s(props) {} s.prototype = new Component(); s.prototype._childDidSuspend = function(e) { this.setState({ _loading: true }); const cb = () => { this.setState({ _loading: false }); }; // Suspense ignores errors thrown in Promises as this should be handled by user land code e.then(cb, cb); }; s.prototype.render = function(props, state) { return state._loading ? props.fallback : props.children; }; // exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped // TODO: does this add the need of a displayName? export const Suspense = s; export function lazy(loader) { let prom; let component; let error; return function L(props) { if (!prom) { prom = loader(); prom.then( ({ default: c }) => { component = c; }, e => error = e, ); } if (error) { throw error; } if (!component) { throw prom; } return createElement(component, props); }; }
import { Component } from './component'; import { createElement } from './create-element'; // having a "custom class" here saves 50bytes gzipped export function s(props) {} s.prototype = new Component(); /** * @param {Promise} promise The thrown promise */ s.prototype._childDidSuspend = function(promise) { this.setState({ _loading: true }); const cb = () => { this.setState({ _loading: false }); }; // Suspense ignores errors thrown in Promises as this should be handled by user land code promise.then(cb, cb); }; s.prototype.render = function(props, state) { return state._loading ? props.fallback : props.children; }; // exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped // TODO: does this add the need of a displayName? export const Suspense = s; export function lazy(loader) { let prom; let component; let error; return function L(props) { if (!prom) { prom = loader(); prom.then( ({ default: c }) => { component = c; }, e => error = e, ); } if (error) { throw error; } if (!component) { throw prom; } return createElement(component, props); }; }
Add some jsdoc to _childDidSuspend
Add some jsdoc to _childDidSuspend
JavaScript
mit
developit/preact,developit/preact
bf79820c7a37188c9e66c912eb9a66ad45ecc7ad
app/javascript/app/pages/sectors-agriculture/sectors-agricuture-selectors.js
app/javascript/app/pages/sectors-agriculture/sectors-agricuture-selectors.js
import { createSelector } from 'reselect'; // import omit from 'lodash/omit'; // import qs from 'query-string'; const getSections = routeData => routeData.route.sections || null; // const getSearch = routeData => routeData.location.search || null; // const getHash = routeData => routeData.hash || null; // const getRoutes = routeData => routeData.route.routes || null; export const getAnchorLinks = createSelector([getSections], sections => sections.filter(route => route.anchor).map(route => ({ label: route.label, path: route.path, hash: route.hash, component: route.component })) ); // export const getRouteLinks = createSelector( // [getRoutes, getHash, getSearch], // (routes, hash, search) => // routes && // routes.filter(r => r.anchor).map(route => ({ // label: route.label, // path: route.path, // search: qs.stringify(omit(qs.parse(search), 'search')), // we want to reset the search on tabs change // hash // })) // ); export default { getAnchorLinks // getRouteLinks };
import { createSelector } from 'reselect'; const getSections = routeData => routeData.route.sections || null; export const getAnchorLinks = createSelector([getSections], sections => sections.filter(route => route.anchor).map(route => ({ label: route.label, path: route.path, hash: route.hash, component: route.component })) ); export default { getAnchorLinks };
Remove commented code from agriculture selectors
Remove commented code from agriculture selectors
JavaScript
mit
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
ed3c72146dad8baa293755c8732f3ad0ef9581f2
eloquent_js/chapter11/ch11_ex02.js
eloquent_js/chapter11/ch11_ex02.js
function Promise_all(promises) { return new Promise((resolve, reject) => { let ctr = promises.length; let resArray = []; if (ctr === 0) resolve(resArray); for (let idx = 0; idx < promises.length; ++idx) { promises[idx].then(result => { resArray[idx] = result; --ctr; if (ctr === 0) resolve(resArray); }, reject); } }); }
function Promise_all(promises) { return new Promise((resolve, reject) => { let result = []; let unresolved = promises.length; if (unresolved == 0) resolve(result); for (let i = 0; i < promises.length; ++i) { promises[i] .then(value => { result[i] = value; --unresolved; if (unresolved == 0) resolve(result); }) .catch(error => reject(error)); } }); }
Add chapter 11, exercise 2
Add chapter 11, exercise 2
JavaScript
mit
bewuethr/ctci
334795d1f6a881f9377bb9c436641a422431153f
modules/cloud-portal-server/src/main/resources/public/static/dist/js/portal.js
modules/cloud-portal-server/src/main/resources/public/static/dist/js/portal.js
$(function() { $("form :button").each(function(){ var button = $(this); if ($(button).attr('id') == 'cancel') { $(button).click(function(e){ e.preventDefault(); history.back(); }); } else { $(button).click(function(e){ var buttonId = $(button).attr('id'); if (typeof buttonId !== 'undefined') { e.preventDefault(); var form = $(this).closest('form'); var originalActionUrl = $(form).attr('action'); if ($(form).valid()) { if (buttonId == "plan" || buttonId == "apply") { $('#myModal').modal('toggle'); } var submit = true; if (buttonId.startsWith('delete')) { submit = confirm('Do you really want to delete this item?'); if (submit) { $('#myModal').modal('toggle'); } } if (submit) { $(form).attr('action', originalActionUrl + "/" + buttonId); $(form).submit(); $(form).attr('action', originalActionUrl); } } } }); } }); $('#datatable').DataTable({ responsive: true, order: [[ 0, 'desc' ]] }); });
$(function() { $("form :button").each(function(){ var button = $(this); if ($(button).attr('id') == 'cancel') { $(button).click(function(e){ e.preventDefault(); history.back(); }); } else { $(button).click(function(e){ var buttonId = $(button).attr('id'); if (typeof buttonId !== 'undefined') { e.preventDefault(); var form = $(this).closest('form'); var originalActionUrl = $(form).attr('action'); if ($(form).valid()) { if (buttonId == "plan" || buttonId == "apply") { $('#myModal').modal('toggle'); } var submit = true; if (buttonId.startsWith('delete')) { submit = confirm('Do you really want to delete this item?'); if (submit) { $('#myModal').modal('toggle'); } } if (submit) { $(form).attr('action', originalActionUrl + "/" + buttonId); $(form).submit(); $(form).attr('action', originalActionUrl); } } } }); } }); $('#datatable').DataTable({ responsive: true, order: [[ 0, 'asc' ]] }); });
Fix for vm list ordering
Fix for vm list ordering
JavaScript
mit
chrisipa/cloud-portal,chrisipa/cloud-portal,chrisipa/cloud-portal
ea768085c12ef4ea8551510bd3ab606a61115967
get-file.js
get-file.js
var fs = require('fs'); var path = require('path'); var md = require('cli-md'); module.exports = function (filepath) { return md(fs.readFileSync(filepath, 'utf8')) .replace(/&#39;/g, "'") .replace(/&quot;/g, '"') .replace(/&lt;/g, '<') .replace(/&gt;/g, '<'); };
var fs = require('fs'); var path = require('path'); var md = require('cli-md'); module.exports = function (filepath) { return md(fs.readFileSync(filepath, 'utf8')) .replace(/&#39;/g, "'") .replace(/&quot;/g, '"') .replace(/&lt;/g, '<') .replace(/&gt;/g, '<'); };
Fix greate/less than HTML entity in problem description
Fix greate/less than HTML entity in problem description
JavaScript
mit
soujiro27/javascripting,ubergrafik/javascripting,SomeoneWeird/javascripting,jaredhensley/javascripting,d9magai/javascripting,montogeek/javascripting,liyuqi/javascripting,nodeschool-no/javascripting,braday/javascripting,michaelgrilo/javascripting,RichardLitt/javascripting,barberboy/javascripting,agrimm/javascripting,ymote/javascripting,ipelekhan/javascripting,CLAV1ER/javascripting,LindsayElia/javascripting,ledsun/javascripting,victorperin/javascripting,aijiekj/javascripting,he11yeah/javascripting,Aalisha/javascripting,samilokan/javascripting,gcbeyond/javascripting,marocchino/javascripting,thenaughtychild/javascripting,sethvincent/javascripting,NgaNguyenDuy/javascripting,a0viedo/javascripting,claudiopro/javascripting,MatthewDiana/javascripting
c4bb41471441da921da9c2dc9515e662619fef5b
public/javascripts/checker.js
public/javascripts/checker.js
var socket = io.connect('/'); var waitMilliSec = 1000; var oldJavaCode = ''; var oldClassName = ''; socket.on('byte_code', function(data) { $('#output_bc').val(data.code); }); socket.on('wrong', function(data) { $('#output_bc').val(data.err); }); $(function() { var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), { mode: 'clike', lineNumbers: true }); var idleIntervalId = setInterval(function() { newJavaCode = inputJavaCM.getValue(); newClassName = $('#class_name').val(); checkDiff(newJavaCode, newClassName); } , waitMilliSec); function checkDiff(newJavaCode, newClassName) { if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) { socket.emit('code_sent', { code: newJavaCode, className: newClassName }); oldJavaCode = newJavaCode; oldClassName = newClassName; } } });
var socket = io.connect('/'); var waitMilliSec = 1000; var oldJavaCode = ''; var oldClassName = ''; var outputBcCM; socket.on('byte_code', function(data) { outputBcCM.setValue(data.code); }); socket.on('wrong', function(data) { outputBcCM.setValue(data.err); }); $(function() { var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), { mode: 'clike', lineNumbers: true }); outputBcCM = CodeMirror.fromTextArea(document.getElementById('output_bc'), { mode: 'clike', lineNumbers: true }); var idleIntervalId = setInterval(function() { newJavaCode = inputJavaCM.getValue(); newClassName = $('#class_name').val(); checkDiff(newJavaCode, newClassName); } , waitMilliSec); function checkDiff(newJavaCode, newClassName) { if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) { socket.emit('code_sent', { code: newJavaCode, className: newClassName }); oldJavaCode = newJavaCode; oldClassName = newClassName; } } });
Apply CodeMirror to output textarea.
Apply CodeMirror to output textarea.
JavaScript
mit
Java2ByteCode/InstantBytecode,Java2ByteCode/InstantBytecode
4690efb9543e0fffc11c5330dc93c75482c3e9b5
kolibri/plugins/coach/assets/src/state/mutations/lessonsMutations.js
kolibri/plugins/coach/assets/src/state/mutations/lessonsMutations.js
export function SET_CLASS_LESSONS(state, lessons) { state.pageState.lessons = lessons; } export function SET_CURRENT_LESSON(state, lesson) { state.pageState.currentLesson = lesson; } export function SET_LEARNER_GROUPS(state, learnerGroups) { state.pageState.learnerGroups = learnerGroups; }
export function SET_CLASS_LESSONS(state, lessons) { state.pageState.lessons = lessons; } export function SET_CURRENT_LESSON(state, lesson) { state.pageState.currentLesson = { ...lesson }; } export function SET_LEARNER_GROUPS(state, learnerGroups) { state.pageState.learnerGroups = learnerGroups; }
Make copy before setting current lesson
Make copy before setting current lesson
JavaScript
mit
DXCanas/kolibri,christianmemije/kolibri,benjaoming/kolibri,christianmemije/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,jonboiser/kolibri,indirectlylit/kolibri,jonboiser/kolibri,indirectlylit/kolibri,benjaoming/kolibri,lyw07/kolibri,DXCanas/kolibri,benjaoming/kolibri,christianmemije/kolibri,indirectlylit/kolibri,christianmemije/kolibri,benjaoming/kolibri,learningequality/kolibri,learningequality/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,DXCanas/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,jonboiser/kolibri,lyw07/kolibri,jonboiser/kolibri
d6da2ba83bb7dbcdaa73f4df45927a50fe8f8e15
backend/Log.js
backend/Log.js
var Log = require("log4js"); var Utils = require("./Utils"); Log.configure({ "replaceConsole": true, "appenders": process.env.DEBUG ? [{"type": "console"}] : [ { "type": "console" }, { "type": "logLevelFilter", "level": "ERROR", "appender": { "type": "smtp", "recipients": process.env.EMAIL, "sender": "info@ideacolorthemes.org", "sendInterval": process.env.LOG_EMAIL_INTERVAL || 30, "transport": "SMTP", "SMTP": Utils.getEmailConfig() } } ] }); module.exports = Log.getLogger();
var Log = require("log4js"); var Utils = require("./Utils"); Log.configure({ "replaceConsole": true, "appenders": process.env.DEBUG ? [{"type": "console"}] : [ { "type": "console" }, { "type": "logLevelFilter", "level": "ERROR", "appender": { "type": "smtp", "recipients": process.env.EMAIL, "sender": process.env.EMAIL, "sendInterval": process.env.LOG_EMAIL_INTERVAL || 30, "transport": "SMTP", "SMTP": Utils.getEmailConfig() } } ] }); module.exports = Log.getLogger();
Fix for error reporting email
Fix for error reporting email
JavaScript
mit
y-a-r-g/color-themes,y-a-r-g/color-themes
d3d7932eb1c067b2a403e0260c87192940565964
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var nodemon = require('gulp-nodemon'); gulp.task('mock-server', function() { nodemon({ script: 'server.js' , ext: 'js json' , env: { 'NODE_ENV': 'development' } }) });
var gulp = require('gulp'); var nodemon = require('gulp-nodemon'); gulp.task('default', function() { nodemon({ script: 'server.js' , ext: 'js json' , env: { 'NODE_ENV': 'development' } }) });
Set gulp task as default
Set gulp task as default
JavaScript
mit
isuru88/lazymine-mock-server
9765f97a3c71483ef3793b7990ec73b6909edc9c
gulpfile.js
gulpfile.js
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.sass('app.scss'); //mix.less(''); mix.copy( './public/js/libs/semantic/dist/themes', 'public/css/themes' ); mix.styles([ './public/js/libs/semantic/dist/semantic.min.css' ], 'public/css/nestor.css'); // mix.scripts([ // './resources/assets/bower/jquery/dist/jquery.js', // './resources/assets/bower/bootstrap-sass-official/assets/javascripts/bootstrap.min.js' // ], // 'public/js/nestor.js'); });
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.sass('app.scss'); //mix.less(''); mix.copy( './public/js/libs/semantic/dist/themes', './public/css/themes' ); mix.styles([ './public/js/libs/semantic/dist/semantic.min.css' ], 'public/css/nestor.css'); // mix.scripts([ // './resources/assets/bower/jquery/dist/jquery.js', // './resources/assets/bower/bootstrap-sass-official/assets/javascripts/bootstrap.min.js' // ], // 'public/js/nestor.js'); });
Use same syntax for all assets
Use same syntax for all assets
JavaScript
mit
nestor-qa/nestor,kinow/nestor,kinow/nestor,nestor-qa/nestor,nestor-qa/nestor,nestor-qa/nestor,kinow/nestor,kinow/nestor
e1fb651837436053b24b9198a5d62ba869090297
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var uglify = require('gulp-uglify'); gulp.task('default', function() { gulp.src('lib/fs.js') .pipe(uglify()) .pipe(gulp.dest('build')); });
var gulp = require('gulp'); var uglify = require('gulp-uglify'); var babel = require('gulp-babel'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); gulp.task('default', function() { gulp.src('src/fs.js') .pipe(sourcemaps.init()) .pipe(babel()) .pipe(uglify()) .pipe(rename('fs.min.js')) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')); });
Update default task for compile prod code
1.2.2: Update default task for compile prod code
JavaScript
mit
wangpin34/fs-h5,wangpin34/fs-h5
2e8ab65088ba8acd7ddda01e4cfc5ba0f0fcdc1a
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp') , jshint = require('gulp-jshint') , nodemon = require('gulp-nodemon') , paths ; paths = { projectScripts: ['./bin/www', '**/*.js', '!node_modules/**', '!public/**'] }; gulp.task('default', ['develop'], function () { }); gulp.task('develop', function () { nodemon({ script: 'bin/www', ext: 'js' }) .on('change', ['lint']) .on('restart', function () { console.log('Restared!'); }); }); gulp.task('lint', function () { gulp.src(paths.projectScripts) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); });
'use strict'; var gulp = require('gulp') , jshint = require('gulp-jshint') , nodemon = require('gulp-nodemon') , paths ; paths = { projectScripts: ['./bin/www', '**/*.js', '!node_modules/**', '!public/**'] }; gulp.task('default', ['develop'], function () { }); gulp.task('develop', function () { nodemon({ script: 'bin/www', ext: 'js' }) .on('change', ['hint']) .on('restart', function () { console.log('Restared!'); }); }); gulp.task('hint', function () { gulp.src(paths.projectScripts) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')); });
Rename lint task to hint
Rename lint task to hint
JavaScript
mit
Hilzu/SecureChat
83cc95b851a39cd3952fa105272a750e0a147dee
addons/notes/src/__tests__/index.js
addons/notes/src/__tests__/index.js
import addons from '@storybook/addons'; import { withNotes } from '..'; jest.mock('@storybook/addons'); describe('Storybook Addon Notes', () => { it('should inject info', () => { const channel = { emit: jest.fn() }; addons.getChannel.mockReturnValue(channel); const getStory = jest.fn(); const context = {}; const decoratedStory = withNotes('hello')(getStory); decoratedStory(context); expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello'); expect(getStory).toHaveBeenCalledWith(context); }); });
import addons from '@storybook/addons'; import { withNotes } from '..'; jest.mock('@storybook/addons'); describe('Storybook Addon Notes', () => { it('should inject text from `notes` parameter', () => { const channel = { emit: jest.fn() }; addons.getChannel.mockReturnValue(channel); const getStory = jest.fn(); const context = { parameters: { notes: 'hello' } }; withNotes(getStory, context); expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello'); expect(getStory).toHaveBeenCalledWith(context); }); it('should inject markdown from `notes.markdown` parameter', () => { const channel = { emit: jest.fn() }; addons.getChannel.mockReturnValue(channel); const getStory = jest.fn(); const context = { parameters: { notes: { markdown: '# hello' } } }; withNotes(getStory, context); expect(channel.emit).toHaveBeenCalledWith( 'storybook/notes/add_notes', expect.stringContaining('<h1 id="hello">hello</h1>') ); expect(getStory).toHaveBeenCalledWith(context); }); it('should inject info (deprecated API)', () => { const channel = { emit: jest.fn() }; addons.getChannel.mockReturnValue(channel); const getStory = jest.fn(); const context = { parameters: {} }; const decoratedStory = withNotes('hello')(getStory); decoratedStory(context); expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello'); expect(getStory).toHaveBeenCalledWith(context); }); });
Update tests with new API
Update tests with new API
JavaScript
mit
rhalff/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,rhalff/storybook
721faf4dd71bef6ee170e3b029dc52ac8f9055a1
src/sprites/object/PineCone/place.js
src/sprites/object/PineCone/place.js
import { treeGrow as growChance } from '../../../game-data/chances'; import { tryChance } from '../../../utils'; import { fastMap } from '../../../world'; import objectPool from '../../../object-pool'; import Phaser from 'phaser'; import Tree from '../Tree'; export default function place() { this.placed = true; this.changeType('planted-pine-cone'); this.game.time.events.add(Phaser.Timer.SECOND * 5, function() { if (this.destroyed) return; const playerTile = this.game.state.states.Game.player.tile; const thisTile = this.tile; if ( (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) && fastMap[thisTile.x + ',' + thisTile.y].length === 1 && // this pine cone should be only thing on tile tryChance(growChance) ) { objectPool.new('tree', Tree, { game: this.game, x: this.x, y: this.y, }); this.destroy(); } else { place.call(this); } }, this); }
import { treeGrow as growChance } from '../../../game-data/chances'; import { tryChance } from '../../../utils'; import { fastMap } from '../../../world'; import objectPool from '../../../object-pool'; import Phaser from 'phaser'; import Tree from '../Tree'; export default function place() { this.placed = true; this.changeType('planted-pine-cone'); this.game.time.events.add(Phaser.Timer.SECOND * 5, function() { if (this.destroyed) return; const playerTile = this.game.state.states.Game.player.tile; const thisTile = this.tile; if ( (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) && fastMap[thisTile.y][thisTile.x].length === 1 && // this pine cone should be only thing on tile tryChance(growChance) ) { objectPool.new('tree', Tree, { game: this.game, x: this.x, y: this.y, }); this.destroy(); } else { place.call(this); } }, this); }
Fix using old map format
Fix using old map format
JavaScript
mit
ThomasMays/incremental-forest,ThomasMays/incremental-forest
1d42cae605889f5bab9f7b773561f9a493c32a6a
src/js/helpers/SecretsUtil.js
src/js/helpers/SecretsUtil.js
var SecretsUtil = { /** * This function checks if the environment value is a reference to a secret * and if yes, it cross-references the secret with the `secrets` property * in `allFields` and it returns the secret reference name. * * @param {Object|String} value - The environment variable value * @param {Object} allFields - The full object definition or all form fields * @returns {String} Returns the string for the environment value */ getSecretReferenceOfEnvValue: function (value, allFields) { if (typeof value !== "object") { return value; } let placeholder; const {secret} = value; const secretSource = allFields[`secrets.${secret}.source`] || (allFields.secrets && allFields.secrets[secret] && allFields.secrets[secret].source); if (!secretSource) { placeholder = 'Invalid Secret Reference'; if (!secret) { placeholder = 'Invalid Value'; } } else { placeholder = `Secret "${secretSource}"`; } return placeholder; } }; export default SecretsUtil;
var SecretsUtil = { /** * This function checks if the environment value is a reference to a secret * and if yes, it cross-references the secret with the `secrets` property * in `allFields` and it returns the secret reference name. * * @param {Object|String} value - The environment variable value * @param {Object} allFields - The full object definition or all form fields * @returns {String} Returns the string for the environment value */ getSecretReferenceOfEnvValue: function (value, allFields) { if (typeof value !== "object") { return value; } let placeholder; const {secret} = value; const secretSource = allFields[`secrets.${secret}.source`] || (allFields.secrets && allFields.secrets[secret] && allFields.secrets[secret].source); if (!secretSource) { placeholder = "Invalid Secret Reference"; if (!secret) { placeholder = "Invalid Value"; } } else { placeholder = `Secret "${secretSource}"`; } return placeholder; } }; export default SecretsUtil;
Replace single with double quotes
Replace single with double quotes
JavaScript
apache-2.0
mesosphere/marathon-ui,mesosphere/marathon-ui
ff58f96f6579d583f8f44db8e9c91260cf2ae5a7
ocw-ui/frontend-new/test/spec/filters/isodatetomiddleendian.js
ocw-ui/frontend-new/test/spec/filters/isodatetomiddleendian.js
'use strict'; describe('Filter: ISODateToMiddleEndian', function () { // load the filter's module beforeEach(module('ocwUiApp')); // initialize a new instance of the filter before each test var ISODateToMiddleEndian; beforeEach(inject(function ($filter) { ISODateToMiddleEndian = $filter('ISODateToMiddleEndian'); })); it('should return the input prefixed with "ISODateToMiddleEndian filter:"', function () { var text = 'angularjs'; expect(ISODateToMiddleEndian(text)).toBe('ISODateToMiddleEndian filter: ' + text); }); });
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: *www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ 'use strict'; describe('Filter: ISODateToMiddleEndian', function () { // load the filter's module beforeEach(module('ocwUiApp')); // initialize a new instance of the filter before each test var ISODateToMiddleEndian; beforeEach(inject(function ($filter) { ISODateToMiddleEndian = $filter('ISODateToMiddleEndian'); })); it('should return the input prefixed with "ISODateToMiddleEndian filter:"', function () { var text = 'angularjs'; expect(ISODateToMiddleEndian(text)).toBe('ISODateToMiddleEndian filter: ' + text); }); });
Add ASF license headers to filter tests
Add ASF license headers to filter tests
JavaScript
apache-2.0
kwhitehall/climate,pwcberry/climate,MJJoyce/climate,jarifibrahim/climate,riverma/climate,lewismc/climate,apache/climate,apache/climate,huikyole/climate,MJJoyce/climate,agoodm/climate,agoodm/climate,jarifibrahim/climate,MBoustani/climate,lewismc/climate,Omkar20895/climate,MJJoyce/climate,agoodm/climate,lewismc/climate,jarifibrahim/climate,pwcberry/climate,agoodm/climate,riverma/climate,MBoustani/climate,lewismc/climate,Omkar20895/climate,lewismc/climate,pwcberry/climate,apache/climate,kwhitehall/climate,riverma/climate,Omkar20895/climate,agoodm/climate,kwhitehall/climate,MJJoyce/climate,pwcberry/climate,MBoustani/climate,huikyole/climate,Omkar20895/climate,huikyole/climate,kwhitehall/climate,riverma/climate,riverma/climate,MBoustani/climate,MBoustani/climate,pwcberry/climate,apache/climate,huikyole/climate,Omkar20895/climate,jarifibrahim/climate,MJJoyce/climate,jarifibrahim/climate,huikyole/climate,apache/climate
7b8c50c247a6ea4b382fb59f83c0c2a7473b9fbc
src/Input/TouchInput.js
src/Input/TouchInput.js
function TouchInput(inputController) { this.inputController = inputController; } TouchInput.prototype.listen = function() { document.addEventListener('touchstart', this.startTouch.bind(this)); document.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) { this.xStart = event.touches[0].clientX; this.yStart = event.touches[0].clientY; }; TouchInput.prototype.detectSwipe = function(event) { if( this.xStart === null || this.yStart === null) { return; } var xEnd = event.touches[0].clientX; var yEnd = event.touches[0].clientY; var deltaX = xEnd - this.xStart; var deltaY = yEnd - this.yStart; var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY); if(isHorizontalSwipe) { deltaX < 0 ? this.inputController.left(): this.inputController.right(); } else if(deltaY > 0) { this.inputController.down(); } this.xStart = null; this.yStart = null; };
function TouchInput(inputController, element) { this.inputController = inputController; this.element = typeof element !== 'undefined' ? element : document; } TouchInput.prototype.listen = function() { this.element.addEventListener('touchstart', this.startTouch.bind(this)); this.element.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) { this.xStart = event.touches[0].clientX; this.yStart = event.touches[0].clientY; }; TouchInput.prototype.detectSwipe = function(event) { if( this.xStart === null || this.yStart === null) { return; } var xEnd = event.touches[0].clientX; var yEnd = event.touches[0].clientY; var deltaX = xEnd - this.xStart; var deltaY = yEnd - this.yStart; var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY); if(isHorizontalSwipe) { deltaX < 0 ? this.inputController.left(): this.inputController.right(); } else if(deltaY > 0) { this.inputController.down(); } this.xStart = null; this.yStart = null; };
Add element binding to touch input
Add element binding to touch input
JavaScript
mit
mnito/factors-game,mnito/factors-game
e3f9fd07b08f30067d055dcbb1ce2558c776f81e
src/controllers/SpotifyController.js
src/controllers/SpotifyController.js
if (!!document.querySelector('#app-player')) { // Old Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#app-player', playStateSelector: '#play-pause', playStateClass: 'playing', playPauseSelector: '#play-pause', nextSelector: '#next', previousSelector: '#previous', titleSelector: '#track-name', artistSelector: '#track-artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1); }); } else { // New Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#main', playStateSelector: '#play', playStateClass: 'playing', playPauseSelector: '#play', nextSelector: '#next', previousSelector: '#previous', titleSelector: '.caption .track', artistSelector: '.caption .artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1); }); }
var config = { supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, playStateClass: 'playing', nextSelector: '#next', previousSelector: '#previous' } if (document.querySelector('#app-player')) { // Old Player config.artworkImageSelector = '#cover-art .sp-image-img'; config.frameSelector = '#app-player'; config.playStateSelector = '#play-pause'; config.playPauseSelector = '#play-pause'; config.titleSelector = '#track-name'; config.artistSelector = '#track-artist'; } else { // New Player config.artworkImageSelector = '#large-cover-image'; config.frameSelector = '#main'; config.playStateSelector = '#play'; config.playPauseSelector = '#pause'; config.titleSelector = '.caption .track'; config.artistSelector = '.caption .artist'; } controller = new BasicController(config); controller.override('getAlbumArt', function() { var img = this.doc().querySelector(this.artworkImageSelector); return img && img.style.backgroundImage.slice(5, -2); });
Fix album art retrieved from Spotify
Fix album art retrieved from Spotify Remove double quotes around image URL retrieved from Spotify by slicing one character more from left and one character more from right. Also, remove redundant code and null errors to console when element is not found. Signed-off-by: Tomas Slusny <71c4488fd0941e24cd13e3ad13ef1eb0a5fe5168@gmail.com>
JavaScript
agpl-3.0
msfeldstein/chrome-media-keys,PeterMinin/chrome-media-keys,PeterMinin/chrome-media-keys
9bec9dd156f97a1d00bf57a5badedebece295844
packages/@sanity/form-builder/src/inputs/BlockEditor-slate/toolbar/LinkButton.js
packages/@sanity/form-builder/src/inputs/BlockEditor-slate/toolbar/LinkButton.js
import React, {PropTypes} from 'react' import ToggleButton from 'part:@sanity/components/toggles/button' import LinkIcon from 'part:@sanity/base/sanity-logo-icon' import styles from './styles/LinkButton.css' export default class LinkButton extends React.Component { static propTypes = { onClick: PropTypes.func, activeLink: PropTypes.bool } handleToggleButtonClick = () => { this.props.onClick(this.props.activeLink) } render() { return ( <div style={{position: 'relative'}}> <ToggleButton onClick={this.handleToggleButtonClick} title={'Link'} className={styles.button} > <div className={styles.iconContainer}> <LinkIcon /> </div> </ToggleButton> </div> ) } }
import React, {PropTypes} from 'react' import ToggleButton from 'part:@sanity/components/toggles/button' import LinkIcon from 'part:@sanity/base/link-icon' import styles from './styles/LinkButton.css' export default class LinkButton extends React.Component { static propTypes = { onClick: PropTypes.func, activeLink: PropTypes.bool } handleToggleButtonClick = () => { this.props.onClick(this.props.activeLink) } render() { const {activeLink} = this.props return ( <div style={{position: 'relative'}}> <ToggleButton onClick={this.handleToggleButtonClick} title={'Link'} selected={activeLink} className={styles.button} > <div className={styles.iconContainer}> <LinkIcon /> </div> </ToggleButton> </div> ) } }
Use link icon for link button
[form-builder] Use link icon for link button
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
1aa3c6485e5c6d04480332e64ee848930fcbba70
configurations/react.js
configurations/react.js
module.exports = { "extends": "justinlocsei/configurations/es6", "ecmaFeatures": { "jsx": true }, "env": { "browser": true }, "plugins": [ "react" ], "rules": { "jsx-quotes": [2, "prefer-double"], "react/jsx-boolean-value": [2, "always"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-handler-names": 2, "react/jsx-no-bind": 2, "react/jsx-no-duplicate-props": [2, {"ignoreCase": true}], "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, "react/self-closing-comp": 2, "react/wrap-multilines": 2 } };
module.exports = { "extends": "justinlocsei/configurations/es6", "ecmaFeatures": { "jsx": true }, "env": { "browser": true }, "plugins": [ "react" ], "rules": { "jsx-quotes": [2, "prefer-double"], "react/jsx-boolean-value": [2, "always"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-handler-names": 2, "react/jsx-no-bind": 2, "react/jsx-no-duplicate-props": [2, {"ignoreCase": true}], "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, "react/jsx-wrap-multilines": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, "react/self-closing-comp": 2 } };
Update the named of a renamed React check
Update the named of a renamed React check
JavaScript
mit
justinlocsei/eslint-config-chiton
19b9def70f2bb1e827ba428527ebab8910ac46e2
app/documents/controllers/SearchController.js
app/documents/controllers/SearchController.js
module.exports = function($scope, $state, $location, $http, GlobalService, DocumentService, DocumentApiService, MathJaxService, QueryParser) { $scope.doSearch = function(){ var apiServer = GlobalService.apiServer() var query = QueryParser.parse($scope.searchText) console.log('query = ' + query) $http.get('http://' + apiServer + '/v1/documents' + '?' + query ) .then(function(response){ console.log(response.data['status']) console.log('Number of documents: ' + response.data['document_count']) var jsonData = response.data var documents = jsonData['documents'] DocumentService.setDocumentList(documents) var id = documents[0]['id'] console.log('SearchController, id: ' + id) DocumentApiService.getDocument(id) .then(function(response) { console.log('CURRENT STATE: ' + $state.current) $state.go('documents') $state.reload() $scope.$watch(function(scope) { return $scope.renderedText }, MathJaxService.reload('SearchController') ); }) }); }; }
module.exports = function($scope, $state, $location, $http, GlobalService, DocumentService, DocumentApiService, MathJaxService, QueryParser) { $scope.doSearch = function(){ var apiServer = GlobalService.apiServer() var query = QueryParser.parse($scope.searchText) console.log('query = ' + query) $http.get('http://' + apiServer + '/v1/documents' + '?' + query ) .then(function(response){ console.log(response.data['status']) console.log('Number of documents: ' + response.data['document_count']) var jsonData = response.data var documents = jsonData['documents'] DocumentService.setDocumentList(documents) var id = documents[0]['id'] console.log('SearchController, id: ' + id) DocumentApiService.getDocument(id) .then(function(response) { console.log('Document " + id + ' retrieved') console.log('CURRENT STATE: ' + $state.current) $state.go('documents') $state.reload() $scope.$watch(function(scope) { return $scope.renderedText }, MathJaxService.reload('SearchController') ); }) }); }; }
Fix search problem (but how??)
Fix search problem (but how??)
JavaScript
mit
jxxcarlson/ns_angular,jxxcarlson/ns_angular
a3e9428d38522008b933e258588bcc91868174d3
src/services/content/index.js
src/services/content/index.js
'use strict'; const request = require('request-promise-native'); const querystring = require('querystring'); const hooks = require('./hooks'); class Service { constructor(options) { this.options = options || {}; } find(params) { const options = {}; if(params.query.$limit) options["page[limit]"] = params.query.$limit; if(params.query.$skip) options["page[offset]"] = params.query.$skip; if(params.query.query) options.query = params.query.query; const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { return JSON.parse(string); }); } /*get(id, params) { return Promise.resolve({ id, text: `A new message with ID: ${id}!` }); }*/ } module.exports = function () { const app = this; // Initialize our service with any options it requires app.use('/contents', new Service()); // Get our initialize service to that we can bind hooks const contentService = app.service('/contents'); // Set up our before hooks contentService.before(hooks.before); // Set up our after hooks contentService.after(hooks.after); }; module.exports.Service = Service;
'use strict'; const request = require('request-promise-native'); const querystring = require('querystring'); const hooks = require('./hooks'); class Service { constructor(options) { this.options = options || {}; } find(params) { const options = {}; if(params.query.$limit) options["page[limit]"] = params.query.$limit; if(params.query.$skip) options["page[offset]"] = params.query.$skip; if(params.query.query) options.query = params.query.query; const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { let result = JSON.parse(string); result.total = result.meta.page.total; result.limit = result.meta.page.limit; result.skip = result.meta.page.offset; return result; }); } /*get(id, params) { return Promise.resolve({ id, text: `A new message with ID: ${id}!` }); }*/ } module.exports = function () { const app = this; // Initialize our service with any options it requires app.use('/contents', new Service()); // Get our initialize service to that we can bind hooks const contentService = app.service('/contents'); // Set up our before hooks contentService.before(hooks.before); // Set up our after hooks contentService.after(hooks.after); }; module.exports.Service = Service;
Add result page information in feathers format
Add result page information in feathers format
JavaScript
agpl-3.0
schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server
1941cfca63e0874c8bd71a24f27a80a66532a9f1
config.js
config.js
var config = module.exports = exports = {} config.items = { tmpDir: { def: 'tmp' } , outDir: { def: 'out' } , originalsPath: { def: 'originals' } , maxCols: { def: 10 } , maxTries: { def: 6 } , invalidRequestMessage: { def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." } , port: { def: 8000 } , maxWidth: { def: 10000 } , maxHeight: { def: 10000 } , minFreeSpace: { def: 0.01 } } config.files = { def: null , env: "IMG_CONFIG" }
var config = module.exports = exports = {} config.items = { tmpDir: { def: 'tmp' } , outDir: { def: 'out' } , originalsPath: { def: 'originals' } , maxCols: { def: 10 } , maxTries: { def: 6 } , invalidRequestMessage: { def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." } , port: { def: 8000 , cli: "-p, --port <nb>" , desc: "Port on which the server should listen" } , maxWidth: { def: 10000 } , maxHeight: { def: 10000 } , minFreeSpace: { def: 0.01 } } config.files = { def: null , env: "IMG_CONFIG" }
Add command-line option to change port
Add command-line option to change port
JavaScript
isc
vigour-io/shutter,vigour-io/vigour-img
4211ee0bc2e124f5807fc6ad538896e60d6cef7d
lib/scan.js
lib/scan.js
'use strict'; var glob = require('glob'), _ = require('lodash'), async = require('async'), fs = require('fs'), lex = require('./lex'); function isFile(path) { var stat = fs.statSync(path); return stat.isFile(); } function getStrings(path, done) { glob(path, function(er, files) { var tokens = []; files = files.filter(isFile); async.reduce(files, tokens, function(tokens, file, next) { fs.readFile(file, function(err, src) { if (err) return next(); if (src.length === 0) return next(); tokens.push(lex(src.toString())); return next(null, tokens); }); }, done); }); } function scan(path, done) { getStrings(path, function(err, results) { var strings = []; if (err) return done(err, strings); strings = results.reduce(function(strings, result) { return strings.concat(result); }, []); return done(null, _.uniq(strings).sort()); }); } module.exports = scan;
'use strict'; var glob = require('glob'), _ = require('lodash'), async = require('async'), fs = require('fs'), lex = require('./lex'); function isFile(path) { var stat = fs.statSync(path); return stat.isFile(); } function getStrings(path, done) { glob(path, function(er, files) { var tokens = []; files = files.filter(isFile); async.reduce(files, tokens, function(tokens, file, next) { fs.readFile(file, function(err, src) { if (err) return next(); if (src.length === 0) return next(null, tokens); tokens.push(lex(src.toString())); return next(null, tokens); }); }, done); }); } function scan(path, done) { getStrings(path, function(err, results) { var strings = []; if (err) return done(err, strings); strings = results.reduce(function(strings, result) { return strings.concat(result); }, []); return done(null, _.uniq(strings).sort()); }); } module.exports = scan;
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty
JavaScript
mit
onepercentclub/extract-gettext
be15a5d1d5f7b694728017494d217972d6481fd5
services/general_response.js
services/general_response.js
/** * General functions */ var general = {}; //General 404 error general.send404 = function(res){ res.status(404); res.jsonp({error: 'Not found'}); res.end(); }; //General 500 error general.send500 = function(res, msg){ res.status(500); res.jsonp({error:'Server error ' + msg}); res.end(); }; general.getOptions = function(res){ res.json({"Get Patients": "/patients", "Get One Patient": "/patient"`}); res.end(); }; module.exports = general;
/** * General functions */ var general = {}; //General 404 error general.send404 = function(res){ res.status(404); res.jsonp({error: 'Not found'}); res.end(); }; //General 500 error general.send500 = function(res, msg){ res.status(500); res.jsonp({error:'Server error ' + msg}); res.end(); }; general.getOptions = function(res){ res.json({"Get Patients": "/patients", "Get One Patient": "/patient"}); res.end(); }; module.exports = general;
Fix typo on getOptions response
Fix typo on getOptions response
JavaScript
mit
NextCenturyCorporation/healthcare-demo,NextCenturyCorporation/healthcare-demo,NextCenturyCorporation/healthcare-demo
26742b0534c27cb9c615c182a867afa191d06bc2
static/js/states/adminHome.js
static/js/states/adminHome.js
define([ 'app' ], function(app) { 'use strict'; return { parent: 'admin_layout', url: '', templateUrl: 'partials/admin/home.html', controller: function($scope, $http, flash) { $scope.loading = true; $http.get('/api/0/systemstats/').success(function(data){ $scope.statusCounts = data.statusCounts; $scope.resultCounts = data.resultCounts; }).error(function(){ flash('error', 'There was an error loading system statistics.'); }).finally(function(){ $scope.loading = false; }); } }; });
define([ 'app' ], function(app) { 'use strict'; return { parent: 'admin_layout', url: '', templateUrl: 'partials/admin/home.html', controller: function($scope, $http, flash) { var timeoutId; $scope.loading = true; $scope.$on('$destory', function(){ if (timeoutId) { window.cancelTimeout(timeoutId); } }); function tick() { $http.get('/api/0/systemstats/').success(function(data){ $scope.statusCounts = data.statusCounts; $scope.resultCounts = data.resultCounts; }).error(function(){ flash('error', 'There was an error loading system statistics.'); }).finally(function(){ $scope.loading = false; }); timeoutId = window.setTimeout(tick, 5000); } tick(); } }; });
Add polling for system stats
Add polling for system stats
JavaScript
apache-2.0
dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,dropbox/changes
30728328443fd659a605850d27cb0925a941ac78
server/index.js
server/index.js
'use strict'; const app = require('./app'); const db = require('../db'); const PORT = process.env.PORT || 3000; const path = require('path'); app.listen(PORT, () => { console.log('Example app listening on port 3000!'); });
'use strict'; const app = require('./app'); const db = require('../db'); const PORT = process.env.PORT || 3000; const path = require('path'); app.listen(PORT, () => { console.log('Example app listening on port ' + PORT); });
Change the console log to show proper port
Change the console log to show proper port
JavaScript
mit
FuriousFridges/FuriousFridges,FuriousFridges/FuriousFridges
23a9512ffcad024bd7e51db5f7677b2688dcc2cd
server/trips/pastTripModel.js
server/trips/pastTripModel.js
// Todo Implement and export schema using mongoose // Reference angular sprint var mongoose = require('mongoose'); //var User = require('../users/UserModel.js'); var Schema = mongoose.Schema; var PastTripSchema = new Schema({ creator: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, participants: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], name: { type: String, required: true }, code: { type: String, required: true }, expenses: [ { name: String, amount: Number, date: Date, location: Schema.Types.Mixed, payer: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, stakeholders: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], } ], summary: [] }); module.exports = mongoose.model('pasttrips', PastTripSchema);
// Todo Implement and export schema using mongoose // Reference angular sprint var mongoose = require('mongoose'); //var User = require('../users/UserModel.js'); var Schema = mongoose.Schema; var PastTripSchema = new Schema({ creator: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, participants: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], name: { type: String, required: true }, code: { type: String, required: true }, expenses: [ { name: String, amount: Number, date: Date, locationString: String, expenseString: String, location: Schema.Types.Mixed, payer: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, stakeholders: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], } ], summary: [] }); module.exports = mongoose.model('pasttrips', PastTripSchema);
Add location and expense strings to pastTrip model
Add location and expense strings to pastTrip model
JavaScript
mit
OrgulousArtichoke/vacaypay,OrgulousArtichoke/vacaypay
1a09bb1a60eaace841526c22b3d08d295082227a
test/filters/travis_filter.js
test/filters/travis_filter.js
"use strict"; var TravisFilter = function(name) { console.dir(process.env) name = name || "ON_TRAVIS"; // Get environmental variables that are known this.filter = function(test) { if(test.metadata == null) return false; if(test.metadata.ignore == null) return false; if(test.metadata.ignore.travis == null) return false; if(process.env[name] && test.metadata.ignore.travis == true) return true; return false; } } module.exports = TravisFilter;
"use strict"; var TravisFilter = function(name) { // console.dir(process.env) name = name || "TRAVIS_JOB_ID"; // Get environmental variables that are known this.filter = function(test) { if(test.metadata == null) return false; if(test.metadata.ignore == null) return false; if(test.metadata.ignore.travis == null) return false; if(process.env[name] != null && test.metadata.ignore.travis == true) return true; return false; } } module.exports = TravisFilter;
Fix ignore tests for travis
Fix ignore tests for travis
JavaScript
apache-2.0
mongodb/node-mongodb-native,mongodb/node-mongodb-native,capaj/node-mongodb-native,zhangyaoxing/node-mongodb-native,tuyndv/node-mongodb-native,thenaughtychild/node-mongodb-native,jqk6/node-mongodb-native,sarathms/node-mongodb-native,agclever/node-mongodb-native,amit777/node-mongodb-native,flyingfisher/node-mongodb-native,janaipakos/node-mongodb-native,nahidcse05/node-mongodb-native,Samicelus/node-mongodb-native,mvnnn/node-mongodb-native,HBOCodeLabs/node-mongodb-native,segmentio/node-mongodb-native,elijah513/node-mongodb-native,HiLittleCat/node-mongodb-native,patriksimek/node-mongodb-native,mongodb/node-mongodb-native,beni55/node-mongodb-native,d-mon-/node-mongodb-native,Lapixx/node-mongodb-native,christophehurpeau/node-mongodb-native,mongodb/node-mongodb-native,hgGeorg/node-mongodb-native,rafkhan/node-mongodb-native,pakokrew/node-mongodb-native,PeterWangPo/node-mongodb-native
ddb7437159ac6f01d84f59864b6e7708f0371df5
scripts/build.js
scripts/build.js
#!/usr/bin/env node var colors = require('colors'), exec = require('child_process').exec, pkg = require('../package.json'), preamble = '/*!\n' + ' * RadioRadio ' + pkg.version + '\n' + ' *\n' + ' * ' + pkg.description + '\n' + ' *\n' + ' * Source code available at: ' + pkg.homepage + '\n' + ' *\n' + ' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' + ' *\n' + ' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' + ' */\n'; exec('uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js'); exec('uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js'); console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
#!/usr/bin/env node var colors = require('colors'), exec = require('child_process').exec, pkg = require('../package.json'), preamble = '/*!\n' + ' * RadioRadio ' + pkg.version + '\n' + ' *\n' + ' * ' + pkg.description + '\n' + ' *\n' + ' * Source code available at: ' + pkg.homepage + '\n' + ' *\n' + ' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' + ' *\n' + ' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' + ' */\n'; exec('$(npm bin)/uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js'); exec('$(npm bin)/uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js'); console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
Add 'npm bin' to uglifyjs command.
Add 'npm bin' to uglifyjs command.
JavaScript
mit
jgarber623/RadioRadio,jgarber623/RadioRadio
55de12e099a43807e473cb5901439796804a3186
material.js
material.js
const Signal = require('signals') let MaterialID = 0 function Material (opts) { this.type = 'Material' this.id = 'Material_' + MaterialID++ this.changed = new Signal() this._uniforms = {} const ctx = opts.ctx this.baseColor = [0.95, 0.95, 0.95, 1] this.emissiveColor = [0, 0, 0, 1] this.metallic = 0.01 this.roughness = 0.5 this.displacement = 0 this.depthTest = true this.depthWrite = true this.depthFunc = opts.ctx.DepthFunc.LessEqual this.blendEnabled = false this.blendSrcRGBFactor = ctx.BlendFactor.ONE this.blendSrcAlphaFactor = ctx.BlendFactor.ONE this.blendDstRGBFactor = ctx.BlendFactor.ONE this.blendDstAlphaFactor = ctx.BlendFactor.ONE this.castShadows = false this.receiveShadows = false this.set(opts) } Material.prototype.init = function (entity) { this.entity = entity } Material.prototype.set = function (opts) { Object.assign(this, opts) Object.keys(opts).forEach((prop) => this.changed.dispatch(prop)) } module.exports = function (opts) { return new Material(opts) }
const Signal = require('signals') let MaterialID = 0 function Material (opts) { this.type = 'Material' this.id = 'Material_' + MaterialID++ this.changed = new Signal() this._uniforms = {} const ctx = opts.ctx this.baseColor = [0.95, 0.95, 0.95, 1] this.emissiveColor = [0, 0, 0, 1] this.metallic = 0.01 this.roughness = 0.5 this.displacement = 0 this.depthTest = true this.depthWrite = true this.depthFunc = opts.ctx.DepthFunc.LessEqual this.blendEnabled = false this.blendSrcRGBFactor = ctx.BlendFactor.ONE this.blendSrcAlphaFactor = ctx.BlendFactor.ONE this.blendDstRGBFactor = ctx.BlendFactor.ONE this.blendDstAlphaFactor = ctx.BlendFactor.ONE this.castShadows = false this.receiveShadows = false this.cullFaceEnabled = true this.set(opts) } Material.prototype.init = function (entity) { this.entity = entity } Material.prototype.set = function (opts) { Object.assign(this, opts) Object.keys(opts).forEach((prop) => this.changed.dispatch(prop)) } module.exports = function (opts) { return new Material(opts) }
Enable face culling by default
Enable face culling by default
JavaScript
mit
pex-gl/pex-renderer,pex-gl/pex-renderer
6437817486b732fb9d298ce14e363db13b07f43a
src/providers/mailer.js
src/providers/mailer.js
var util = require('util'), _ = require('lodash'), vow = require('vow'), nm = require('nodemailer'), transport = require('nodemailer-smtp-transport'), errors = require('../errors').Mailer, logger = require('./../logger'), mailer; module.exports = { /** * Initialize mailer module */ init: function (options) { logger.info('Initialize e-mail sending module', module); if (!options) { errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn'); return vow.resolve(); } mailer = new nm.createTransport(transport({ host: options.host, port: options.port })); return vow.resolve(mailer); }, /** * Email sending * @param {Object} options - e-mail options object * @returns {*} */ send: function (options) { var base = { encoding: 'utf-8' }; logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module); if (!mailer) { errors.createError(errors.CODES.NOT_INITIALIZED).log(); return vow.resolve(); } var def = vow.defer(); mailer.sendMail(_.extend({}, base, options), function (err) { errors.createError(errors.CODES.COMMON, { err: err }).log(); err ? def.reject(err) : def.resolve(); }); return def.promise(); } };
var util = require('util'), _ = require('lodash'), vow = require('vow'), nm = require('nodemailer'), transport = require('nodemailer-smtp-transport'), errors = require('../errors').Mailer, logger = require('./../logger'), mailer; module.exports = { /** * Initialize mailer module */ init: function (options) { logger.info('Initialize e-mail sending module', module); if (!options) { errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn'); return vow.resolve(); } mailer = new nm.createTransport(transport({ host: options.host, port: options.port })); return vow.resolve(mailer); }, /** * Email sending * @param {Object} options - e-mail options object * @returns {*} */ send: function (options) { var base = { encoding: 'utf-8' }; logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module); if (!mailer) { errors.createError(errors.CODES.NOT_INITIALIZED).log(); return vow.resolve(); } var def = vow.defer(); mailer.sendMail(_.extend({}, base, options), function (err) { if (err) { errors.createError(errors.CODES.COMMON, { err: err }).log(); def.reject(err); } else { def.resolve(); } }); return def.promise(); } };
Fix error with invalid error message while sending e-mail
Fix error with invalid error message while sending e-mail
JavaScript
mpl-2.0
bem-site/bse-admin,bem-site/bse-admin
b57a4d2ed50d373248041ec278e20e7bab8d0643
test/specs/operations.spec.js
test/specs/operations.spec.js
describe('Operations', function () { var isNode = typeof module !== 'undefined' && module.exports; var Parallel = isNode ? require('../../lib/parallel.js') : self.Parallel; it('should require(), map() and reduce correctly (check console errors)', function () { var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8], { evalPath: isNode ? undefined : 'lib/eval.js' }); function add(d) { return d[0] + d[1]; } function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); } p.require(factorial); var done = false; runs(function () { p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() { done = true; }); }); waitsFor(function () { return done; }, "it should finish", 500); }); });
describe('Operations', function () { var isNode = typeof module !== 'undefined' && module.exports; var Parallel = isNode ? require('../../lib/parallel.js') : self.Parallel; it('should require(), map() and reduce correctly (check console errors)', function () { var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8], { evalPath: isNode ? undefined : 'lib/eval.js' }); function add(d) { return d[0] + d[1]; } function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); } p.require(factorial); var done = false; runs(function () { p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() { done = true; }); }); waitsFor(function () { return done; }, "it should finish", 1000); }); });
Increase timeout slightly to avoid failing
Increase timeout slightly to avoid failing
JavaScript
mit
1aurabrown/parallel.js,parallel-js/parallel.js,adambom/parallel.js,SRobertZ/parallel.js,kidaa/parallel.js,1aurabrown/parallel.js,blackrabbit99/doubleW,blackrabbit99/parallel.js,colemakdvorak/parallel.js,blackrabbit99/parallel.js,kidaa/parallel.js,SRobertZ/parallel.js,parallel-js/parallel.js,colemakdvorak/parallel.js,blackrabbit99/doubleW,adambom/parallel.js
a5675bcb304623bcc28307751fd538f253c02fae
document/app.js
document/app.js
var express = require('express'); module.exports = function setup(options, imports, register) { var backend = imports.backend.app, frontend = imports.frontend.app; var plugin = { app: {}, documents: {} }; backend.get('/api/Documents', function (req, res, next) { res.json(module.documents); }); register(null, { document: plugin }); };
var express = require('express'); module.exports = function setup(options, imports, register) { var backend = imports.backend.app, frontend = imports.frontend.app; var plugin = { app: {}, documents: {}, addType: function (name, config) { this.documents[name] = config; } }; backend.get('/api/Documents', function (req, res, next) { res.json(module.documents); }); register(null, { document: plugin }); };
Add addType method to content
Add addType method to content
JavaScript
mit
bauhausjs/bauhausjs,bauhausjs/bauhausjs,bauhausjs/bauhausjs,bauhausjs/bauhausjs
e1e7cf8bdbaf961b665f45254a190914801d6bac
server/server.js
server/server.js
const express = require('express'); const app = express(); app.use(express.static('dist')); app.listen(8080, function() { console.log('App started on port 8080!'); });
const express = require('express'); const app = express(); app.use(express.static('dist')); app.listen(3000, function() { console.log('Listening on port 3000!'); });
Use port 3000 for testing
Use port 3000 for testing
JavaScript
mit
codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa
50249d2fed6c2e8bd9f1a7abd60d53a6cbb33f59
backend/lib/openfisca/index.js
backend/lib/openfisca/index.js
/* ** Module dependencies */ var config = require('../../config/config'); var http = require('http'); var mapping = require('./mapping'); var url = require('url'); var openfiscaURL = url.parse(config.openfiscaApi); function sendOpenfiscaRequest(simulation, callback) { var postData = JSON.stringify(simulation); var options = { hostname: openfiscaURL.hostname, port: openfiscaURL.port, path: 'calculate', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; var request = http.request(options, function(response) { response.setEncoding('utf8'); var rawData = ''; response.on('data', function(chunk) { rawData += chunk; }); response.on('end', function() { try { var content = JSON.parse(rawData); if (response.statusCode == 200) { callback(null, content); } else { callback(content.error); } } catch (e) { callback({ code: 500, errors: 'Can\'t parse: ' + rawData, message: e.message, stack: e.stack, }); } }); }); request.write(postData); request.on('error', callback); request.end(); } var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest; function calculate(situation, callback) { var request; try { request = buildOpenFiscaRequest(situation); } catch(e) { return callback({ message: e.message, name: e.name, stack: e.stack }); } sendOpenfiscaRequest(request, callback); } exports.calculate = calculate;
var config = require('../../config/config'); var mapping = require('./mapping'); var rp = require('request-promise'); var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest; function sendToOpenfisca(endpoint) { return function(situation, callback) { var request; try { request = buildOpenFiscaRequest(situation); } catch(e) { return callback({ message: e.message, name: e.name, stack: e.stack }); } rp({ uri: config.openfiscaApi + '/' + endpoint, method: 'POST', body: request, json: true, }) .then(function(result) { callback(null, result); }).catch(callback); }; } exports.calculate = sendToOpenfisca('calculate'); exports.trace = sendToOpenfisca('trace');
Use request-promise to manage OpenFisca calls
Use request-promise to manage OpenFisca calls
JavaScript
agpl-3.0
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
f63b1cd62f823d89e62d559ef5e86a70f504126c
javascripts/pong.js
javascripts/pong.js
(function() { 'use strict'; var canvas = document.getElementById('game'); var width = window.innerWidth; var height = window.innerHeight; canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; var clear = function() { ctx.clearRect(0, 0, width, height); }; var update = function() { }; var render = function () { }; var step = function() { update(); render(); requestAnimationFrame(FPS); } requestAnimationFrame(step()); })();
(function() { 'use strict'; var canvas = document.getElementById('game'); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; canvas.width = WIDTH; canvas.height = HEIGHT; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; var Paddle = function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.xSpeed = 0; this.ySpeed = 0; }; Paddle.prototype.render = function() { ctx.fillStyle = "#FFFFFF"; ctx.fillRect(this.x, this.y, this.width, this.height); } var clear = function() { ctx.clearRect(0, 0, WIDTH, HEIGHT); }; var update = function() { }; var render = function () { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, WIDTH, HEIGHT); }; var step = function() { update(); render(); requestAnimationFrame(FPS); } requestAnimationFrame(step()); })();
Define paddle object and a basic render function. Also capitalise width and height constants to easily distinguish them from object properties or parameters
Define paddle object and a basic render function. Also capitalise width and height constants to easily distinguish them from object properties or parameters
JavaScript
mit
msanatan/pong,msanatan/pong,msanatan/pong
ddfc71983fb71ccb81f5196f97f5bb040637cdf0
jive-sdk-service/generator/examples/todo/tiles/todo/public/javascripts/main.js
jive-sdk-service/generator/examples/todo/tiles/todo/public/javascripts/main.js
(function() { var clientid; jive.tile.onOpen(function(config, options, other, container ) { osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) { if( resp && resp.content ) { clientid = resp.content.clientid; } }); gadgets.window.adjustHeight(); if ( typeof config === "string" ) { config = JSON.parse(config); } var json = config || { }; json.project = json.project || container.name; // prepopulate the sequence input dialog $("#project").val( json.project); $("#btn_submit").click( function() { config.project = $("#project").val(); config.clientid = clientid; jive.tile.close(config, {} ); gadgets.window.adjustHeight(300); }); }); })();
(function() { var clientid; jive.tile.onOpen(function(config, options, other, container ) { osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) { if( resp && resp.content ) { clientid = resp.content.clientid; } }); gadgets.window.adjustHeight(); if ( typeof config === "string" ) { config = JSON.parse(config); } var json = config || { }; json.project = json.project || (container && container.name) || ""; // prepopulate the sequence input dialog $("#project").val( json.project); $("#btn_submit").click( function() { config.project = $("#project").val(); config.clientid = clientid; jive.tile.close(config, {} ); gadgets.window.adjustHeight(300); }); }); })();
Handle when container is undefined.
Handle when container is undefined.
JavaScript
apache-2.0
jivesoftware/jive-sdk,jivesoftware/jive-sdk,jivesoftware/jive-sdk
3f84b85e5524743a35237116b3e8ba9fdf3d1e2d
src/TopItems.js
src/TopItems.js
import React, { Component } from 'react'; import Item from './Item'; import sortByScore from './sorter'; var TopItems = React.createClass({ sortByScore: function() { this.setState({items: sortByScore(this.props.items)}); }, render: function() { var rank = 0; var all_items = this.props.items.map(function(item) { rank++; return ( <Item key={item.id} rank={rank} item={item} /> ); }); // Retired, sort button // <SortButton items={this.props.items} sortByScore={this.sortByScore}/> return ( <div> <div className="top-stories"> {all_items} </div> </div> ); } }); var SortButton = React.createClass({ render: function() { return ( <div> <a className='button' onClick={this.props.sortByScore}>Sort!</a> </div> ); } }); export default TopItems;
import React, { Component } from 'react'; import Item from './Item'; var TopItems = React.createClass({ render: function() { var rank = 0; var all_items = this.props.items.map(function(item) { rank++; return ( <Item key={item.id} rank={rank} item={item} /> ); }); return ( <div> <div className="top-stories"> {all_items} </div> </div> ); } }); export default TopItems;
Remove sort button, as we sort by default now
Remove sort button, as we sort by default now
JavaScript
mit
danbartlett/hn_minimal,danbartlett/hn_minimal
a8376d565326e347fcd6ef955d8de19483e7261d
lib/apps.js
lib/apps.js
/** * Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED. */ define([ './collection'], function (Collection) { var apps = function (api) { this.api = api; this.collection = 'apps'; }; apps.prototype = Object.create(new Collection()); apps.prototype.getAppInstances = function (guid, done) { this.api.get('/v2/apps/' + guid + '/instances', {status_code: 200}, function (err, res) { if (err) { return done(err); } done(null, res.body); }); }; apps.prototype.getFiles = function (guid, instance_index, path, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/instances/' + instance_index + '/files/' + path, {status_code: 200}, done); }; // TODO: Pull out in to Stackato specific extension apps.prototype.getLogTail = function (guid, line_count, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/stackato_logs', {query: '?num=' + (line_count || 25) + '&monolith=1', status_code: 200}, done) }; return apps; } );
/** * Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED. */ define([ './collection'], function (Collection) { var apps = function (api) { this.api = api; this.collection = 'apps'; }; apps.prototype = Object.create(new Collection()); apps.prototype.getAppInstances = function (guid, done) { this.api.get('/v2/apps/' + guid + '/instances', {status_code: 200}, function (err, res) { if (err) { return done(err); } done(null, res.body); }); }; apps.prototype.getFiles = function (guid, instance_index, path, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/instances/' + instance_index + '/files/' + path, {query: '?allow_redirect=false', status_code: 200}, done); }; // TODO: Pull out in to Stackato specific extension apps.prototype.getLogTail = function (guid, line_count, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/stackato_logs', {query: '?num=' + (line_count || 25) + '&monolith=1', status_code: 200}, done) }; return apps; } );
Disable redirect when browsing files from browser
Disable redirect when browsing files from browser
JavaScript
mit
ActiveState/cloud-foundry-client-js,18F/cloud-foundry-client-js,18F/cloud-foundry-client-js,hpcloud/cloud-foundry-client-js,hpcloud/cloud-foundry-client-js,ActiveState/cloud-foundry-client-js,morikat/cloud-foundry-client-js,morikat/cloud-foundry-client-js
e37507356b99586b31f888ba8405b1fc320f8400
lib/main.js
lib/main.js
"use babel"; "use strict"; import fs from "fs"; import path from "path"; import {CompositeDisposable} from "atom"; import {name as packageName} from "../package.json"; export default { subscriptions: null, activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.themes.onDidChangeActiveThemes(() => { this.subscriptions.add(atom.config.observe(`${packageName}.subtheme`, value => { this.apply(value); })); })); }, deactivate() { this.subscriptions.dispose(); }, apply(value) { let newData = `@import "colors/${value}";\n`, file = path.join(__dirname, "..", "styles", "syntax-variables.less"), oldData = fs.readFileSync(file, "utf8"); if (newData !== oldData) { fs.writeFileSync(file, newData); this.reloadAllStylesheets(); } }, reloadAllStylesheets() { atom.themes.deactivateThemes(); atom.themes.refreshLessCache(); let promises = [], ref = atom.themes.getEnabledThemeNames(); for (let i = 0, len = ref.length; i < len; i++) { let themeName = ref[i]; promises.push(atom.packages.activatePackage(themeName)); } Promise.all(promises).then(() => { atom.themes.addActiveThemeClasses(); atom.themes.refreshLessCache(); atom.themes.loadUserStylesheet(); atom.themes.reloadBaseStylesheets(); }); } };
"use babel"; "use strict"; import fs from "fs"; import path from "path"; import {CompositeDisposable} from "atom"; import {name as packageName} from "../package.json"; export default { subscriptions: null, activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.themes.onDidChangeActiveThemes(() => { this.subscriptions.add(atom.config.observe(`${packageName}.subtheme`, value => { this.apply(value); })); })); }, deactivate() { this.subscriptions.dispose(); }, apply(value) { let newData = `@import "colors/${value}";\n`, file = path.join(__dirname, "..", "styles", "syntax-variables.less"), oldData = fs.readFileSync(file, "utf8"); if (newData !== oldData) { fs.writeFileSync(file, newData); this.reloadAllStylesheets(); } }, reloadAllStylesheets() { atom.themes.loadUserStylesheet(); atom.themes.reloadBaseStylesheets(); let ref = atom.packages.getActivePackages(); for (let i = 0, len = ref.length; i < len; i++) { let pack = ref[i]; pack.reloadStylesheets(); } } };
Revert ":bug: Fix stylesheets issue when changing subtheme"
Revert ":bug: Fix stylesheets issue when changing subtheme" This reverts commit a9b1f3c3e9932fc0d049a6be64c3c8ecc01c7f4f.
JavaScript
mit
gt-rios/firefox-syntax
5c8bfc9df05fe7d13a4435085df1ba52f27bb376
lib/main.js
lib/main.js
'use babel'; let lineEndingTile = null; export function activate() { atom.workspace.observeActivePaneItem((item) => { let ending = getLineEnding(item); if (lineEndingTile) lineEndingTile.firstChild.textContent = ending; }); } export function consumeStatusBar(statusBar) { lineEndingTile = document.createElement('div'); lineEndingTile.style.display = "inline-block"; lineEndingTile.className = "line-ending-tile"; lineEndingTile.innerHTML = "<a></a>"; statusBar.addRightTile({item: lineEndingTile, priority: 200}); } function getLineEnding(item) { if (!item) return ""; let hasLF = false; let hasCRLF = false; if (item && item.scan) { item.scan(/\n|\r\n/g, ({matchText}) => { if (matchText === "\n") hasLF = true; if (matchText === "\r\n") hasCRLF = true; }); } if (hasLF && hasCRLF) return "Mixed"; if (hasLF) return "LF"; if (hasCRLF) return "CRLF"; if (process.platform === 'win32') return "CRLF"; return "LF"; }
'use babel'; let lineEndingTile = null; export function activate() { atom.workspace.observeActivePaneItem((item) => { let ending = getLineEnding(item); if (lineEndingTile) lineEndingTile.textContent = ending; }); } export function consumeStatusBar(statusBar) { lineEndingTile = document.createElement('a'); lineEndingTile.className = "line-ending-tile"; statusBar.addRightTile({item: lineEndingTile, priority: 200}); } function getLineEnding(item) { if (!item) return ""; let hasLF = false; let hasCRLF = false; if (item && item.scan) { item.scan(/\n|\r\n/g, ({matchText}) => { if (matchText === "\n") hasLF = true; if (matchText === "\r\n") hasCRLF = true; }); } if (hasLF && hasCRLF) return "Mixed"; if (hasLF) return "LF"; if (hasCRLF) return "CRLF"; if (process.platform === 'win32') return "CRLF"; return "LF"; }
Remove unneeded div around tile element
Remove unneeded div around tile element Signed-off-by: Max Brunsfeld <78036c9b69b887700d5846f26a788d53b201ffbb@gmail.com>
JavaScript
mit
clintwood/line-ending-selector,download13/line-ending-selector,atom/line-ending-selector,bolinfest/line-ending-selector
b6339fe3e288d639efb0236bf029b6a94602f706
lib/assets/test/spec/new-dashboard/unit/specs/store/user/user.spec.js
lib/assets/test/spec/new-dashboard/unit/specs/store/user/user.spec.js
import UserStore from 'new-dashboard/store/user'; import { testAction } from '../helpers'; jest.mock('carto-node'); const mutations = UserStore.mutations; const actions = UserStore.actions; describe('UserStore', () => { describe('mutations', () => { it('setUserData', () => { const state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; const userData = { email: 'example@carto.com', username: 'carto' }; mutations.setUserData(state, userData); expect(state).toEqual({ email: 'example@carto.com', username: 'carto', website: 'https://carto.com' }); }); }); describe('actions', () => { describe('updateData', () => { let state; beforeEach(() => { state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; }); it('success', done => { const newConfigData = { email: 'example@carto.com', username: 'carto' }; testAction(actions.updateData, null, state, [ { type: 'setUserData', payload: newConfigData } ], [], done); }); }); }); });
import UserStore from 'new-dashboard/store/user'; import { testAction2 } from '../helpers'; jest.mock('carto-node'); const mutations = UserStore.mutations; const actions = UserStore.actions; describe('UserStore', () => { describe('mutations', () => { it('setUserData', () => { const state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; const userData = { email: 'example@carto.com', username: 'carto' }; mutations.setUserData(state, userData); expect(state).toEqual({ email: 'example@carto.com', username: 'carto', website: 'https://carto.com' }); }); }); describe('actions', () => { describe('updateData', () => { let state; beforeEach(() => { state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; }); it('success', done => { const newConfigData = { email: 'example@carto.com', username: 'carto' }; const expectedMutations = [ { type: 'setUserData', payload: newConfigData } ]; testAction2({ action: actions.updateData, state, expectedMutations, done }); }); }); }); });
Use new test action function
test: Use new test action function
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
39ea495532f1d113a0ca6e98cd81848943e1695a
src/browser/home/HomePage.js
src/browser/home/HomePage.js
/* @flow */ import type { State } from '../../common/types'; import React from 'react'; import AddrListByRoom from './AddressListByRoom'; import AddrList from './AddressList'; import { connect } from 'react-redux'; import linksMessages from '../../common/app/linksMessages'; import { isEmpty, pathOr, reject } from 'ramda'; import { Block, Title, View, } from '../components'; import { Box } from 'reflexbox'; type HomePageProps = { smartHomeState: Object, location: Object, }; const HomePage = ({ smartHomeState, location }: HomePageProps) => { const { livestate, prefs } = smartHomeState; /* Built address-list, remove some address-types which should not be displayed */ const addresses = reject(addr => addr.type === 'fb', livestate); if (isEmpty(addresses)) { return ( <Block> <p>Waiting for SmartHome-State...</p> </Block> ); } const viewType = pathOr('changes', ['pathname'], location); const addrList = viewType === 'changes' ? <AddrList addresses={addresses} /> : <AddrListByRoom addresses={addresses} prefs={prefs} />; return ( <View> <Title message={linksMessages.home} /> <Box py={2}> {addrList} </Box> </View> ); }; export default connect( (state: State) => ({ smartHomeState: state.smartHome, }), )(HomePage);
/* @flow */ import type { State } from '../../common/types'; import React from 'react'; import AddrListByRoom from './AddressListByRoom'; import AddrList from './AddressList'; import { connect } from 'react-redux'; import linksMessages from '../../common/app/linksMessages'; import { isEmpty, pathOr, reject, test } from 'ramda'; import { Block, Title, View } from '../components'; import { Box } from 'reflexbox'; type HomePageProps = { smartHomeState: Object, location: Object, }; const HomePage = ({ smartHomeState, location }: HomePageProps) => { const { livestate, prefs } = smartHomeState; /* Built address-list, remove some address-types which should not be displayed */ const addresses = reject(addr => addr.type === 'fb', livestate); if (isEmpty(addresses)) { return ( <Block> <p>Waiting for SmartHome-State...</p> </Block> ); } const viewType = pathOr('changes', ['pathname'], location); const addrList = test(/rooms$/, viewType) ? <AddrListByRoom addresses={addresses} prefs={prefs} /> : <AddrList addresses={addresses} />; return ( <View> <Title message={linksMessages.home} /> <Box py={2}> {addrList} </Box> </View> ); }; export default connect((state: State) => ({ smartHomeState: state.smartHome, }))(HomePage);
Improve tolerance when matching url-paths for router-navigation.
Improve tolerance when matching url-paths for router-navigation.
JavaScript
mit
cjk/smart-home-app
7ced1f20afd2b52ac687bfae21ca33537b635ae6
src/routes/Player/components/PlayerController/PlayerControllerContainer.js
src/routes/Player/components/PlayerController/PlayerControllerContainer.js
import PlayerController from './PlayerController' import { connect } from 'react-redux' import { ensureState } from 'redux-optimistic-ui' import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue' import { playerLeave, playerError, playerLoad, playerPlay, playerStatus, } from '../../modules/player' import { playerVisualizerError } from '../../modules/playerVisualizer' const mapActionCreators = { playerLeave, playerError, playerLoad, playerPlay, playerStatus, playerVisualizerError, } const mapStateToProps = (state) => { const { player, playerVisualizer, prefs } = state const queue = ensureState(state.queue) return { cdgAlpha: player.cdgAlpha, cdgSize: player.cdgSize, historyJSON: state.status.historyJSON, // @TODO use state.player instead? isAtQueueEnd: player.isAtQueueEnd, isErrored: player.isErrored, isPlaying: player.isPlaying, isPlayingNext: player.isPlayingNext, isQueueEmpty: queue.result.length === 0, isReplayGainEnabled: prefs.isReplayGainEnabled, isWebGLSupported: player.isWebGLSupported, mp4Alpha: player.mp4Alpha, queue: getOrderedQueue(state), queueId: player.queueId, volume: player.volume, visualizer: playerVisualizer, } } export default connect(mapStateToProps, mapActionCreators)(PlayerController)
import PlayerController from './PlayerController' import { connect } from 'react-redux' import { ensureState } from 'redux-optimistic-ui' import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue' import { playerLeave, playerError, playerLoad, playerPlay, playerStatus, } from '../../modules/player' import { playerVisualizerError } from '../../modules/playerVisualizer' const mapActionCreators = { playerLeave, playerError, playerLoad, playerPlay, playerStatus, playerVisualizerError, } const mapStateToProps = (state) => { const { player, playerVisualizer, prefs } = state const queue = ensureState(state.queue) return { cdgAlpha: player.cdgAlpha, cdgSize: player.cdgSize, historyJSON: player.historyJSON, isAtQueueEnd: player.isAtQueueEnd, isErrored: player.isErrored, isPlaying: player.isPlaying, isPlayingNext: player.isPlayingNext, isQueueEmpty: queue.result.length === 0, isReplayGainEnabled: prefs.isReplayGainEnabled, isWebGLSupported: player.isWebGLSupported, mp4Alpha: player.mp4Alpha, queue: getOrderedQueue(state), queueId: player.queueId, volume: player.volume, visualizer: playerVisualizer, } } export default connect(mapStateToProps, mapActionCreators)(PlayerController)
Use internal player history instead of emitted status
Use internal player history instead of emitted status
JavaScript
isc
bhj/karaoke-forever,bhj/karaoke-forever
373dfb4090d23fceb878278a244b64ecde31efb0
lib/util.js
lib/util.js
exports = module.exports = require('util'); exports.formatDate = function(date){ if (typeof date === 'string') return date; date = new Date(date); var month = date.getMonth() + 1, day = date.getDate(), str = date.getFullYear(); str += '-'; if (month < 10) str += '0'; str += month; str += '-'; if (day < 10) str += '0'; str += day; return str; }; exports.formatError = function(data){ return new Error(data.message + ' (Code: ' + data.code + ')'); };
exports = module.exports = require('util'); exports.formatDate = function(date){ if (typeof date === 'string') return date; date = new Date(date); var month = date.getMonth() + 1, day = date.getDate(), str = date.getFullYear(); str += '-'; if (month < 10) str += '0'; str += month; str += '-'; if (day < 10) str += '0'; str += day; return str; }; exports.formatError = function(data){ var err = new Error(data.message + ' (Code: ' + data.code + ')'); err.code = data.code; return err; };
Add code to error object
Add code to error object
JavaScript
mit
tommy351/node-flurry-api
b3e10b4bc710a4892d430efeb2f41ef6900fb72c
src/components/OAuthLogin.js
src/components/OAuthLogin.js
import React from 'react'; import {FormattedMessage} from "react-intl"; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { const location = window.location; const targetUrl = `${location.protocol}//${location.host}/login`; const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`; return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> <a href={`${provider.login}${loginUrlQueryString}`} className="pt-button pt-intent-primary pt-icon-log-in"> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> </a> </p>)} </div> }; export const handleOAuthCallback = (onLoginFn) => { const parsedHash = queryString.parse(location.hash); if (parsedHash.token) { onLoginFn(parsedHash.token); location.hash = ''; } }; export default OAuthLogin;
import React from 'react'; import {FormattedMessage} from "react-intl"; import {AnchorButton, Intent} from '@blueprintjs/core'; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { const location = window.location; const targetUrl = `${location.protocol}//${location.host}/login`; const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`; return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> <AnchorButton href={`${provider.login}${loginUrlQueryString}`} intent={Intent.PRIMARY}> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> </AnchorButton> </p>)} </div> }; export const handleOAuthCallback = (onLoginFn) => { const parsedHash = queryString.parse(location.hash); if (parsedHash.token) { onLoginFn(parsedHash.token); location.hash = ''; } }; export default OAuthLogin;
Use AnchorButton for anchor button
Use AnchorButton for anchor button
JavaScript
mit
alephdata/aleph,pudo/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph
84bad5d57dff7d5591d24bcc5caf6698e17e40b6
src/Aggregrid.js
src/Aggregrid.js
Ext.define('Jarvus.aggregrid.Aggregrid', { extend: 'Ext.Component', html: 'Hello World' });
Ext.define('Jarvus.aggregrid.Aggregrid', { extend: 'Ext.Component', config: { columnsStore: null, rowsStore: null }, html: 'Hello World', // config handlers applyColumnsStore: function(store) { return Ext.StoreMgr.lookup(store); }, applyRowsStore: function(store) { return Ext.StoreMgr.lookup(store); } });
Add columnsStore and rowsStore configs
Add columnsStore and rowsStore configs
JavaScript
mit
JarvusInnovations/jarvus-aggregrid,JarvusInnovations/jarvus-aggregrid,JarvusInnovations/jarvus-aggregrid
b8fdcaf0033348f8ec7203bc1150f66d188c6259
src/Constants.js
src/Constants.js
export const BLOCK_TYPE = { // This is used to represent a normal text block (paragraph). UNSTYLED: 'unstyled', HEADER_ONE: 'header-one', HEADER_TWO: 'header-two', HEADER_THREE: 'header-three', HEADER_FOUR: 'header-four', HEADER_FIVE: 'header-five', HEADER_SIX: 'header-six', UNORDERED_LIST_ITEM: 'unordered-list-item', ORDERED_LIST_ITEM: 'ordered-list-item', BLOCKQUOTE: 'blockquote', PULLQUOTE: 'pullquote', CODE: 'code-block', ATOMIC: 'atomic', }; export const ENTITY_TYPE = { LINK: 'LINK', }; export const INLINE_STYLE = { BOLD: 'BOLD', CODE: 'CODE', ITALIC: 'ITALIC', STRIKETHROUGH: 'STRIKETHROUGH', UNDERLINE: 'UNDERLINE', }; export default { BLOCK_TYPE, ENTITY_TYPE, INLINE_STYLE, };
export const BLOCK_TYPE = { // This is used to represent a normal text block (paragraph). UNSTYLED: 'unstyled', HEADER_ONE: 'header-one', HEADER_TWO: 'header-two', HEADER_THREE: 'header-three', HEADER_FOUR: 'header-four', HEADER_FIVE: 'header-five', HEADER_SIX: 'header-six', UNORDERED_LIST_ITEM: 'unordered-list-item', ORDERED_LIST_ITEM: 'ordered-list-item', BLOCKQUOTE: 'blockquote', PULLQUOTE: 'pullquote', CODE: 'code-block', ATOMIC: 'atomic', }; export const ENTITY_TYPE = { LINK: 'LINK', IMAGE: 'IMAGE' }; export const INLINE_STYLE = { BOLD: 'BOLD', CODE: 'CODE', ITALIC: 'ITALIC', STRIKETHROUGH: 'STRIKETHROUGH', UNDERLINE: 'UNDERLINE', }; export default { BLOCK_TYPE, ENTITY_TYPE, INLINE_STYLE, };
Add Image to ENTITY_TYPE Enum
Add Image to ENTITY_TYPE Enum Useful for rich text editor inline image support
JavaScript
isc
draft-js-utils/draft-js-utils
c66a58685ab7fd556634f123c5d0389c52ac2a71
js/components/developer/payment-info-screen/paymentInfoScreenStyle.js
js/components/developer/payment-info-screen/paymentInfoScreenStyle.js
import { StyleSheet } from 'react-native'; const paymentInfoStyle = StyleSheet.create({ addCardButton: { padding: 20, }, }); module.exports = paymentInfoStyle;
import { StyleSheet } from 'react-native'; const paymentInfoStyle = StyleSheet.create({ addCardButton: { padding: 10, }, }); module.exports = paymentInfoStyle;
Reduce button padding in PaymentInfoScreen
Reduce button padding in PaymentInfoScreen
JavaScript
mit
justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client
969fc9567cc94d0a7a7d79528f989f8179cb3053
ukelonn.web.frontend/src/main/frontend/sagas/modifyPaymenttypeSaga.js
ukelonn.web.frontend/src/main/frontend/sagas/modifyPaymenttypeSaga.js
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype); } function* requestReceiveModifyPaymenttypeSaga(action) { try { const response = yield call(doModifyPaymenttype, action.payload); const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : []; yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes)); } catch (error) { yield put(MODIFY_PAYMENTTYPE_FAILURE(error)); } } export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); }
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, CLEAR_PAYMENT_TYPE_FORM, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype); } function* requestReceiveModifyPaymenttypeSaga(action) { try { const response = yield call(doModifyPaymenttype, action.payload); const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : []; yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes)); } catch (error) { yield put(MODIFY_PAYMENTTYPE_FAILURE(error)); } } function* clearPaymenttypeForm() { yield put(CLEAR_PAYMENT_TYPE_FORM()); } export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); yield takeLatest(MODIFY_PAYMENTTYPE_RECEIVE, clearPaymenttypeForm); }
Clear payment type form data after succesfully saving a modified payment type
Clear payment type form data after succesfully saving a modified payment type
JavaScript
apache-2.0
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
c37dcfb3438de31be8ad7fc7dd5847d840bd05d6
app/assets/javascripts/angular/common/models/user-model.js
app/assets/javascripts/angular/common/models/user-model.js
(function(){ 'use strict'; angular .module('secondLead') .factory('UserModel',['Auth', 'Restangular', 'store', function(Auth, Restangular, store) { var baseUsers = Restangular.all('users'); return { getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, isLoggedIn: function (user) { return store.get('user'); }, register: function(newUser){ return baseUsers.post({"user": { first_name: newUser.firstName, last_name: newUser.lastName, email: newUser.email, username: newUser.username, password: newUser.password } }); }, login: function (user) { return Auth.login({ username: user.username, password: user.password }); } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .factory('UserModel',['Auth', 'Restangular', '$rootScope', 'store', function(Auth, Restangular, $rootScope, store) { var baseUsers = Restangular.all('users'); var loggedIn = false; function setLoggedIn(state){ loggedIn = state; $rootScope.$broadcast('loggedIn:updated',state); }; return { currentUser: function() { return store.get('user'); }, getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, getStatus: function() { return { loggedIn: loggedIn } }, login: function (user) { var auth = Auth.login({ username: user.username, password: user.password }); return auth; }, register: function(newUser){ return baseUsers.post({"user": { first_name: newUser.firstName, last_name: newUser.lastName, email: newUser.email, username: newUser.username, password: newUser.password } }); }, setLoggedIn: setLoggedIn } ; }]) })();
Refactor user model to broadcast changes to login state
Refactor user model to broadcast changes to login state
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
e40b9eb6927bfeb12a1f2e477c009076bbb7bcab
lib/startup/restoreOverwrittenFilesWithOriginals.js
lib/startup/restoreOverwrittenFilesWithOriginals.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const glob = require('glob') const path = require('path') const fs = require('fs') const logger = require('../logger') const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) if (fs.existsSync('../../frontend/dist')) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => { if (err) { logger.warn('Error listing JSON files in /data/static/i18n folder: ' + err.message) } else { files.forEach(filename => { fs.copyFileSync(filename, path.resolve(__dirname, '../../i18n/', filename.substring(filename.lastIndexOf('/') + 1))) }) } }) } module.exports = restoreOverwrittenFilesWithOriginals
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const glob = require('glob') const path = require('path') const fs = require('fs') const logger = require('../logger') const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) if (fs.existsSync(path.resolve(__dirname,'../../frontend/dist'))) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => { if (err) { logger.warn('Error listing JSON files in /data/static/i18n folder: ' + err.message) } else { files.forEach(filename => { fs.copyFileSync(filename, path.resolve(__dirname, '../../i18n/', filename.substring(filename.lastIndexOf('/') + 1))) }) } }) } module.exports = restoreOverwrittenFilesWithOriginals
Check for correct folder before copying subtitle file
Check for correct folder before copying subtitle file
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
22bcd6224d7424504b4cc7f24c04ff62443d0d46
components/calendar/day.js
components/calendar/day.js
import Event from './event'; const Day = ({ events }) => { let id = 0; let eventList = []; for (let e of events) { eventList.push(<Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>); id++; } const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; const DAY = events[ 0 ].start_time; const DAY_NAME = DAY_NAMES[ DAY.getDay() ]; const DATE = DAY.getDate(); const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ]; return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> {eventList} <br /> </div> ); }; export default Day;
import Event from './event'; const Day = ({ events }) => { const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; const DAY = events[ 0 ].start_time; const DAY_NAME = DAY_NAMES[ DAY.getDay() ]; const DATE = DAY.getDate(); const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ]; return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> { events.map((e, id) => { return <Event title={e.title} start_time={e.start_time} content={e.content} key={id}/> })} <br /> </div> ); }; export default Day;
Remove the for-loop in favor of mapping the array into event components
Remove the for-loop in favor of mapping the array into event components
JavaScript
mit
dotKom/glowing-fortnight,dotKom/glowing-fortnight
822874ab19a96ebdab6f7232fdfdc3cfe411ab6d
config/ldap.js
config/ldap.js
const LDAP = require('ldap-client'), config = require('./config'); let protocol = config.get('ssl') ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port; module.exports = new LDAP({ uri: protocol + [host, port].join(':'), base: config.get('ldap').searchBase });
'use strict'; const LDAP = require('ldap-client'), config = require('./config'); let protocol = config.get('ldap').ssl ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port; module.exports = new LDAP({ uri: protocol + [host, port].join(':'), base: config.get('ldap').searchBase });
Fix let bug on older node
Fix let bug on older node
JavaScript
apache-2.0
mfinelli/cautious-ldap,mfinelli/cautious-ldap
d4444f33c32a56db9dc5b59d1174c79b5f04aafa
client/store/configureStore.js
client/store/configureStore.js
import {applyMiddleware, createStore} from 'redux'; import rootReducer from '../reducers'; import thunkMiddleware from 'redux-thunk'; export default function configureStore (initialState) { const create = typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension()(createStore) : createStore; const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(create); return createStoreWithMiddleware(rootReducer, initialState); }
import {applyMiddleware, compose, createStore} from 'redux'; import reducer from '../reducers'; import thunk from 'redux-thunk'; export default function configureStore (initialState) { return createStore( reducer, initialState, compose( applyMiddleware(thunk), typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension() : (f) => f ) ); }
Clean up store using compose
Clean up store using compose
JavaScript
mit
richardkall/react-starter,Thomas0c/react-starter,adamjking3/react-redux-apollo-starter
4813e914f56cd9e5ad82f04c449c509fc8e04034
src/api/model.js
src/api/model.js
import express from 'express'; import {addAction} from '../lib/database'; import ModelStore from '../store/model-store'; let app = express(); app.get('/', (req, res) => { let model = ModelStore.getModelById(req.query.id); res.successJson({ model: { address: model.address, name: model.name } }); }); app.get('/all-models', (req, res) => { res.successJson({ models: ModelStore.getAllModels() }); }); app.post('/', (req, res) => { addAction('NEW_MODEL', { name: req.body.name }) .then(actionId => { let model = ModelStore.getModelByActionId(actionId); res.successJson({ address: model.address }); }) .catch(e => { res.failureJson(e.message); }); }); export default app;
import express from 'express'; import { addAction } from '../lib/database'; import ModelStore from '../store/model-store'; let app = express(); app.get('/', (req, res) => { let model = ModelStore.getModelById(req.query.id); res.successJson({ model: { address: model.address, name: model.name } }); }); app.get('/all', (req, res) => { res.successJson({ models: ModelStore.getAllModels() }); }); app.post('/', (req, res) => { addAction('NEW_MODEL', { name: req.body.name }) .then(actionId => { let model = ModelStore.getModelByActionId(actionId); res.successJson({ address: model.address }); }) .catch(e => { res.failureJson(e.message); }); }); export default app;
Fix the things Jordan didn't
Fix the things Jordan didn't
JavaScript
unlicense
TheFourFifths/consus,TheFourFifths/consus
69ea3ae14fba2cca826f4c40d2e4ed8914029560
ghost/admin/app/utils/route.js
ghost/admin/app/utils/route.js
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade')) { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade') && transition.to?.name !== 'signout') { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
Allow signout in `forceUpgrade` state
Allow signout in `forceUpgrade` state
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
d7c846fd0e3289c25f40046c36e5f3046e4b74ea
src/banks/CBE.js
src/banks/CBE.js
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); }); const rates = []; return rates; } }
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } static getCurrencyCode(name) { const dict = { 'US Dollar​': 'USD', 'Euro​': 'EUR', 'Pound Sterling​': 'GBP', 'Swiss Franc​': 'CHF', 'Japanese Yen 100​': 'JPY', 'Saudi Riyal​': 'SAR', 'Kuwaiti Dinar​': 'KWD', 'UAE Dirham​': 'AED', 'Chinese yuan​': 'CNY', }; return (dict[name]); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); const rates = []; tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); rates.push({ code: CBE.getCurrencyCode(currencyName), buy: currencyBuy, sell: currencySell, }); }); return rates; } }
Convert currency name to currency iso code
Convert currency name to currency iso code
JavaScript
mit
MMayla/egypt-banks-scraper
b453399b7913fec129a54b16f7e4e8e9f27f839d
src/server/api/put-drawing.js
src/server/api/put-drawing.js
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { ref.set(meta.location); publishedRef.set(meta.location); res.send('ok'); }) .catch((err) => { res.error(err); }); }
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { const cloudFront = `https://d3ieg3cxah9p4i.cloudfront.net/${meta.location.split('/bolg/')[1]}`; ref.set(cloudFront); publishedRef.set(cloudFront); res.send('ok'); }) .catch((err) => { res.error(err); }); }
Use cloudfront link to store drawings
Use cloudfront link to store drawings
JavaScript
mit
tuelsch/bolg,tuelsch/bolg
b980b03d21e5941ffdf22491fd4fe786bf914094
native/packages/react-native-bpk-component-button-link/src/styles.js
native/packages/react-native-bpk-component-button-link/src/styles.js
/* * Backpack - Skyscanner's Design System * * Copyright 2018 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* @flow */ import { StyleSheet } from 'react-native'; import { colorBlue500, colorGray300, spacingSm, spacingXl, } from 'bpk-tokens/tokens/base.react.native'; const styles = StyleSheet.create({ view: { height: spacingXl, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, viewLarge: { height: spacingXl + spacingSm, }, viewLeading: { flexDirection: 'row-reverse', }, text: { color: colorBlue500, }, textDisabled: { color: colorGray300, }, icon: { color: colorBlue500, marginLeft: spacingSm, }, iconLeading: { marginLeft: 0, marginRight: spacingSm, }, }); export default styles;
/* * Backpack - Skyscanner's Design System * * Copyright 2018 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* @flow */ import { StyleSheet } from 'react-native'; import { colorBlue500, colorGray300, spacingSm, spacingXl, } from 'bpk-tokens/tokens/base.react.native'; const styles = StyleSheet.create({ view: { minHeight: spacingXl, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, viewLarge: { minHeight: spacingXl + spacingSm, }, viewLeading: { flexDirection: 'row-reverse', }, text: { color: colorBlue500, }, textDisabled: { color: colorGray300, }, icon: { color: colorBlue500, marginLeft: spacingSm, }, iconLeading: { marginLeft: 0, marginRight: spacingSm, }, }); export default styles;
Add dynamic text to Link buttons
[BPK-1716] Add dynamic text to Link buttons
JavaScript
apache-2.0
Skyscanner/backpack,Skyscanner/backpack,Skyscanner/backpack
16ebd7082ce2dff40de666cfeb06c939e7e92159
src/Jadu/Pulsar/Twig.js/Extension/RelativeTimeExtension.js
src/Jadu/Pulsar/Twig.js/Extension/RelativeTimeExtension.js
var _ = require('lodash'), moment = require('moment'); function RelativeTimeExtension() { moment.locale('en', { relativeTime : { future: "in %s", past: "%s ago", s: function (number, withoutSuffix, key, isFuture) { var plural = (number < 2) ? " second" : " seconds"; return number + plural; }, m: "%d minute", mm: "%d minutes", h: "%d hour", hh: "%d hours", d: "%d day", dd: "%d days", M: "%d month", MM: "%d months", y: "%d year", yy: "%d years" } }); } RelativeTimeExtension.prototype.getName = function () { return 'relative_time_extension'; }; RelativeTimeExtension.prototype.timeAgo = function (time_from) { if (time_from === undefined || time_from === null) { return false; } if (_.isDate(time_from)) { time_from = time_from.getTime()/1000; } var time_now = new Date().getTime(); if ((time_from*1000-time_now) === 0) { return 'just now'; } return moment.unix(time_from).fromNow(); }; module.exports = RelativeTimeExtension;
var _ = require('lodash'), moment = require('moment'); function RelativeTimeExtension() { moment.updateLocale('en', { relativeTime : { future: "in %s", past: "%s ago", s: function (number, withoutSuffix, key, isFuture) { var plural = (number < 2) ? " second" : " seconds"; return number + plural; }, m: "%d minute", mm: "%d minutes", h: "%d hour", hh: "%d hours", d: "%d day", dd: "%d days", M: "%d month", MM: "%d months", y: "%d year", yy: "%d years" } }); } RelativeTimeExtension.prototype.getName = function () { return 'relative_time_extension'; }; RelativeTimeExtension.prototype.timeAgo = function (time_from) { if (time_from === undefined || time_from === null) { return false; } if (_.isDate(time_from)) { time_from = time_from.getTime()/1000; } var time_now = new Date().getTime(); if ((time_from*1000-time_now) === 0) { return 'just now'; } return moment.unix(time_from).fromNow(); }; module.exports = RelativeTimeExtension;
Fix deprecation warning from moment
Fix deprecation warning from moment
JavaScript
mit
jadu/pulsar,jadu/pulsar,jadu/pulsar
e8bf6e4214d906771ae27f2ba843825cc61eb62b
geotrek/jstests/_nav-utils.js
geotrek/jstests/_nav-utils.js
var fs = require('fs'); module.exports = (function() { const PATH_COOKIES = '/tmp/cookies.txt'; function setUp() { casper.options.viewportSize = {width: 1280, height: 768}; casper.options.waitTimeout = 10000; casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'); casper.on('remote.message', function(msg) { this.echo("Error: " + msg, "ERROR"); }); casper.on('page.error', function(msg, trace) { this.echo("Error: " + msg, "ERROR"); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', "ERROR"); } }); } function saveCookies(path) { path = path || PATH_COOKIES; var cookies = JSON.stringify(phantom.cookies); fs.write(path, cookies, 600); } function loadCookies(path) { path = path || PATH_COOKIES; var data = fs.read(path); phantom.cookies = JSON.parse(data); } return { saveCookies: saveCookies, loadCookies: loadCookies }; })();
var fs = require('fs'); module.exports = (function() { const PATH_COOKIES = '/tmp/cookies.txt'; function setUp() { casper.options.viewportSize = {width: 1280, height: 768}; casper.options.waitTimeout = 10000; casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'); casper.on('remote.message', function(msg) { this.echo("Error: " + msg, "ERROR"); }); casper.on('page.error', function(msg, trace) { this.echo("Error: " + msg, "ERROR"); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', "ERROR"); } }); } function saveCookies(path) { path = path || PATH_COOKIES; var cookies = JSON.stringify(phantom.cookies); fs.write(path, cookies, 600); } function loadCookies(path) { path = path || PATH_COOKIES; var data = fs.read(path); phantom.cookies = JSON.parse(data); } return { saveCookies: saveCookies, loadCookies: loadCookies, setUp: setUp }; })();
Fix nav test utils export
Fix nav test utils export
JavaScript
bsd-2-clause
GeotrekCE/Geotrek-admin,johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,camillemonchicourt/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek
74b8de8809ce6b2343657a996768b96320d7c242
src/gulpfile.js
src/gulpfile.js
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.copy( 'node_modules/bootstrap/dist/fonts', 'public/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', 'public/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', 'public/fonts' ); mix.scripts([ '../../../node_modules/jquery/dist/jquery.min.js', '../../../node_modules/bootstrap/dist/js/bootstrap.min.js' ], 'public/js/vendor.js'); mix.scripts([ 'app.js' ], 'public/js/app.js'); mix.less([ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', 'admin-lte/AdminLTE.less', 'admin-lte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([ 'app.less' ], 'public/css/app.css'); mix.less([ 'welcome.less' ], 'public/css/welcome.css'); mix.version([ 'public/css/app.css', 'public/css/welcome.css', 'public/css/vendor.css', 'public/js/app.js', 'public/js/vendor.js' ]); });
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.copy( 'node_modules/bootstrap/dist/fonts', 'public/build/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', 'public/build/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', 'public/build/fonts' ); mix.scripts([ '../../../node_modules/jquery/dist/jquery.min.js', '../../../node_modules/bootstrap/dist/js/bootstrap.min.js' ], 'public/js/vendor.js'); mix.scripts([ 'app.js' ], 'public/js/app.js'); mix.less([ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', 'adminlte/AdminLTE.less', 'adminlte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([ 'app.less' ], 'public/css/app.css'); mix.less([ 'welcome.less' ], 'public/css/welcome.css'); mix.version([ 'public/css/app.css', 'public/css/welcome.css', 'public/css/vendor.css', 'public/js/app.js', 'public/js/vendor.js' ]); });
Change path tot adminlte less file Copy the fonts to build folder because we will be using elixir
Change path tot adminlte less file Copy the fonts to build folder because we will be using elixir
JavaScript
mit
syahzul/admin-theme
7fa1ebf356afb1c8b7e1f0bc013428f1d4377fb1
src/Native/D3/index.js
src/Native/D3/index.js
Elm.Native.D3 = {}; import "JavaScript" import "Render" import "Color" import "Selection" import "Event" import "Transition" import "Voronoi"
Elm.Native.D3 = {}; import "JavaScript" import "Render" import "Color" import "Selection" import "Event" import "Transition" import "Voronoi" Elm.Native.D3.Scales = {}; import "Scales/Quantitative"
Index will include scales during compilation
Index will include scales during compilation
JavaScript
bsd-3-clause
NigelThorne/elm-d3,seliopou/elm-d3,NigelThorne/elm-d3
93b31e51d8a7e1017f7cd2d3603023ca4ecf1bc1
src/views/plugins/Markdown.js
src/views/plugins/Markdown.js
import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; function toAbsolute(baseUrl, src) { try { return new URL(src, baseUrl).toString(); } catch (e) { return src; } } const GH_CDN = 'https://raw.githubusercontent.com'; export default class extends MarkdownIt { constructor(opts) { super(opts); const rules = this.renderer.rules; this.renderer.rules = { ...rules, // Rewrite relative URLs. image(tokens, idx, ...args) { const token = tokens[idx]; // Rewrite repository-relative urls to the github CDN. const repository = opts.package.repository; if (repository && repository.type === 'git') { const github = gh(repository.url); if (github) { token.attrSet('src', toAbsolute( `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, token.attrGet('src'))); } } return rules.image(tokens, idx, ...args); }, }; } }
import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; import { before } from 'meld'; function toAbsolute(baseUrl, src) { try { return new URL(src, baseUrl).toString(); } catch (e) { return src; } } const GH_CDN = 'https://raw.githubusercontent.com'; export default class extends MarkdownIt { constructor(opts) { super(opts); // Rewrite relative image URLs. before(this.renderer.rules, 'image', (tokens, idx) => { const token = tokens[idx]; // Rewrite repository-relative urls to the github CDN. const repository = opts.package.repository; if (repository && repository.type === 'git') { const github = gh(repository.url); if (github) { token.attrSet('src', toAbsolute( `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, token.attrGet('src'))); } } }); } }
Use `meld` to override markdown image handling.
Use `meld` to override markdown image handling.
JavaScript
mit
ExtPlug/ExtPlug
327a3e9edc2d44fc6e5dc6dfbab2f783efac471e
src/bot/index.js
src/bot/index.js
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1-5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
Fix to default cron time
Fix to default cron time
JavaScript
mit
simon-johansson/tipsbot
dbb9c0957a5485a0a86f982c61eeb6b8c44cf3b9
horizon/static/horizon/js/horizon.metering.js
horizon/static/horizon/js/horizon.metering.js
horizon.metering = { init_create_usage_report_form: function() { horizon.datepickers.add('input[data-date-picker="True"]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, init_stats_page: function() { if (typeof horizon.d3_line_chart !== 'undefined') { horizon.d3_line_chart.init("div[data-chart-type='line_chart']", {'auto_resize': true}); } horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, show_or_hide_date_fields: function() { $("#date_from .controls input, #date_to .controls input").val(''); if ($("#id_period").find("option:selected").val() === "other"){ $("#id_date_from, #id_date_to").parent().parent().show(); return true; } else { $("#id_date_from, #id_date_to").parent().parent().hide(); return false; } }, add_change_event_to_period_dropdown: function() { $("#id_period").change(function(evt) { if (horizon.metering.show_or_hide_date_fields()) { evt.stopPropagation(); } }); } };
horizon.metering = { init_create_usage_report_form: function() { horizon.datepickers.add('input[data-date-picker]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, init_stats_page: function() { if (typeof horizon.d3_line_chart !== 'undefined') { horizon.d3_line_chart.init("div[data-chart-type='line_chart']", {'auto_resize': true}); } horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, show_or_hide_date_fields: function() { $("#date_from .controls input, #date_to .controls input").val(''); if ($("#id_period").find("option:selected").val() === "other"){ $("#id_date_from, #id_date_to").parent().parent().show(); return true; } else { $("#id_date_from, #id_date_to").parent().parent().hide(); return false; } }, add_change_event_to_period_dropdown: function() { $("#id_period").change(function(evt) { if (horizon.metering.show_or_hide_date_fields()) { evt.stopPropagation(); } }); } };
Change widget attribute to string
Change widget attribute to string In Django 1.8, widget attribute data-date-picker=True will be rendered as 'data-date-picker'. This patch will just look for the presence of the attribute, ignoring the actual value. Change-Id: I0beabddfe13c060ef2222a09636738428135040a Closes-Bug: #1467935 (cherry picked from commit f4581dd48a7ffdcdf1b0061951e837c69caf9420)
JavaScript
apache-2.0
Daniex/horizon,NCI-Cloud/horizon,wangxiangyu/horizon,wangxiangyu/horizon,NCI-Cloud/horizon,wangxiangyu/horizon,VaneCloud/horizon,izadorozhna/dashboard_integration_tests,VaneCloud/horizon,izadorozhna/dashboard_integration_tests,Daniex/horizon,VaneCloud/horizon,Daniex/horizon,NCI-Cloud/horizon,Daniex/horizon,NCI-Cloud/horizon,wangxiangyu/horizon,VaneCloud/horizon
301d8c45b157cd4b673f40a70965a19af2c4275d
addon/utils/get-mutable-attributes.js
addon/utils/get-mutable-attributes.js
import Ember from 'ember'; var getMutValue = Ember.__loader.require('ember-htmlbars/hooks/get-value')['default']; export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => { acc[attr] = getMutValue(attrs[attr]); return acc; }, {}); }
import Ember from 'ember'; const emberMajorMinorVersion = Ember.VERSION.match(/(\d+\.\d+)\.*/)[1]; const isGlimmer = Number(emberMajorMinorVersion) >= 2.10; let getMutValue; if (isGlimmer) { const { MUTABLE_CELL } = Ember.__loader.require('ember-views/compat/attrs'); getMutValue = (value) => { if (value && value[MUTABLE_CELL]) { return value.value; } else { return value; } }; } else { getMutValue = Ember.__loader.require('ember-glimmer/hooks/get-value')['default']; } export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => { acc[attr] = getMutValue(attrs[attr]); return acc; }, {}); }
Fix for getting mutable attributes in glimmer
Fix for getting mutable attributes in glimmer
JavaScript
mit
pswai/ember-cli-react,pswai/ember-cli-react
9474e5cb8a16fd2beb8aa5c73f8189c0d78cfd25
tasks/parallel-behat.js
tasks/parallel-behat.js
'use strict'; var glob = require('glob'), _ = require('underscore'), ParallelExec = require('./lib/ParallelExec'), BehatTask = require('./lib/BehatTask'), defaults = { src: './**/*.feature', bin: './bin/behat', cwd: './', config: './behat.yml', flags: '', maxProcesses: 10000, baseDir: './', debug: false, numRetries: 0, timeout: 600000 }; /** * Grunt task for executing behat feature files in parallel * * @param {Grunt} grunt */ function GruntTask (grunt) { var options = _.defaults(grunt.config('behat') || {}, defaults), executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), behat; grunt.registerTask('behat', 'Parallel behat', function () { var done = this.async(); glob(options.src, function (err, files) { options.files = files; options.done = done; options.executor = executor; options.log = grunt.log.writeln; behat = new BehatTask(options); behat.run(); }); }); } module.exports = GruntTask;
'use strict'; var glob = require('glob'), _ = require('underscore'), ParallelExec = require('./lib/ParallelExec'), BehatTask = require('./lib/BehatTask'), defaults = { src: './**/*.feature', bin: './bin/behat', cwd: './', config: './behat.yml', flags: '', maxProcesses: 10000, baseDir: './', debug: false, numRetries: 0, timeout: 600000 }; /** * Grunt task for executing behat feature files in parallel * * @param {Grunt} grunt */ function GruntTask (grunt) { grunt.registerMultiTask('behat', 'Parallel behat', function () { var done = this.async(), options = this.options(defaults), executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), behat; options.files = this.filesSrc; options.done = done; options.executor = executor; options.log = grunt.log.writeln; behat = new BehatTask(options); behat.run(); }); } module.exports = GruntTask;
Fix options loading and turn into MultiTask
Fix options loading and turn into MultiTask
JavaScript
mit
linusnorton/grunt-parallel-behat
cab68ae620e449e49385a6125d233129d7d325cf
src/js/route.js
src/js/route.js
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, arrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? arrayKey : tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } arrayKey++; return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
Add support for unkeyed params array.
Add support for unkeyed params array.
JavaScript
mit
tightenco/ziggy,tightenco/ziggy
dff0317c05d48588f6e86b80ebc3b1bdc3b0b8f7
editor/static/editor.js
editor/static/editor.js
var app var project var checkout var host var session window.addEventListener('load', () => { project = substance.getQueryStringParam('project'); checkout = substance.getQueryStringParam('checkout'); host = substance.getQueryStringParam('host'); session = substance.getQueryStringParam('session'); // If a session is provided then connect directly to that host // otherwise use the top level v0 API to create a new session if (host && session) { window.STENCILA_HOSTS = `${host}/v1/sessions!/${session}`; } else if (host) { window.STENCILA_HOSTS = `${host}/v0`; } // Mount the app substance.substanceGlobals.DEBUG_RENDERING = substance.platform.devtools; app = stencila.StencilaWebApp.mount({ archiveId: checkout, storageType: 'fs', storageUrl: '/edit/storage' }, window.document.body); // Remove the loading var loading = document.getElementById('loading'); loading.parentNode.removeChild(loading) // Commit button var commitBtn = document.getElementById('commit'); commitBtn.addEventListener('click', () => { commitBtn.disabled = true; commit().then(() => { commitBtn.disabled = false; }) }) }); window.addEventListener('beforeunload', () => { // Commit changes when window closed commit() }) function commit () { return app._save().then(() => { fetch(`/checkouts/${checkout}/commit`, { credentials: 'same-origin' }) }) }
var app var checkout var key var host var session window.addEventListener('load', () => { checkout = substance.getQueryStringParam('checkout'); key = substance.getQueryStringParam('key'); host = substance.getQueryStringParam('host'); session = substance.getQueryStringParam('session'); // If a session is provided then connect directly to that host // otherwise use the top level v0 API to create a new session if (host && session) { window.STENCILA_HOSTS = `${host}/v1/sessions!/${session}`; } else if (host) { window.STENCILA_HOSTS = `${host}/v0`; } // Mount the app substance.substanceGlobals.DEBUG_RENDERING = substance.platform.devtools; app = stencila.StencilaWebApp.mount({ archiveId: key, storageType: 'fs', storageUrl: '/edit/storage' }, window.document.body); // Remove the loading var loading = document.getElementById('loading'); loading.parentNode.removeChild(loading) // Commit button var commitBtn = document.getElementById('commit'); commitBtn.addEventListener('click', () => { commitBtn.disabled = true; commit().then(() => { commitBtn.disabled = false; }) }) }); window.addEventListener('beforeunload', () => { // Commit changes when window closed commit() }) function commit () { return app._save().then(() => { fetch(`/checkouts/${checkout}/save/`, { method: 'POST', credentials: 'same-origin' }) }) }
Change var names and use save endpoint
Change var names and use save endpoint
JavaScript
apache-2.0
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
6bb1a3ca881b6c7e0a20e5e049c211a79183ff6e
src/disclosures/js/dispatchers/get-school-values.js
src/disclosures/js/dispatchers/get-school-values.js
'use strict'; var stringToNum = require( '../utils/handle-string-input' ); var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
'use strict'; var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
Remove lingering but unneeded requirement call
Remove lingering but unneeded requirement call
JavaScript
cc0-1.0
mistergone/college-costs,mistergone/college-costs,mistergone/college-costs,mistergone/college-costs
c76fda7d6ed6ca449330a9d2b084732a9ffd295e
test/index.js
test/index.js
import test from "ava"; import {newUnibeautify, Beautifier} from "unibeautify"; import beautifier from "../dist"; test.beforeEach((t) => { t.context.unibeautify = newUnibeautify(); }); test("should successfully install beautifier", (t) => { const {unibeautify} = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); test("should successfully beautify JavaScript text", (t) => { const {unibeautify} = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; return unibeautify.beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2 } }, text }).then((results) => { t.is(results, beautifierResult); }); });
import test from "ava"; import { newUnibeautify, Beautifier } from "unibeautify"; import beautifier from "../dist"; test.beforeEach(t => { t.context.unibeautify = newUnibeautify(); }); test("should successfully install beautifier", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); test("should successfully beautify JavaScript text with 2 space indentation", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; return unibeautify .beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2 } }, text }) .then(results => { t.is(results, beautifierResult); }); }); test("should successfully beautify JavaScript text with double quotes", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `console.log('hello world');`; const beautifierResult = `console.log("hello world");`; return unibeautify .beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2, convert_quotes: "double" } }, text }) .then(results => { t.is(results, beautifierResult); }); });
Add test for double quotes
Add test for double quotes
JavaScript
mit
Unibeautify/beautifier-prettydiff,Unibeautify/beautifier-prettydiff
00f048fe44190a4df276a6c9ddf2a80359ecd1a8
test/reverse_urlSpec.js
test/reverse_urlSpec.js
(function () { 'use strict'; describe('Unit: angular-reverse-url', function () { beforeEach(module('angular-reverse-url')); describe('reverseUrl filter', function () { }); }); }());
(function () { 'use strict'; var reverseUrl, $route; var routeMock = {}; routeMock.routes = { '/testRoute1/': { controller: 'TestController1', originalPath: '/test-route-1/' }, '/testRoute1/:params/': { controller: 'TestController1', originalPath: '/test-route-1/:param/' }, '/testRoute2/': { name: 'TestRoute2', originalPath: '/test-route-2/' }, }; describe('Unit: angular-reverse-url', function () { beforeEach(module('angular-reverse-url', function ($provide) { $provide.value('$route', routeMock); })); describe('reverseUrl filter', function () { beforeEach(inject(function ($injector) { $route = $injector.get('$route') reverseUrl = $injector.get('$filter')('reverseUrl'); })); it('should correctly match to a basic route by controller', function () { expect(reverseUrl('TestController1')).toEqual('#/test-route-1/'); }); it('should correctly match to a basic route by name', function () { expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/'); }); it('should correctly match to a route with params', function () { expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/'); }); }); }); }());
Add tests for existing functionality
Add tests for existing functionality
JavaScript
mit
incuna/angular-reverse-url
f7215986927ab3136b878bda5654d6fffc2d0fc1
app/components/github-team-notices.js
app/components/github-team-notices.js
import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set("contents", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get("contents"); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy("url", existingItem.get("url")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy("url", item.url); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set("dashEventType", "Pull Request"); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices;
import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set("contents", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get("contents"); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy("id", existingItem.get("id")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy("url", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set("dashEventType", "Pull Request"); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices;
Fix existing item recognition in "Code" widget.
Fix existing item recognition in "Code" widget.
JavaScript
mit
substantial/substantial-dash-client
b5c332043213eaf57bc56c00b24c51728a6f3041
test/server/app_test.js
test/server/app_test.js
var should = require('chai').should(), expect = require('chai').expect, supertest = require('supertest'), config = require('config'), port = config.get('port'), testingUrl = 'http://localhost:' + port, api = supertest(testingUrl) describe('Get /', () => { it('should render the homepage', (done) => { api.get('/') .expect(200, done) }) } ) describe('Post ', () =>{ var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('creates an account', (done) => { api.post('/signup') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { user_response = res.body.user return (user_response.hasOwnProperty('email') && user_response.hasOwnProperty('username') && user_response.hasOwnProperty('firstName') && user_response.hasOwnProperty('lastName')) }) .end(done) })
var should = require('chai').should(), expect = require('chai').expect, supertest = require('supertest'), config = require('config'), port = config.get('port'), testingUrl = 'http://localhost:' + port, api = supertest(testingUrl) describe('Get /', () => { it('should render the homepage', (done) => { api.get('/') .expect(200, done) }) } ) describe('Post ', () =>{ var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('creates an account', (done) => { api.post('/signup') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { user_response = res.body.user return (user_response.hasOwnProperty('email') && user_response.hasOwnProperty('username') && user_response.hasOwnProperty('firstName') && user_response.hasOwnProperty('lastName')) }) .end(done) })}) describe('Post ', () =>{ //need to have an exising user var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('logs into an account', (done) => { // user should already exist bc there is currently no setup or teardown api.post('/login') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { login_response = res.body.user // not sure this is right either return ((login_response.hasOwnProperty('user') && login_response.hasOwnProperty('token'))) }) .end(done) } ) })
Add failing test for login
Add failing test for login
JavaScript
mit
tylergreen/react-redux-express-app,tylergreen/react-redux-express-app
3f5acc776fed90572762275e82bab94224c52bcf
app/src/index.js
app/src/index.js
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import MainScreen from './react/MainScreen'; import config from './config'; import SculptureApp from './app'; window.onload = () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root')); };
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import MainScreen from './react/MainScreen'; import config from './config'; import SculptureApp from './app'; // Read all all local storage and overwrite the corresponding values in the given config object // Returns a promise function applyFromLocalStorage(config) { return new Promise((resolve, reject) => { chrome.storage.local.get(null, (items) => { if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); } else { for (let key of Object.keys(items)) { config[key] = items[key]; } resolve(true); } }); }); } window.onload = async () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); // Apply config from Chrome local storage to anyware_config await applyFromLocalStorage(anyware_config); // Apply config from the global variable anyware_config config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root')); };
Support per-sculpture overrides in local storage
Support per-sculpture overrides in local storage
JavaScript
mit
anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client