commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
e825b025f3e7e2c96cf73ae669e70161bb1e6b7e
app/assets/javascripts/umlaut/ajax_windows.js
app/assets/javascripts/umlaut/ajax_windows.js
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { data = $(data); var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); if (submit) $("#modal .modal-footer").html(submit.wrap('<div>').parent().html()); $("#modal").modal("show"); } var display_modal = function(event) { event.preventDefault(); $.get(this.href, "", populate_modal, "html"); return false; } var ajax_form_catch = function(event) { event.preventDefault(); var form = $("#modal form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); return false; }; $("a.ajax_window").live("click", display_modal); $("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch); $("#modal form").live("submit", ajax_form_catch); });
/* ajax_windows.js. Support for modal popup windows in Umlaut items. */ jQuery(document).ready(function($) { var populate_modal = function(data, textStatus, jqXHR) { data = $(data); var heading = data.find("h1, h2, h3, h4, h5, h6").eq(0).remove(); $("#modal .modal-header h3").text(heading.text()); var submit = data.find("form input[type=submit]").eq(0).remove(); $("#modal .modal-body").html(data.html()); footer = $("#modal .modal-footer") var old_submit = footer.find("#modal .modal-footer input[type=submit]").eq(0).remove(); if (submit) { footer.prepend(submit); } $("#modal").modal("show"); } var display_modal = function(event) { event.preventDefault(); $.get(this.href, "", populate_modal, "html"); return false; } var ajax_form_catch = function(event) { event.preventDefault(); var form = $("#modal form"); $.post(form.attr("action"), form.serialize(), populate_modal, "html"); return false; }; $("a.ajax_window").live("click", display_modal); $("#modal .modal-footer input[type=submit]").live("click", ajax_form_catch); $("#modal form").live("submit", ajax_form_catch); });
Update to handle modal window submits.
Update to handle modal window submits.
JavaScript
mit
team-umlaut/umlaut,team-umlaut/umlaut,team-umlaut/umlaut
6cdc555485a9fba147558341eed8a11b2a63efd7
lib/CordovaPluginAdapter.js
lib/CordovaPluginAdapter.js
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; CordovaPluginAdapter.prototype.exec = function(success, fail, service, action, args) { var callbackId = [service, action, this._callbackCount].join(':'); this._callbacks[callbackId] = { success: success, fail: fail }; this.nativeInterface.exec(service, action, callbackId, JSON.stringify(args)); this._callbackCount++; }; CordovaPluginAdapter.prototype.initCallbackChannel = function() { RCTDeviceEventEmitter.addListener('CordovaWebViewProxy', this.onChannelCallback, this); }; CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { var result = params.message; try { if (params.status === 1) { this._callbacks[params.callbackId].success(result); } else if (params.status === 1) { this._callbacks[params.callbackId].fail(result); } } finally { if (!params.keepCallback) { delete this._callbacks[params.callbackId]; } } } }; module.exports = CordovaPluginAdapter;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; CordovaPluginAdapter.prototype.exec = function(success, fail, service, action, args) { var callbackId = [service, action, this._callbackCount].join(':'); this._callbacks[callbackId] = { success: success, fail: fail }; this.nativeInterface.exec(service, action, callbackId, JSON.stringify(args)); this._callbackCount++; }; CordovaPluginAdapter.prototype.initCallbackChannel = function() { RCTDeviceEventEmitter.addListener('CordovaWebViewProxy', this.onChannelCallback, this); }; CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { var result = JSON.parse(params.message); try { if (params.status === 1) { this._callbacks[params.callbackId].success(result); } else if (params.status === 1) { this._callbacks[params.callbackId].fail(result); } } finally { if (!params.keepCallback) { delete this._callbacks[params.callbackId]; } } } }; module.exports = CordovaPluginAdapter;
Return object, not string from Cordova plugin calls
Return object, not string from Cordova plugin calls
JavaScript
isc
axemclion/react-native-cordova-plugin,axemclion/react-native-cordova-plugin
476629c71af2137a81c276d93abaa87946e6ccbc
vendor/ember-intercom-io.js
vendor/ember-intercom-io.js
(function() { /* globals define, Intercom */ function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } function setupIntercom(config) { var ic = window.Intercom || null; if (typeof ic === 'function') { ic('reattach_activator'); ic('update', {}); } else { var d = document; var i = function() { i.c(arguments); }; i.q = []; i.c = function(args) { i.q.push(args); }; window.Intercom = i; var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = `https://widget.intercom.io/widget/${Ember.get(config, 'intercom.appId')}`; var [x] = d.getElementsByTagName('script'); x.parentNode.insertBefore(s, x); } } generateModule('ember-intercom-io', { 'setupIntercom': setupIntercom }); })();
(function() { /* globals define, Intercom */ function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } function setupIntercom(config) { var ic = window.Intercom || null; if (typeof ic === 'function') { ic('reattach_activator'); ic('update', {}); } else { var d = window.document; var i = function() { i.c(arguments); }; i.q = []; i.c = function(args) { i.q.push(args); }; window.Intercom = i; var s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://widget.intercom.io/widget/' + Ember.get(config, 'intercom.appId'); var x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } } generateModule('ember-intercom-io', { 'setupIntercom': setupIntercom }); })();
Use es5 for node.js code, to make phantom happy
Use es5 for node.js code, to make phantom happy
JavaScript
mit
levanto-financial/ember-intercom-io,seawatts/ember-intercom-io,mike-north/ember-intercom-io,levanto-financial/ember-intercom-io,mike-north/ember-intercom-io,seawatts/ember-intercom-io
2cef9ebfa7c747e96db3a8d8e2a3dce9a3e74c82
test/stub/ns.tmpl.js
test/stub/ns.tmpl.js
beforeEach(function() { function genViewHTML(id, view) { var html = ''; var clazz = 'ns-view-' + id; if (view.async) { clazz += ' ns-async'; } if (view.collection) { clazz += ' ns-view-container-desc'; } if (view.placeholder) { clazz += ' ns-view-placeholder'; } html += '<div class="' + clazz + '" data-key="' + view.key + '">'; // don't create child views in async state if (!view.async) { html += genHTML(view.views); } html += '</div>'; return html; } function genHTML(views) { var html = ''; for (var id in views) { var view = views[id]; // collection if (Array.isArray(view)) { view.forEach(function(collectionItem) { html += genViewHTML(id, collectionItem); }); } else { html += genViewHTML(id, view); } } return html; } sinon.stub(ns, 'tmpl', function(json) { return ns.html2node('<div class="root">' + genHTML(json.views) + '</div>'); }); }); afterEach(function() { ns.tmpl.restore(); });
beforeEach(function() { function genViewHTML(id, view) { var html = ''; var clazz = 'ns-view-' + id; if (view.async) { clazz += ' ns-async'; } if (view.collection) { clazz += ' ns-view-container-desc'; } if (view.placeholder) { clazz += ' ns-view-placeholder'; } html += '<div class="' + clazz + '" data-key="' + view.key + '" data-random="' + Math.random() + '">'; // don't create child views in async state if (!view.async) { html += genHTML(view.views); } html += '</div>'; return html; } function genHTML(views) { var html = ''; for (var id in views) { var view = views[id]; // collection if (Array.isArray(view)) { view.forEach(function(collectionItem) { html += genViewHTML(id, collectionItem); }); } else { html += genViewHTML(id, view); } } return html; } sinon.stub(ns, 'tmpl', function(json) { return ns.html2node('<div class="root">' + genHTML(json.views) + '</div>'); }); }); afterEach(function() { ns.tmpl.restore(); });
Add random key to generated nodes to simple get same it or not
Add random key to generated nodes to simple get same it or not
JavaScript
mit
yandex-ui/noscript,Rebulus/noscript,mishk0/noscript
c7ff1ef3550c46c3ee97740c97ca1d47a3914217
src/components/encrypt/EncryptKeyListItem.js
src/components/encrypt/EncryptKeyListItem.js
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; class EncryptKeyListItem extends Component { classes() { return { 'default': { }, }; } render() { return <div></div>; } } export default ReactCSS(EncryptKeyListItem);
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; import { User } from '../common/index'; import colors from '../../styles/variables/colors'; import { spacing, sizing } from '../../styles/variables/utils'; class EncryptKeyListItem extends Component { classes() { return { 'default': { user: { padding: `${spacing.m}px ${spacing.m}px ${spacing.m}px`, display: 'flex', }, spaceLine: { borderBottom: `solid 1px ${colors.offBgLight}`, margin: `0px ${spacing.m}px 0px ${spacing.m + sizing.avatar + spacing.s}px`, item: 1, }, }, }; } render() { return <div></div>; } } export default ReactCSS(EncryptKeyListItem);
Add encrypt key list item styles
Add encrypt key list item styles
JavaScript
mit
henryboldi/felony,tobycyanide/felony,henryboldi/felony,tobycyanide/felony
9fcd1742f83e9759d0b8d7fd4338cd6149a19a07
PageTool/Analytics/Include/Analytics.tool.js
PageTool/Analytics/Include/Analytics.tool.js
var _gaq = _gaq || []; _gaq.push(['_setAccount', '{ANALYTICS_CODE}']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js', '__gaTracker'); __gaTracker('create', '{ANALYTICS_CODE}', 'teawars.com'); __gaTracker('send', 'pageview');
Update to use Universal Tracking
Update to use Universal Tracking
JavaScript
mit
phpgt/webengine
2d0d320d058b08703a1c4ce746c6cd5e0c976acb
webui/src/app/core/providers.resource.js
webui/src/app/core/providers.resource.js
'use strict'; var angular = require('angular'); var traefikCoreProvider = 'traefik.core.provider'; module.exports = traefikCoreProvider; angular .module(traefikCoreProvider, ['ngResource']) .factory('Providers', Providers); /** @ngInject */ function Providers($resource, $q) { const resourceProvider = $resource('../api/providers'); return { get: function () { return $q((resolve, reject) => { resourceProvider.get() .$promise .then((rawProviders) => { for (let providerName in rawProviders) { if (rawProviders.hasOwnProperty(providerName)) { if (!providerName.startsWith('$')) { // BackEnds mapping let bckends = rawProviders[providerName].backends || {}; rawProviders[providerName].backends = Object.keys(bckends) .map(key => { const goodBackend = bckends[key]; goodBackend.backendId = key; return goodBackend; }); // FrontEnds mapping let frtends = rawProviders[providerName].frontends || {}; rawProviders[providerName].frontends = Object.keys(frtends) .map(key => { const goodFrontend = frtends[key]; goodFrontend.frontendId = key; return goodFrontend; }); } } } resolve(rawProviders); }) .catch(reject); }); } }; }
'use strict'; var angular = require('angular'); var traefikCoreProvider = 'traefik.core.provider'; module.exports = traefikCoreProvider; angular .module(traefikCoreProvider, ['ngResource']) .factory('Providers', Providers); /** @ngInject */ function Providers($resource, $q) { const resourceProvider = $resource('../api/providers'); return { get: function () { return $q((resolve, reject) => { resourceProvider.get() .$promise .then((rawProviders) => { delete rawProviders.acme; delete rawProviders.ACME; for (let providerName in rawProviders) { if (rawProviders.hasOwnProperty(providerName)) { if (!providerName.startsWith('$')) { // BackEnds mapping let bckends = rawProviders[providerName].backends || {}; rawProviders[providerName].backends = Object.keys(bckends) .map(key => { const goodBackend = bckends[key]; goodBackend.backendId = key; return goodBackend; }); // FrontEnds mapping let frtends = rawProviders[providerName].frontends || {}; rawProviders[providerName].frontends = Object.keys(frtends) .map(key => { const goodFrontend = frtends[key]; goodFrontend.frontendId = key; return goodFrontend; }); } } } resolve(rawProviders); }) .catch(reject); }); } }; }
Remove useless ACME tab from UI.
Remove useless ACME tab from UI.
JavaScript
mit
containous/traefik,aantono/traefik,vdemeester/traefik,FriggaHel/traefik,aantono/traefik,ldez/traefik,vdemeester/traefik,containous/traefik,aantono/traefik,dtomcej/traefik,mmatur/traefik,FriggaHel/traefik,aantono/traefik,ldez/traefik,mmatur/traefik,mmatur/traefik,dtomcej/traefik,vdemeester/traefik,mmatur/traefik,SantoDE/traefik,SantoDE/traefik,ldez/traefik,dtomcej/traefik,aantono/traefik,ldez/traefik,FriggaHel/traefik,SantoDE/traefik,dtomcej/traefik,containous/traefik,FriggaHel/traefik,vdemeester/traefik,containous/traefik,SantoDE/traefik
f5cdb43607f9894f915e266b634a88e3577cbe05
bin/gh.js
bin/gh.js
#!/usr/bin/env node /* * Copyright 2013-2015, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Eduardo Lundgren <edu@rdo.io> */ 'use strict'; var path = require('path'), fs = require('fs'), logger = require('../lib/logger'), pkg = require('../package.json'), semver = require('semver'), tracker = require('../lib/tracker'), configs = require('../lib/configs'); // Check node version if (!isCompatibleNodeVersion()) { logger.error('Please update your NodeJS version: http://nodejs.org/download'); } if (!fs.existsSync(configs.getUserHomePath())) { configs.createGlobalConfig(); } // If configs.PLUGINS_PATH_KEY is undefined, try to cache it before proceeding. if (configs.getConfig()[configs.PLUGINS_PATH_KEY] === undefined) { configs.getNodeModulesGlobalPath(); } // -- Env ------------------------------------------------------------------------------------------ try { process.env.GH_PATH = path.join(__dirname, '../'); require('../lib/cmd.js').run(); } catch (e) { tracker.track('error'); throw e; } function isCompatibleNodeVersion() { return semver.satisfies(process.version, pkg.engines.node); }
#!/usr/bin/env node /* * Copyright 2013-2015, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Eduardo Lundgren <edu@rdo.io> */ 'use strict'; var path = require('path'), fs = require('fs'), logger = require('../lib/logger'), pkg = require('../package.json'), semver = require('semver'), tracker = require('../lib/tracker'), configs = require('../lib/configs'); // Check node version function isCompatibleNodeVersion() { return semver.satisfies(process.version, pkg.engines.node); } if (!isCompatibleNodeVersion()) { logger.error('Please update your NodeJS version: http://nodejs.org/download'); } if (!fs.existsSync(configs.getUserHomePath())) { configs.createGlobalConfig(); } // If configs.PLUGINS_PATH_KEY is undefined, try to cache it before proceeding. if (configs.getConfig()[configs.PLUGINS_PATH_KEY] === undefined) { configs.getNodeModulesGlobalPath(); } // -- Env ------------------------------------------------------------------------------------------ try { process.env.GH_PATH = path.join(__dirname, '../'); require('../lib/cmd.js').run(); } catch (e) { tracker.track('error'); throw e; }
Fix linting issue. Source formatting.
Fix linting issue. Source formatting.
JavaScript
bsd-3-clause
oouyang/gh,tomzx/gh,henvic/gh,modulexcite/gh,TomzxForks/gh,tomzx/gh,dustinryerson/gh,oouyang/gh,henvic/gh,modulexcite/gh,TomzxForks/gh,dustinryerson/gh
7df460bdc5be6aadb2a0d20bddf6c2648652639c
modules/ext.pageTriage.util/ext.pageTriage.viewUtil.js
modules/ext.pageTriage.util/ext.pageTriage.viewUtil.js
$( function() { if ( !mw.pageTriage ) { mw.pageTriage = {}; } mw.pageTriage.viewUtil = { // fetch and compile a template, then return it. // args: view, template template: function( arg ) { apiRequest = { 'action': 'pagetriagetemplate', 'view': arg.view, 'format': 'json' }; var templateText; if( arg.template instanceof Array ) { apiRequest.template = arg.template.join('|'); } else { apiRequest.template = arg.template; } $.ajax( { type: 'post', url: mw.util.wikiScript( 'api' ), data: apiRequest, dataType: 'json', async: false, success: function( result ) { if( result.pagetriagetemplate.result == 'success' ) { templateText = result.pagetriagetemplate.template; } } } ); return _.template( templateText ); } }; } );
$( function() { if ( !mw.pageTriage ) { mw.pageTriage = {}; } mw.pageTriage.viewUtil = { // fetch and compile a template, then return it. // args: view, template template: function( arg ) { apiRequest = { 'action': 'pagetriagetemplate', 'view': arg.view, 'format': 'json' }; var templateText; if( arg.template instanceof Array ) { apiRequest.template = arg.template.join('|'); } else { apiRequest.template = arg.template; } $.ajax( { type: 'post', url: mw.util.wikiScript( 'api' ), data: apiRequest, dataType: 'json', async: false, success: function( result ) { if ( result.pagetriagetemplate !== undefined && result.pagetriagetemplate.result === 'success' ) { templateText = result.pagetriagetemplate.template; } } } ); return _.template( templateText ); } }; } );
Make sure some results were returned to avoid error.
Make sure some results were returned to avoid error. Change-Id: Ic788bd1be6711e8c9475909562514d66c6a26d4c
JavaScript
mit
wikimedia/mediawiki-extensions-PageTriage,wikimedia/mediawiki-extensions-PageTriage,wikimedia/mediawiki-extensions-PageTriage
f1f97709aaed83b7cc3bac30d795650519d417aa
app/assets/javascripts/controller/router.js
app/assets/javascripts/controller/router.js
var AppRouter = Backbone.Router.extend({ routes: { 'topics/:topicId': 'showResults', '*actions': 'defaultAction' }, showResults: function(topicId) { if ($('#topics-container').length === 0) { this.defaultAction(); } var resultsView = new ResultsView(); resultsView.render(); var topicCharts = new TopicCharts([], { topicId: topicId }); topicCharts.fetch({ success: function(response) { var topicChartsView = new TopicChartsView({ collection: response.models }); topicChartsView.render(); // Ensure that the correct option is displayed as 'selected' in the dropdown. $('option:nth-child(' + (parseInt(topicId)+1) + ')').attr('selected', true); } }); }, defaultAction: function() { var homeView = new HomeView(); homeView.render(); } });
var AppRouter = Backbone.Router.extend({ routes: { 'topics/:topicId': 'showResults', '*actions': 'defaultAction' }, showResults: function(topicId) { if ($('#topics-container').length === 0) { this.defaultAction(); } var resultsView = new ResultsView(); resultsView.render(); var topicCharts = new TopicCharts([], { topicId: topicId }); topicCharts.fetch({ success: function(response) { $('option:nth-child(' + (parseInt(topicId)+1) + ')').attr('selected', true); var topicChartsView = new TopicChartsView({ collection: response.models }); topicChartsView.render(); // Ensure that the correct option is displayed as 'selected' in the dropdown. } }); }, defaultAction: function() { var homeView = new HomeView(); homeView.render(); } });
Fix refresh bug by ensuring the correct dropdown choice is selected
Fix refresh bug by ensuring the correct dropdown choice is selected
JavaScript
mit
Jasmine-Feldmann/pollarity,Jasmine-Feldmann/pollarity,zebogen/pollarity,Jasmine-Feldmann/pollarity,zebogen/pollarity,zebogen/pollarity,zebogen/pollarity,Jasmine-Feldmann/pollarity
d28e387391f8ea3aa46932e6ec0ae75f28f2f4ae
app/assets/javascripts/spending_averages.js
app/assets/javascripts/spending_averages.js
$(function () { $('#spending-averages').highcharts({ chart: { type: 'bar' }, title: { text: 'Historic World Population by Region' }, subtitle: { text: 'Source: <a href="https://en.wikipedia.org/wiki/World_population">Wikipedia.org</a>' }, yAxis: { categories: ['Housing', 'Transportation', 'Food', 'Phone', 'Misc'], title: { text: null } }, xAxis: { min: 0, title: { text: 'Population (millions)', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { valueSuffix: ' millions' }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 80, floating: true, borderWidth: 1, backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'), shadow: true }, credits: { enabled: false }, series: [{ name: 'Your spending', data: [107, 31, 635, 203, 2] }, { name: 'Average Spending', data: [133, 156, 947, 408, 6] }] }); });
$(function () { $('#spending-averages').highcharts({ chart: { type: 'bar' }, title: { text: 'Historic World Population by Region' }, subtitle: { text: 'Source: <a href="https://en.wikipedia.org/wiki/World_population">Wikipedia.org</a>' }, yAxis: { categories: ['Housing', 'Transportation', 'Food', 'Phone', 'Misc'], title: { text: null } }, xAxis: { min: 0, title: { text: 'Population (millions)', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { valueSuffix: ' millions' }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 80, floating: true, borderWidth: 1, backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'), shadow: true }, credits: { enabled: false }, series: [{ name: 'Your spending', data: [107, 31, 635, 203, 5] }, { name: 'Average Spending', data: [35, 15, 7, 3, 30, 10] }] }); });
Add data for national avrages
Add data for national avrages
JavaScript
mit
nyc-cicadas-2015/Can-I-Afford-This,nyc-cicadas-2015/Can-I-Afford-This,nyc-cicadas-2015/Can-I-Afford-This
292eab2125b76d48c175559e8cbd1198ef53510c
app/polymer/src/server/config/babel.prod.js
app/polymer/src/server/config/babel.prod.js
module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ [ require.resolve('babel-preset-env'), { targets: { browsers: ['last 2 versions', 'safari >= 7'], }, modules: false, }, ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), require.resolve('babel-preset-minify'), ], plugins: [ require.resolve('babel-plugin-transform-regenerator'), [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ [ require.resolve('babel-preset-env'), { targets: { browsers: ['last 2 versions', 'safari >= 7'], }, modules: false, }, ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), [ require.resolve('babel-preset-minify'), { mangle: false, }, ], ], plugins: [ require.resolve('babel-plugin-transform-regenerator'), [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
Set mangle to false in babel-preset-minify for polymer to fix static build
Set mangle to false in babel-preset-minify for polymer to fix static build
JavaScript
mit
storybooks/storybook,rhalff/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook,rhalff/storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook
42500591eb8048396af67dac18e155e28ba6de03
_attachments/script/paste.js
_attachments/script/paste.js
jQuery(function($) { /* tab insertion handling */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; this.value = this.value.slice(0, start) + '\t' + this.value.slice(end); this.setSelectionRange(start + 1, start + 1); this.scrollTop = top; e.preventDefault(); } else if (document.selection.createRange) { this.selection = document.selection.createRange(); this.selection.text = '\t'; e.returnValue = false; } } }) $('#paste').click(function(e) { var doc = {}; doc.title = $('#title').val().trim(); doc.content = $('#code').val().trim(); var tags = $('#tags').val().split(','); doc.tags = tags.map(function(t) {return t.trim()}); $Couch.create(doc, './ddoc/_update/create').done(function (data) { window.location.pathname += data._id; }) return false; //e.preventDefault(); }) })
jQuery(function($) { /* tab handling - gemo style */ $('#code').keydown(function(e) { if (e.keyCode == 9 && !e.ctrlKey && !e.altKey) { if (this.setSelectionRange) { var start = this.selectionStart; var end = this.selectionEnd; var top = this.scrollTop; var selected = this.value.slice(start, end); if (e.shiftKey) { // deindent var replacement = selected.replace(/^\t/gm, ''); } else { // indent var replacement = selected.replace(/^/gm, '\t'); } this.value = this.value.slice(0, start) + replacement + this.value.slice(end); this.setSelectionRange(start, end + replacement.length - selected.length ); this.scrollTop = top; e.preventDefault(); } else if (document.selection.createRange) { this.selection = document.selection.createRange(); this.selection.text = '\t'; e.returnValue = false; } } }) $('#paste').click(function(e) { var doc = {}; doc.title = $('#title').val().trim(); doc.content = $('#code').val().trim(); var tags = $('#tags').val().split(','); doc.tags = tags.map(function(t) {return t.trim()}); $Couch.create(doc, './ddoc/_update/create').done(function (data) { window.location.pathname += data._id; }) return false; //e.preventDefault(); }) })
Indent and deindent selected block of text - gemo style
Indent and deindent selected block of text - gemo style
JavaScript
mit
gdamjan/paste-couchapp
2569ab19ab1ae516451a8018b8911fd82c72e100
array/common-elements-two-arrays.js
array/common-elements-two-arrays.js
// Program that identifies common element(s) that exist within both two arrays function intersection(firstArray, secondArray) { var hashMap = {}; var commonElements = []; // create hashmap with elements of first array as keys arrOne.forEach(function(element) { hashMap[element] = 1; }) }
// Program that identifies common element(s) that exist within both two arrays function intersection(firstArray, secondArray) { var hashMap = {}; var commonElements = []; // create hashmap with elements of first array as keys arrOne.forEach(function(element) { hashMap[element] = 1; }) // use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array) secondArray.forEach(function(element) { // iterate through entire second array if (hashMap[element] === 1) { // if element in second array exists in hashmap commonElements.push(element); // add matching element into output array } }); }
Use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array), iterating through entire second array
Use hashmap's O(1) look up time to check if an element in second array exists in the hash (i.e. first array), iterating through entire second array
JavaScript
mit
derekmpham/interview-prep,derekmpham/interview-prep
79019f506fe1fef40d1edb4e79ab4ca732403d1a
webpack-cfg/alias.js
webpack-cfg/alias.js
module.exports = { resolve: { alias: { // Use non-compiled version of the following libraries 'reselect': 'reselect/src/index.js', // Use non-compiled version of the following react libraries 'react-icon-base': 'react-icon-base/index.js', 'react-collapse': 'react-collapse/src/index.js', 'react-height': 'react-height/src/index.js', 'react-i18next': 'react-i18next/src/index.js', 'react-sortable-hoc': 'react-sortable-hoc/dist/es6' } } }
module.exports = { resolve: { alias: { // Use non-compiled version of the following libraries 'reselect': 'reselect/src/index.js', 'react-redux-firebase': 'react-redux-firebase/es' } } }
Use ES module of react-redux-firebase
Use ES module of react-redux-firebase
JavaScript
mit
jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend
13893fdda355e822af305b3863c07ceeba88a13a
init.js
init.js
requirejs.config({ paths: { 'jquery': './lib/components/jquery/dist/jquery.min' } }); require( [ 'src/graph' ] , function( Graph ) { var functions = [ function( domGraph, domSource ) { var g1 = new Graph( domGraph ); var serie = g1.newSerie("serieTest") .setLabel( "My serie" ) .autoAxis() .setData( [ [1, 2], [2, 5], [3, 10] ] ) .showMarkers( true ) .setMarkerType( 1 ); var serie = g1.newSerie("serieTest") .setLabel( "My serie 2" ) .autoAxis() .setData( [ [2, 4], [3, 1], [5, 20] ] ) .setLineColor('red'); var legend = g1.makeLegend({ frame: true, frameWidth: 1, frameColor: "green", backgroundColor: "blue" }); g1.redraw( ); g1.drawSeries(); } ] for( var i = 0, l = functions.length ; i < l ; i ++ ) { functions[ i ]("example-1-graph"); $("#example-1-source").html( functions[ i ].toString() ); } } );
requirejs.config({ paths: { 'jquery': './lib/components/jquery/dist/jquery.min' } }); require( [ 'src/graph' ] , function( Graph ) { var functions = [ function( domGraph ) { var graph = new Graph( domGraph ); graph.newSerie("serieTest") .setLabel( "My serie" ) .autoAxis() .setData( [ [1, 2], [2, 5], [3, 10] ] ) .showMarkers( true ) .setMarkerType( 1 ); graph.newSerie("serieTest") .setLabel( "My serie 2" ) .autoAxis() .setData( [ [2, 4], [3, 1], [5, 20] ] ) .setLineColor('red'); graph.makeLegend({ frame: true, frameWidth: 1, frameColor: "green", backgroundColor: "blue" }); graph.redraw( ); graph.drawSeries(); } ] for( var i = 0, l = functions.length ; i < l ; i ++ ) { functions[ i ]("example-1-graph"); $("#example-1-source").html( functions[ i ].toString() ); } } );
Update script for the beauty of it
Update script for the beauty of it
JavaScript
mit
NPellet/jsGraph,andcastillo/graph,NPellet/jsGraph,andcastillo/graph
5cfea2ffb89d3f81e20bb36dd5341b281fa78ada
app/assets/javascripts/scripts.js
app/assets/javascripts/scripts.js
$(function(){ $(".tablesorter").tablesorter(); $("tr[data-link]").click(function() { window.location = $(this).data("link") }); console.log('Scripts loaded.'); });
var tablesort = function() { $(".tablesorter").tablesorter(); console.log('Tablesorter loaded.'); }; $(document).on('turbolinks:load', tablesort);
Load js on turbolink refresh
Load js on turbolink refresh
JavaScript
mit
greenvault/wahlbezirke,greenvault/wahlbezirke,greenvault/wahlbezirke
324b5aba5334b203ce1a622471b41427d0b0afa6
addon/models/file-version.js
addon/models/file-version.js
import DS from 'ember-data'; import OsfModel from './osf-model'; /** * @module ember-osf * @submodule models */ /** * Model for OSF APIv2 file versions. Primarily used in relationship fields. * This model is used for basic file version metadata. To interact with file contents directly, see the `file-manager` service. * For field and usage information, see: * * https://api.osf.io/v2/docs/#!/v2/File_Versions_List_GET * * https://api.osf.io/v2/docs/#!/v2/File_Version_Detail_GET * @class FileVersion */ export default OsfModel.extend({ size: DS.attr('number'), contentType: DS.attr('fixstring') });
import DS from 'ember-data'; import OsfModel from './osf-model'; /** * @module ember-osf * @submodule models */ /** * Model for OSF APIv2 file versions. Primarily used in relationship fields. * This model is used for basic file version metadata. To interact with file contents directly, see the `file-manager` service. * For field and usage information, see: * * https://api.osf.io/v2/docs/#!/v2/File_Versions_List_GET * * https://api.osf.io/v2/docs/#!/v2/File_Version_Detail_GET * @class FileVersion */ export default OsfModel.extend({ size: DS.attr('number'), dateCreated: DS.attr('date'), contentType: DS.attr('fixstring') });
Add dateCreated to file version model
Add dateCreated to file version model
JavaScript
apache-2.0
jamescdavis/ember-osf,binoculars/ember-osf,crcresearch/ember-osf,baylee-d/ember-osf,CenterForOpenScience/ember-osf,binoculars/ember-osf,jamescdavis/ember-osf,chrisseto/ember-osf,baylee-d/ember-osf,chrisseto/ember-osf,CenterForOpenScience/ember-osf,crcresearch/ember-osf
870d438d162750d7b3b0586702ec551352200c10
client/app/scripts/services/meta-machine.js
client/app/scripts/services/meta-machine.js
angular .module('app') .factory('MetaMachine', function($rootScope) { var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; $rootScope.title = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; } }; return MetaMachine; });
angular .module('app') .factory('MetaMachine', function($rootScope) { var metaDefaults = { metaTitle: "Home | Rootstrikers", metaDescription: "We fight the corrupting influence of money in politics", metaImage: "http://facultycreative.com/img/icons/facultyicon114.png", metaUrl: "http://rs002dev.herokuapp.com/" }; (function setDefaults() { _.each(metaDefaults, function(val, key) { $rootScope[key] = val; }); })(); var MetaMachine = { title: function(pageTitle, baseTitle) { baseTitle = typeof baseTitle != 'undefined' ? baseTitle : "Rootstrikers"; $rootScope.metaTitle = typeof pageTitle != 'undefined' ? pageTitle + " | " + baseTitle : baseTitle; }, description: function(description) { $rootScope.metaDescription = description || "We fight the corrupting influence of money in politics"; }, image: function(url) { $rootScope.metaImage = url || "http://facultycreative.com/img/icons/facultyicon114.png"; }, url: function(url) { $rootScope.metaUrl = url || "http://rs002dev.herokuapp.com/"; } }; return MetaMachine; });
Update MetaMachine directive to add a metaImage tag and metaUrl tag (OG tags for Facebook). Directive now also sets page defaults.
Update MetaMachine directive to add a metaImage tag and metaUrl tag (OG tags for Facebook). Directive now also sets page defaults.
JavaScript
mit
brettshollenberger/rootstrikers,brettshollenberger/rootstrikers
083e928a4b8260b92646fe2ce14a34b6e67c8bb4
app/initializers/clock-service.js
app/initializers/clock-service.js
// Based on "Continous Redrawing of Objects" // http://emberjs.com/guides/cookbook/working_with_objects/continuous_redrawing_of_views/ // // #pulse is updated every ~15-seconds // var ClockService = Ember.Object.extend({ pulse: Ember.computed.oneWay('_minutes').readOnly(), tick: function () { var clock = this; Ember.run.later(function () { var minutes = clock.get('_minutes'); if (typeof minutes === 'number') { clock.set('_minutes', minutes + (1/4)); } }, 15000); }.observes('_minutes').on('init'), _minutes: 0 }); var ClockServiceInitializer = { name: "clock-service", initialize: function(container, application) { container.register('clock:service', ClockService, { singleton: true }); application.inject('view', 'clock', 'clock:service'); } }; export default ClockServiceInitializer;
// Based on "Continous Redrawing of Objects" // http://emberjs.com/guides/cookbook/working_with_objects/continuous_redrawing_of_views/ // // #pulse is updated every ~15-seconds // var ClockService = Ember.Object.extend({ pulse: Ember.computed.oneWay('_minutes').readOnly(), tick: function () { var clock = this; // This should be the idiomatic `Ember.run.later` but that // blocks acceptance tests. This is a workaround from // https://github.com/emberjs/ember.js/issues/3008 setTimeout(function() { Em.run(function() { var minutes = clock.get('_minutes'); if (typeof minutes === 'number') { clock.set('_minutes', minutes + (1/4)); } }) }, 15000); }.observes('_minutes').on('init'), _minutes: 0 }); var ClockServiceInitializer = { name: "clock-service", initialize: function(container, application) { container.register('clock:service', ClockService, { singleton: true }); application.inject('view', 'clock', 'clock:service'); } }; export default ClockServiceInitializer;
Fix for stalling acceptance tests.
Fix for stalling acceptance tests.
JavaScript
mit
substantial/substantial-dash-client
6eed7ab4ff7ec2b9834153874d3b8813d0eda54f
src/lib/addCustomMediaQueries.js
src/lib/addCustomMediaQueries.js
import _ from 'lodash' import postcss from 'postcss' function buildMediaQuery(breakpoint) { if (_.isString(breakpoint)) { breakpoint = {min: breakpoint} } return _(breakpoint).map((value, feature) => { feature = _.get( { min: 'min-width', max: 'max-width', }, feature, feature ) return `(${feature}: ${value})` }).join(' and ') } export default function(options) { let breakpoints = options.breakpoints return function(css) { Object.keys(breakpoints).forEach(breakpoint => { const variableName = `--breakpoint-${breakpoint}` const mediaQuery = buildMediaQuery(breakpoints[breakpoint]) const rule = postcss.atRule({ name: 'custom-media', params: `${variableName} ${mediaQuery}`, }) css.prepend(rule) }) } }
import _ from 'lodash' import postcss from 'postcss' function buildMediaQuery(breakpoints) { if (_.isString(breakpoints)) { breakpoints = {min: breakpoints} } if (!_.isArray(breakpoints)) { breakpoints = [breakpoints] } return _(breakpoints).map((breakpoint) => { return _(breakpoint).map((value, feature) => { feature = _.get( { min: 'min-width', max: 'max-width', }, feature, feature ) return `(${feature}: ${value})` }).join(' and ') }).join(', ') } export default function(options) { let breakpoints = options.breakpoints return function(css) { Object.keys(breakpoints).forEach(breakpoint => { const variableName = `--breakpoint-${breakpoint}` const mediaQuery = buildMediaQuery(breakpoints[breakpoint]) const rule = postcss.atRule({ name: 'custom-media', params: `${variableName} ${mediaQuery}`, }) css.prepend(rule) }) } }
Add ability to define more complex breakpoints.
Add ability to define more complex breakpoints.
JavaScript
mit
tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss,tailwindlabs/tailwindcss
9ee00c1b2b9bb79e664d5f7ce0b9ce78478d7c1d
src/hooks/useDatePicker.js
src/hooks/useDatePicker.js
/* eslint-disable import/prefer-default-export */ import React from 'react'; /** * Hook to simplify the use of the native date picker component by unwrapping * the callback event and firing the callback only when the date is changing, * providing a value to conditionally render the native picker and a callback * to set the render value. * * Pass an onChange callback which will be called when a new date is selected * from the datepicker and not when cancelled or dismissed, with a JS date object * rather than a nativeEvent. * * @param {Func} callback callback * @return {Array} [ * datePickerIsOpen: boolean indicator whether the date picker is open. * openDatePicker: Callback function to set the datePickerIsOpen to true. * datePickerCallback: Wrapped callback, triggered on changing the date in the picker, * returning a JS date object. * ] */ export const useDatePicker = onChangeCallback => { const [datePickerIsOpen, setDatePickerIsOpen] = React.useState(false); const datePickerCallback = React.useCallback( event => { setDatePickerIsOpen(false); const { type, nativeEvent } = event; if (type === 'set' && onChangeCallback) { const { timestamp } = nativeEvent; onChangeCallback(new Date(timestamp)); } }, [onChangeCallback] ); const openDatePicker = React.useCallback(() => { setDatePickerIsOpen(true); }, []); return [datePickerIsOpen, openDatePicker, datePickerCallback]; };
/* eslint-disable import/prefer-default-export */ import React from 'react'; /** * Hook to simplify the use of the native date picker component by unwrapping * the callback event and firing the callback only when the date is changing, * providing a value to conditionally render the native picker and a callback * to set the render value. * * Pass an onChange callback which will be called when a new date is selected * from the datepicker and not when cancelled or dismissed, with a JS date object * rather than a nativeEvent. * * @param {Func} callback callback * @return {Array} [ * datePickerIsOpen: boolean indicator whether the date picker is open. * openDatePicker: Callback function to set the datePickerIsOpen to true. * datePickerCallback: Wrapped callback, triggered on changing the date in the picker, * returning a JS date object. * ] */ export const useDatePicker = onChangeCallback => { const [datePickerIsOpen, setDatePickerIsOpen] = React.useState(false); const datePickerCallback = React.useCallback( event => { setDatePickerIsOpen(false); const { type, nativeEvent } = event; if (type === 'set' && onChangeCallback) { const { timestamp } = nativeEvent; onChangeCallback(timestamp); } }, [onChangeCallback] ); const openDatePicker = React.useCallback(() => { setDatePickerIsOpen(true); }, []); return [datePickerIsOpen, openDatePicker, datePickerCallback]; };
Add pass timestamp rather than date object
Add pass timestamp rather than date object
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
e186fce706c2b219bc3c5451ee8910baaf98400c
src/data/teams/selectors.js
src/data/teams/selectors.js
import { createSelector } from 'reselect'; import { denormalize } from 'normalizr'; import mapValues from 'lodash/mapValues'; import teamSchema from './schema'; const selectPlayers = state => state.data.players; export const selectTeam = (state, props) => state.data.teams.byId[props.teamId]; export const selectTeams = state => state.data.teams; export const selectTeamPlayerItems = (state, props) => state.data.teams.byId[props.teamId].players; export const selectDenormalizedTeams = createSelector( [selectTeams, selectPlayers], (teams, players) => { const data = { teams, players }; return denormalize( Object.keys(teams.byId), [teamSchema], { ...mapValues(data, value => value.byId) }, ); }, );
import { createSelector } from 'reselect'; import { denormalize } from 'normalizr'; import mapValues from 'lodash/mapValues'; import teamSchema from './schema'; const selectPlayers = state => state.data.players; export const selectTeam = (state, props) => state.data.teams.byId[props.teamId]; export const selectTeams = state => state.data.teams; export const selectTeamPlayerItems = (state, props) => { const team = selectTeam(state, props); return team ? team.players : []; }; export const selectDenormalizedTeams = createSelector( [selectTeams, selectPlayers], (teams, players) => { const data = { teams, players }; return denormalize( Object.keys(teams.byId), [teamSchema], { ...mapValues(data, value => value.byId) }, ); }, );
Reset response errors when a new tactic is created
Reset response errors when a new tactic is created
JavaScript
mit
m-mik/tactic-editor,m-mik/tactic-editor
f1ae689d7dcffb5187b61f78dbed65d54322cbfe
quickstart/node/autopilot/query-task/query_task.3.x.js
quickstart/node/autopilot/query-task/query_task.3.x.js
// Download the helper library from https://www.twilio.com/docs/python/install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
// Download the helper library https://www.twilio.com/docs/libraries/node#install // Your Account Sid and Auth Token from twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const client = require('twilio')(accountSid, authToken); // Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list query = client.preview.understand.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .queries .create({ language: 'en-US', query: 'Tell me a joke', }) .then(query => console.log(query.results.task)) .done();
Update comment to point to node library install
Update comment to point to node library install
JavaScript
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
eb13bf4ff0d9b2f74e1de34418f0d7250fd537cc
rules/style.js
rules/style.js
module.exports = { rules: { // require trailing comma in multilines 'comma-dangle': [2, 'always-multiline'], // require function expressions to have a name 'func-names': 0, // require or disallow use of semicolons instead of ASI 'semi': [2, 'never'], // require or disallow space before function opening parenthesis 'space-before-function-paren': [2, 'never'], // require or disallow Yoda conditions 'yoda': [2, 'never'] } }
module.exports = { rules: { // disallow trailing commas in object literals 'comma-dangle': [2, 'never'], // require function expressions to have a name 'func-names': 0, // require or disallow use of semicolons instead of ASI 'semi': [2, 'never'], // require or disallow space before function opening parenthesis 'space-before-function-paren': [2, 'never'], // require or disallow Yoda conditions 'yoda': [2, 'never'] } }
Revert "[WV][000000] Allow trailing comma"
Revert "[WV][000000] Allow trailing comma"
JavaScript
mit
rentpath/eslint-config-rentpath
cc8f8d2f523a0c440bbd819610d860f86ba9d383
src/modules/findBestIcon.js
src/modules/findBestIcon.js
function sortIconsBySize(icons) { return icons.sort((a, b) => { if (a.data.size < b.data.size) { return 1; } else { return -1; } }); } function findBestIcon(icons) { return sortIconsBySize(icons)[0]; } module.exports = findBestIcon;
function sortIconsBySize(icons) { return icons.sort((a, b) => { if (a.size < b.size) { return 1; } else { return -1; } }); } function findBestIcon(icons) { return sortIconsBySize(icons)[0]; } module.exports = findBestIcon;
Fix bug where icons are not sorted properly
Fix bug where icons are not sorted properly
JavaScript
mit
jiahaog/page-icon
f4f275c057152f37855e6eb23945d07509cb2af0
res/loader.js
res/loader.js
browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages' ] ).then( function ( r ) { var m = r.messages.split( '\n' ); m = m[ Math.floor( Math.random() * m.length ) ]; document.querySelector( 'h1' ).textContent = m; document.body.style.backgroundColor = r.bgcolor; document.body.style.color = r.textcolor; console.log( r ); } );
browser.storage.local.get( [ 'bgcolor', 'textcolor', 'messages' ] ).then( function ( r ) { var m = r.messages || 'Breathe'; m = m.split( '\n' ); m = m[ Math.floor( Math.random() * m.length ) ]; document.querySelector( 'h1' ).textContent = m; document.body.style.backgroundColor = r.bgcolor || '#fff'; document.body.style.color = r.textcolor || '#b3b3b3'; console.log( r ); } );
Load sane settings if there are none
Load sane settings if there are none
JavaScript
mit
prtksxna/breathe,prtksxna/breathe
6f3cd5a14d32b86bec9c0892a75d367e89420a05
native/components/list-loading-indicator.react.js
native/components/list-loading-indicator.react.js
// @flow import { connect } from 'lib/utils/redux-utils'; import * as React from 'react'; import { ActivityIndicator } from 'react-native'; import type { AppState } from '../redux/redux-setup'; import type { Colors } from '../themes/colors'; import { colorsSelector, styleSelector } from '../themes/colors'; type Props = {| // Redux state colors: Colors, styles: typeof styles, |}; function ListLoadingIndicator(props: Props) { const { listBackgroundLabel } = props.colors; return ( <ActivityIndicator color={listBackgroundLabel} size="large" style={props.styles.loadingIndicator} /> ); } const styles = { loadingIndicator: { backgroundColor: 'listBackground', flex: 1, padding: 10, }, }; const stylesSelector = styleSelector(styles); export default connect((state: AppState) => ({ colors: colorsSelector(state), styles: stylesSelector(state), }))(ListLoadingIndicator);
// @flow import * as React from 'react'; import { ActivityIndicator } from 'react-native'; import { useStyles, useColors } from '../themes/colors'; function ListLoadingIndicator() { const styles = useStyles(unboundStyles); const colors = useColors(); const { listBackgroundLabel } = colors; return ( <ActivityIndicator color={listBackgroundLabel} size="large" style={styles.loadingIndicator} /> ); } const unboundStyles = { loadingIndicator: { backgroundColor: 'listBackground', flex: 1, padding: 10, }, }; export default ListLoadingIndicator;
Use hook instead of connect functions and HOC in ListLoadingIndicator
[native] Use hook instead of connect functions and HOC in ListLoadingIndicator Test Plan: Flow Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: zrebcu411, Adrian Differential Revision: https://phabricator.ashoat.com/D483
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
b9fa1633356d88a60e39b7e29f612d6f0a2901b0
js/population.js
js/population.js
function Population(size) { var agents = new Array(size); var genomes = new Array(size); for (i = 0; i < size; i++) { var prob = Math.random(); if (prob <= 0.33) { genomes[i] = new Genome(1,0,0); } elseif (prob > 0.33 && prob <= 0.67) { genomes[i] = new Genome(0,1,0); } else genomes[i] = new Genome(0,0,1); agents[i] = new Agent(genomes[i]); } this.pop = agents; } // "T" for tournament, "R" for roulette wheel var parentmethod = "T"; Population.prototype.parentselection = function() { // Get all fitness functions from parents if (parentmethod == "T") { // Choose parents // return parents } else if (parentmethod == "R") { } }
function Population(size) { var agents = new Array(size); var genomes = new Array(size); for (i = 0; i < size; i++) { var prob = Math.random(); if (prob < 0.33) { genomes[i] = new Genome(1,0,0); } else if (prob >= 0.33 && prob < 0.67) { genomes[i] = new Genome(0,1,0); } else genomes[i] = new Genome(0,0,1); agents[i] = new Agent(genomes[i]); } this.pop = agents; } // "T" for tournament, "R" for roulette wheel var parentmethod = "T"; Population.prototype.parentselection = function() { // Get all fitness functions from parents var fitness = new Array(this.pop.length); for (i = 0; i < this.pop.length; i++) { fitness[i] = this.pop[i].getFitness(); } // Tournament selection if (parentmethod == "T") { // Choose k individuals from population at random for (p = 0; p < 4; p++) { var k = 3; var parents = new Array(k); for (i = 0; i < tournament; i ++) { parents[i] = Math.round(Math.random() * this.pop.length); } } // return parents } // Roulette wheel selection else if (parentmethod == "R") { } } Population.prototype.update = function() { }
Edit parent selection, update gamemanager to Senna's version
Edit parent selection, update gamemanager to Senna's version
JavaScript
mit
Moorkopsoesje/natural-computing,Moorkopsoesje/natural-computing,Moorkopsoesje/natural-computing
3989a97b750c34da3963f8edb0154167fe99f2bc
addon/components/jqui-datepicker/component.js
addon/components/jqui-datepicker/component.js
import Ember from 'ember'; import jquiWidget from 'ember-cli-jquery-ui/mixins/jqui-widget'; export default Ember.TextField.extend(jquiWidget, { uiType: 'datepicker', uiOptions: ["altField", "altFormat", "appendText", "autoSize", "beforeShow", "beforeShowDay", "buttonImage", "buttonImageOnly", "buttonText", "calculateWeek", "changeMonth", "changeYear", "closeText", "constrainInput", "currentText", "dateFormat", "dayNames", "dayNamesMin", "dayNamesShort", "defaultDate", "duration", "firstDay", "gotoCurrent", "hideIfNoPrevNext", "isRTL", "maxDate", "minDate", "monthNames", "monthNamesShort", "navigationAsDateFormat", "nextText", "numberOfMonths", "onChangeMonthYear", "onClose", "onSelect", "prevText", "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", "yearSuffix"], uiEvents: ['onChangeMonthYear', 'onClose', 'onSelect'] });
import Ember from 'ember'; import jquiWidget from 'ember-cli-jquery-ui/mixins/jqui-widget'; export default Ember.TextField.extend(jquiWidget, { uiType: 'datepicker', uiOptions: ["altField", "altFormat", "appendText", "autoSize", "beforeShow", "beforeShowDay", "buttonImage", "buttonImageOnly", "buttonText", "calculateWeek", "changeMonth", "changeYear", "closeText", "constrainInput", "currentText", "dateFormat", "dayNames", "dayNamesMin", "dayNamesShort", "defaultDate", "duration", "firstDay", "gotoCurrent", "hideIfNoPrevNext", "isRTL", "maxDate", "minDate", "monthNames", "monthNamesShort", "navigationAsDateFormat", "nextText", "numberOfMonths", "onChangeMonthYear", "onClose", "onSelect", "prevText", "selectOtherMonths", "shortYearCutoff", "showAnim", "showButtonPanel", "showCurrentAtPos", "showMonthAfterYear", "showOn", "showOptions", "showOtherMonths", "showWeek", "stepMonths", "weekHeader", "yearRange", "yearSuffix"] });
Remove useless events that don't exist
Remove useless events that don't exist
JavaScript
mit
Gaurav0/ember-cli-jquery-ui,Gaurav0/ember-cli-jquery-ui
ff6e324be00554374a57e068519e40d62b9664dd
lib/router.js
lib/router.js
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('notifications'); } }); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return Meteor.subscribe('comments', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('posts/:_id/edit', { name: 'postEdit', data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); Router.route('/:postsLimit?', { name: 'postsList', waitOn: function() { var limit = parseInt(this.params.postsLimit) || 5; return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit }); } }); var requireLogin = function() { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', { only: 'postPage' }); Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('notifications'); } }); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return Meteor.subscribe('comments', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('posts/:_id/edit', { name: 'postEdit', data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); Router.route('/:postsLimit?', { name: 'postsList', waitOn: function() { var limit = parseInt(this.params.postsLimit) || 5; return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit }); }, data: function() { var limit = parseInt(this.params.postsLimit) || 5; return { posts: Posts.find({}, { sort: { submitted: -1 }, limit: limit }); } } }); var requireLogin = function() { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', { only: 'postPage' }); Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
Add dataContext to postsLimit route
Add dataContext to postsLimit route
JavaScript
mit
Bennyz/microscope,Bennyz/microscope
126873a8d5c90810789387c8e8ec90fe4ad1f3d8
lib/router.js
lib/router.js
var subscriptions = new SubsManager(); Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.route('/', { name: 'home', waitOn: function() { return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')]; }, fastRender: true }); Router.route('/ranking', { name: 'rankingWrapper', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/championship', { name: 'ChampionshipWrapper', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/search', { name: 'search', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/account', { name: 'accountWrapper', fastRender: true });
var subscriptions = new SubsManager(); Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.route('/', { name: 'home', waitOn: function() { return [subscriptions.subscribe('lastGames'), subscriptions.subscribe('allUsers')]; }, fastRender: true }); Router.route('/ranking', { name: 'rankingWrapper', waitOn: function() { return subscriptions.subscribe('allUsers'); }, data: function() { return Meteor.users.find({}, { fields: { 'profile.firstName': 1, 'profile.lastName': 1, 'profile.points': 1 } }); }, fastRender: true }); Router.route('/championship', { name: 'ChampionshipWrapper', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/search', { name: 'search', /*waitOn: function() { return subscriptions.subscribe(''); },*/ fastRender: true }); Router.route('/account', { name: 'accountWrapper', fastRender: true });
Add data for ranking route
Add data for ranking route
JavaScript
mit
dexterneo/ping_pong_wars,dexterneo/ping_pong_wars
f905f4080d45f0db635b178b2931daf93b51706e
test/server/webhookSpec.js
test/server/webhookSpec.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(() => webhook.notify(challenge, 'https://webhook.site/46beb3e9-df8f-495b-98b9-abf0d4ae38a0')).to.not.throw() }) }) })
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const chai = require('chai') const expect = chai.expect describe('webhook', () => { const webhook = require('../../lib/webhook') const challenge = { key: 'key', name: 'name' } describe('notify', () => { it('fails when no webhook URL is provided via environment variable', () => { expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument') }) it('fails when supplied webhook is not a valid URL', () => { expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"') }) it('submits POST with payload to existing URL', () => { expect(() => webhook.notify(challenge, 'https://webhook.site/#!/e3b07c99-fd53-4799-aa18-984f71009f8c')).to.not.throw() }) }) })
Update to new (unburned) webhook.site URL
Update to new (unburned) webhook.site URL
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
e7ae935573dfc193d2e7548b8eac6abec475a849
test/spec/leafbird.spec.js
test/spec/leafbird.spec.js
/* Copyright 2015 Leafbird 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. */ describe('configure', function() { it('Confugure changes on original config.', function() { var leafbrd = Leafbird({}); leafbrd.configure({}); expect(leafbrd.config).toEqual(undefined); }); it('verify if a leafbird global object has defined', function(){ expect(leafbird).toBeDefined(); }); });
/* Copyright 2015 Leafbird 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. */ describe('configure', function() { it('Confugure changes on original config.', function() { var leafbrd = Leafbird({}); leafbrd.configure({}); expect(leafbrd.config).toEqual(undefined); }); it('verify if a leafbird global object has defined', function() { expect(leafbird).toBeDefined(); }); it('verify if leafbird global variable has a Leafbird object instance', function() { if(!(leafbird instanceof Leafbird)) { fail('leafbird global variable is not a Leafbird instance.'); } }); });
Verify if leafbird global variable has a Leafbird object instance.
Verify if leafbird global variable has a Leafbird object instance.
JavaScript
apache-2.0
bscherer/leafbird,leafbirdjs/leafbird,leafbirdjs/leafbird,lucasb/leafbird,bscherer/leafbird,lucasb/leafbird
8458ca15bf929710cdfc5f0667690a22fe1ce40b
test/specs/effects.spec.js
test/specs/effects.spec.js
import * as effects from 'src/effects' /** * @jest-environment jsdom */ jest.useFakeTimers() describe('Effects', () => { let element beforeEach(() => { element = document.createElement('div') document.body.appendChild(element) }) afterEach(() => { document.body.innerHTML = '' }) test('Fade in', () => { element.style.opacity = 1 effects.fadeIn(element, 100) expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(0) jest.runAllTimers() expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { window.requestAnimationFrame = jest.fn(fn => setTimeout(fn, 1)) effects.fadeIn(element, 1) jest.runAllTimers() expect(window.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() expect(window.requestAnimationFrame).toBeCalled() delete window.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0 effects.fadeOut(element, 100) expect(Number(element.style.opacity)).toBeLessThanOrEqual(1) jest.runAllTimers() expect(Number(element.style.opacity)).toBeLessThanOrEqual(0) }) test('Hide', () => { effects.hide(element) expect(element.style.display).toBe('none') }) test('Show', () => { effects.show(element) expect(element.style.display).toBe('') }) })
import * as effects from 'src/effects' /** * @jest-environment jsdom */ jest.useFakeTimers() describe('Effects', () => { let element beforeEach(() => { element = document.createElement('div') document.body.appendChild(element) }) afterEach(() => { document.body.innerHTML = '' }) test('Fade in', () => { element.style.opacity = 1 effects.fadeIn(element, 100) expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(0) jest.runAllTimers() expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { global.requestAnimationFrame = jest.fn() effects.fadeIn(element, 1) jest.runAllTimers() expect(global.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() expect(global.requestAnimationFrame).toBeCalled() delete global.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0 effects.fadeOut(element, 100) expect(Number(element.style.opacity)).toBeLessThanOrEqual(1) jest.runAllTimers() expect(Number(element.style.opacity)).toBeLessThanOrEqual(0) }) test('Hide', () => { effects.hide(element) expect(element.style.display).toBe('none') }) test('Show', () => { effects.show(element) expect(element.style.display).toBe('') }) })
Fix fade test with RAF
test(Effects): Fix fade test with RAF Because of wrong mock implementation
JavaScript
mit
lucaperret/gaspard
5e0df55f9306d7e6eecd71881c59788a35925aec
parse-comments/lib/utils.js
parse-comments/lib/utils.js
/*! * parse-comments <https://github.com/jonschlinkert/parse-comments> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var utils = module.exports = {}; utils.trimRight = function(str) { return str.replace(/\s+$/, ''); }; utils.stripStars = function (line) { var re = /^(?:\s*[\*]{1,2}\s)/; return utils.trimRight(line.replace(re, '')); };
let utils = module.exports = {}; utils.trimRight = function(str) { return str.replace(/\s+$/, ''); }; utils.stripStars = function (line) { let re = /^(?:\s*[\*]{1,2}\s)/; return utils.trimRight(line.replace(re, '')); };
Clean up parse-comments utilis file
Clean up parse-comments utilis file
JavaScript
apache-2.0
weepower/wee-core
bd2ee45b9fad33587764f03dbeb6f39c86299ea6
js/main.js
js/main.js
var questions = [ Q1 = { question: "What do HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What do CSS means?", answer: "Cascading Style Sheet" } ]; var question = document.getElementById('question'); var questionNum = 0; function createNum() { questionNum = Math.floor(Math.random() * 2); } createNum(); question.innerHTML = questions[questionNum].question;
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0; function createNum() { questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question;
Modify and add another question
Modify and add another question
JavaScript
mit
vinescarlan/FlashCards,vinescarlan/FlashCards
265769d571df9e80462bb339c0476d8b1f4e3516
initialize.js
initialize.js
var i = (function() { 'use strict'; return { c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); if ('init' in newObj) { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } newObj.init.apply(newObj, args); } } return newObj; } } }; })();
var i = (function() { 'use strict'; return { c: function(obj, args) { if (arguments.length > 0) { var newObj = Object.create(arguments[0]); if ('init' in newObj && typeof newObj.init === 'function') { if (arguments.length > 1) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } newObj.init.apply(newObj, args); } } return newObj; } } }; })();
Check that init is a function
Check that init is a function
JavaScript
mit
delta-nry/Initialize.js,delta-nry/Initialize.js
a8bc763ab377f872355bef930bf5ad1735c25e19
app/models/UserDevice.js
app/models/UserDevice.js
module.exports = function(sequelize, DataTypes) { var UserDevice = sequelize.define('UserDevice', { type: { type: DataTypes.ENUM('IOS', 'ANDROID'), defaultValue: 'IOS' }, token: { type: DataTypes.STRING, allowNull: false } }, { classMethods: { addDevice: function(deviceInfo) { UserDevice.find({where: deviceInfo}) .success(function(device) { if(device) { } else { UserDevice.create(deviceInfo); } }); } }, associate: function(models){ UserDevice.belongsTo(models.User); } } ); return UserDevice; };
module.exports = function(sequelize, DataTypes) { var UserDevice = sequelize.define('UserDevice', { type: { type: DataTypes.ENUM('IOS', 'ANDROID'), defaultValue: 'IOS' }, token: { type: DataTypes.STRING, allowNull: false } }, { classMethods: { addDevice: function(deviceInfo) { var search = { type: deviceInfo.type, token: deviceInfo.token, }; UserDevice.find({where: search}) .success(function(device) { if(device) { device.destroy(); } UserDevice.create(deviceInfo); }); } }, associate: function(models){ UserDevice.belongsTo(models.User); } } ); return UserDevice; };
Remove duplicated device token for multiple users
Remove duplicated device token for multiple users
JavaScript
mit
barak-shirali/PDS,barak-shirali/PDS,barak-shirali/PDS,barak-shirali/PDS
dffde72e5e73cd23d2531198a0f61435ca30efb0
lib/ArgVerifier.js
lib/ArgVerifier.js
var ArgumentError = require('./ArgumentError'); var topiarist = require('topiarist'); function verifierMethod(verifier, methodName) { return function() { if(!this.skipVerification) { if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.'); verifier[methodName].apply(this, arguments); } if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) { this.argsVerifier.constructor.pendingVerifier = this.argsVerifier; } return this.argsVerifier; }; } function ArgVerifier(argsVerifier, argName, argValue) { this.argsVerifier = argsVerifier; this.argName = argName; this.argValue = argValue; } ArgVerifier.addVerifier = function(verifier) { for(var methodName in verifier) { ArgVerifier.prototype[methodName] = verifierMethod(verifier, methodName); } }; Object.defineProperty(ArgVerifier.prototype, 'optionally', { get: function optionally() { if((this.argValue === undefined) || (this.argValue === null)) { this.skipVerification = true; } return this; } }); module.exports = ArgVerifier;
var ArgumentError = require('./ArgumentError'); var topiarist = require('topiarist'); function verifierMethod(verifierMethod) { return function(arg) { if(!this.skipVerification) { if(this.argValue === undefined) throw new ArgumentError(this.argName + ' argument must be provided.'); verifierMethod.call(this, arg); } if(this.argsVerifier.argIndex < this.argsVerifier.arguments.length) { this.argsVerifier.constructor.pendingVerifier = this.argsVerifier; } return this.argsVerifier; }; } function ArgVerifier(argsVerifier, argName, argValue) { this.argsVerifier = argsVerifier; this.argName = argName; this.argValue = argValue; } ArgVerifier.addVerifier = function(verifier) { for(var methodName in verifier) { ArgVerifier.prototype[methodName] = verifierMethod(verifier[methodName]); } }; Object.defineProperty(ArgVerifier.prototype, 'optionally', { get: function optionally() { if((this.argValue === undefined) || (this.argValue === null)) { this.skipVerification = true; } return this; } }); module.exports = ArgVerifier;
Use call() rather than apply() to improve performance.
Use call() rather than apply() to improve performance.
JavaScript
apache-2.0
dchambers/typester
c532fbe1246fcf2032b09a417b27a932f0bce774
server/services/ads.spec.js
server/services/ads.spec.js
/* global describe, beforeEach, afterEach, it */ const knex_config = require('../../knexfile'); const knex = require('knex')(knex_config['test']); const chai = require('chai'); const should = chai.should(); describe('Handle ads', function() { beforeEach(function(done) { knex.migrate.rollback() .then(function() { knex.migrate.latest() .then(function() { return knex.seed.run() .then(function() { done(); }); }); }); }); afterEach(function(done) { knex.migrate.rollback() .then(function() { done(); }); }); it('should list ads in order', (done) => { done(); }) });
/* global describe, beforeEach, afterEach, it */ const chai = require('chai'); const should = chai.should(); const knex_config = require('../../knexfile'); const knex = require('knex')(knex_config['test']); const util = require('../util')({ knex }); const service = require('./ads')({ knex, util }); describe('Handle ads', function() { beforeEach(function(done) { knex.migrate.rollback() .then(function() { knex.migrate.latest() .then(function() { return knex.seed.run() .then(function() { done(); }); }); }); }); afterEach(function(done) { knex.migrate.rollback() .then(function() { done(); }); }); it('should list ads in order', (done) => { service.listAds(false).then((ads) => { ads.map(ad => ad.id).should.eql([2, 3, 1]); done(); }) }) });
Test that ads appear in date order latest first
Test that ads appear in date order latest first
JavaScript
agpl-3.0
Tradenomiliitto/tradenomiitti,Tradenomiliitto/tradenomiitti,Tradenomiliitto/tradenomiitti
9e246962370dcd7f96732b56eaa2c09d1c757626
util/transitionToParams.js
util/transitionToParams.js
import queryString from 'query-string'; function transitionToParams(params) { const location = this.props.location; let query = location.query; if (query === undefined) query = queryString.parse(location.search); const allParams = Object.assign({}, query, params); const keys = Object.keys(allParams); let url = location.pathname; if (keys.length) { url += `?${keys.map(key => `${key}=${encodeURIComponent(allParams[key])}`).join('&')}`; } this.props.history.push(url); } export default transitionToParams;
import queryString from 'query-string'; function transitionToParams(params) { const location = this.props.location; let query = location.query; if (query === undefined) query = queryString.parse(location.search); const allParams = Object.assign({}, query, params); const keys = Object.keys(allParams); let url = location.pathname; if (keys.length) { url += `?${queryString.stringify(allParams)}`; } this.props.history.push(url); } export default transitionToParams;
Use queryString.stringify instead of by-hand gluing
Use queryString.stringify instead of by-hand gluing Fixes STCOM-112
JavaScript
apache-2.0
folio-org/stripes-components,folio-org/stripes-components
09605e33cb1693d1a1cc88ee38b08d275bc9119c
views/components/addApp.js
views/components/addApp.js
import { h, Component } from 'preact' import { bind } from './util' export default class extends Component { constructor() { super() this.state.show = false } linkState(key) { return e => this.setState({ [key]: e.target.value }) } @bind toggleShow() { this.setState({ show: !this.state.show }) } clearState() { this.setState({ appName: '', username: '', password: '', show: false }) } @bind handleSubmit(e) { e.preventDefault() this.props.add(this.state.appName, this.state.username, this.state.password) this.clearState() } render(_, { show, appName, username, password }) { return ( <section> <div style={{display: show ? 'block' : 'none'}}> <form onSubmit={this.handleSubmit}> <input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} /> <input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} /> <input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} /> <button type='submit'>Save</button> </form> </div> <button onClick={this.toggleShow}>Add new app</button> </section> ) } }
import { h, Component } from 'preact' import { bind } from './util' export default class extends Component { constructor() { super() this.state.show = false } linkState(key) { return e => this.setState({ [key]: e.target.value }) } @bind toggleShow() { this.setState({ show: !this.state.show }) } clearState() { this.setState({ appName: '', username: '', password: '', show: false }) } @bind handleSubmit(e) { const { appName, username, password } = this.state e.preventDefault() this.props.add(appName, username, password) this.clearState() } render(_, { show, appName, username, password }) { return ( <section> <div style={{display: show ? 'block' : 'none'}}> <form onSubmit={this.handleSubmit}> <input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} /> <input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} /> <input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} /> <button type='submit'>Save</button> </form> </div> <button onClick={this.toggleShow}>Add new app</button> </section> ) } }
Use destructuring to remove noise
Use destructuring to remove noise
JavaScript
mit
zeusdeux/password-manager,zeusdeux/password-manager
1dc06e37aa07f60780d1f3e74d2f58fa896d913e
src/Loading.js
src/Loading.js
import React, { Component } from 'react'; import './Loading.css'; class Loading extends Component { render() { return <p>Loading timetable data.</p>; } } export default Loading;
import React, { Component } from 'react'; import './Loading.css'; class Loading extends Component { render() { return ( <div className='loading'> <h1>Loading</h1> <h2>{this.props.name}</h2> <p>{this.props.message}</p> </div> ); } } Loading.defaultProps = { name: 'Loading name', message: 'Loading something. This is the default message. Blame the lazy developer for not giving you any more info and copy-pasting this text from Error screen.' }; Loading.propTypes = { name: React.PropTypes.string, message: React.PropTypes.string }; export default Loading;
Add error style message and name.
Add error style message and name.
JavaScript
mit
kangasta/timetablescreen,kangasta/timetablescreen
3cb2c725d0571d44d43c1265966e0de8df47b725
lib/common.js
lib/common.js
/** * Find indices of all occurance of elem in arr. Uses 'indexOf'. * @param {array} arr - Array-like element (works with strings too!). * @param {array_element} elem - Element to search for in arr. * @return {array} indices - Array of indices where elem occurs in arr. */ var findAllIndices = function(arr, elem) { var indices = []; var i = arr.indexOf(elem); while (i != -1) { indices.push(i); i = arr.indexOf(elem, i + 1); } return indices; }; /** * Find indices of all matches of Regex pattern in str. * @param {string} str - string to find Regex patterns in. * @param {RegExp} re - Regex patterns * @return {array} Array of indices where Regex pattern occurs in str. */ var findAllIndicesRegex = function(str, re) { var indices = []; var m = re.exec(str); while (m) { indices.push(m.index); m = re.exec(str); } return indices; }; module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex;
/** * Find indices of all occurance of elem in arr. Uses 'indexOf'. * @param {array} arr - Array-like element (works with strings too!). * @param {array_element} elem - Element to search for in arr. * @return {array} indices - Array of indices where elem occurs in arr. */ var findAllIndices = function(arr, elem) { var indices = []; var i = arr.indexOf(elem); while (i != -1) { indices.push(i); i = arr.indexOf(elem, i + 1); } return indices; }; /** * Find indices of all matches of Regex pattern in str. * @param {string} str - string to find Regex patterns in. * @param {RegExp} re - Regex patterns * @return {array} Array of indices where Regex pattern occurs in str. */ var findAllIndicesRegex = function(str, re) { var indices = []; var m = re.exec(str); while (m) { indices.push(m.index); m = re.exec(str); } return indices; }; var nullOutChars = function(str, start, end, nullChar) { return str.slice(0, start) + nullChar.repeat(end - start) + str.slice(end); } module.exports.findAllIndices = findAllIndices; module.exports.findAllIndicesRegex = findAllIndicesRegex; module.exports.nullOutChars = nullOutChars;
Add new fxn to null out chars in str range
Add new fxn to null out chars in str range
JavaScript
mit
nhatbui/libhrc,nhatbui/libhrc
09fddd7a0bf9a3c53e46f371f04701ef56a42811
test/algorithms/sorting/testInsertionSort.js
test/algorithms/sorting/testInsertionSort.js
/* eslint-env mocha */ const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort; const assert = require('assert'); describe('Insertion Sort', () => { it('should have no data when empty initialization', () => { const inst = new InsertionSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); });
/* eslint-env mocha */ const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort; const assert = require('assert'); describe('Insertion Sort', () => { it('should have no data when empty initialization', () => { const inst = new InsertionSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); it('should sort the array', () => { const inst = new InsertionSort([2, 1, 3, 4]); assert.equal(inst.size, 4); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 3, 4'); }); });
Test Insertion Sort: Test for sorting the array
Test Insertion Sort: Test for sorting the array
JavaScript
mit
ManrajGrover/algorithms-js
28838615005e5da47a15e78596f9e0f2513b9df7
addon/mixins/lazy-route.js
addon/mixins/lazy-route.js
/** * ES6 not supported here */ import Ember from "ember"; import config from 'ember-get-config'; export default Ember.Mixin.create({ bundleLoader: Ember.inject.service("bundle-loader"), findBundleNameByRoute: function(routeName){ //Find bundle for route var foundBundleName = Object.keys(config.bundles) .find((name)=> { let bundle = config.bundles[name]; return bundle.routes.indexOf(routeName)>-1; }); return foundBundleName; }, beforeModel: function(transition, queryParams){ this._super(transition,queryParams); let service = this.get("bundleLoader"); let bundleName = this.findBundleNameByRoute(transition.targetName); return service.loadBundle(bundleName); } });
/** * ES6 not supported here */ import Ember from "ember"; import config from 'ember-get-config'; export default Ember.Mixin.create({ bundleLoader: Ember.inject.service("bundle-loader"), findBundleNameByRoute: function(routeName){ //Find bundle for route var bundleName = null; var bundleNames = Object.keys(config.bundles); bundleNames.forEach(function(name) { var bundle = config.bundles[name]; if(bundle.routes.indexOf(routeName) >= 0) { bundleName = name; } }); return bundleName; }, beforeModel: function(transition, queryParams){ this._super(transition,queryParams); let service = this.get("bundleLoader"); let bundleName = this.findBundleNameByRoute(transition.targetName); return service.loadBundle(bundleName); } });
Fix tests by switching to es5 syntax in finding bundles
Fix tests by switching to es5 syntax in finding bundles
JavaScript
mit
duizendnegen/ember-cli-lazy-load,duizendnegen/ember-cli-lazy-load
007c630953c76a27b74b46b48b20dcb8b3d79cae
js/respec-w3c-extensions.js
js/respec-w3c-extensions.js
// extend the bibliographic entries var localBibliography = { "HYDRA-CORE": { authors: [ "Markus Lanthaler" ], href: "http://www.hydra-cg.com/spec/latest/core/", title: "Hydra Core Vocabulary", status: "unofficial", publisher: "W3C" }, "PAV": "Paolo Ciccarese, Stian Soiland-Reyes, Khalid Belhajjame, Alasdair JG Gray, Carole Goble, Tim Clark (2013): <cite><a href=\"http://purl.org/pav/\">PAV ontology: provenance, authoring and versioning</a>.</cite> Journal of biomedical semantics 4:37. doi:<a href=\"http://dx.doi.org/10.1186/2041-1480-4-37\">10.1186/2041-1480-4-37</a>" };
// extend the bibliographic entries var localBibliography = { "HYDRA-CORE": { authors: [ "Markus Lanthaler" ], href: "http://www.hydra-cg.com/spec/latest/core/", title: "Hydra Core Vocabulary", status: "Unofficial Draft", publisher: "W3C" }, "PAV": { authors: [ "Paolo Ciccarese", "Stian Soiland-Reyes", "Khalid Belhajjame", "Alasdair JG Gray", "Carole Goble", "Tim Clark" ], href: "http://purl.org/pav/", title: "PAV ontology: provenance, authoring and versioning", publisher: "Journal of biomedical semantics", status: "Published" } };
Set up localBiblio according to ReSpec's documentation:
Set up localBiblio according to ReSpec's documentation: http://www.w3.org/respec/ref.html#localbiblio
JavaScript
mit
pentandra/spec,pentandra/spec
f617ae5418d6c1223887a6685cd9714526fc95d2
src/components/LoginForm.js
src/components/LoginForm.js
import React, {Component} from 'react'; import {Button, Card, CardSection, Input} from './common'; class LoginForm extends Component { constructor(props) { super(props); this.state = {email: "", password: ''}; } render() { return <Card> <CardSection> <Input label="Email" placeholder="user@gmail.com" onChangeText={email => this.setState({email})} value={this.state.email}/> </CardSection> <CardSection> <Input secureTextEntry label="Password" placeholder = "password" onChangeText={password => this.setState({password})} value = {this.state.password} /> </CardSection> <CardSection> <Button> Log in </Button> </CardSection> </Card> } } export default LoginForm;
import React, {Component} from 'react'; import {Button, Card, CardSection, Input} from './common'; import firebase from 'firebase'; import {Text} from 'react-native'; class LoginForm extends Component { constructor(props) { super(props); this.state = {email: '', password: '', error: ''}; } async onButtonPress() { const {email, password} = this.state; this.setState({error: ''}); try { await firebase.auth().signInWithEmailAndPassword(email, password); } catch (err) { try { await firebase.auth().createUserWithEmailAndPassword(email, password); } catch (err) { console.log("error", err); this.setState({error: "Login Failed"}); } } } render() { return <Card> <CardSection> <Input label="Email" placeholder="user@gmail.com" onChangeText={email => this.setState({email})} value={this.state.email}/> </CardSection> <CardSection> <Input secureTextEntry label="Password" placeholder="password" onChangeText={password => this.setState({password})} value={this.state.password} /> </CardSection> <Text style={styles.errorTextStyle}> {this.state.error} </Text> <CardSection> <Button onPress={()=>this.onButtonPress()}> Log in </Button> </CardSection> </Card> } } const styles = { errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' } }; export default LoginForm;
Use firebase to authenticate users
Use firebase to authenticate users
JavaScript
apache-2.0
ChenLi0830/RN-Auth,ChenLi0830/RN-Auth,ChenLi0830/RN-Auth
a9bcc1388143c86f8ac6d5afcfe0b8cb376b8de7
src/main/webapp/resources/dev/js/singleUser.js
src/main/webapp/resources/dev/js/singleUser.js
/** * Author: Josh Adam <josh.adam@phac-aspc.gc.ca> * Date: 2013-04-17 * Time: 9:41 AM */ var username = $('#username').text(); function Project (data) { "use strict"; this.name = data.name; } function UserViewModel () { "use strict"; self.projects = ko.observableArray([]); function getUserProjects () { "use strict"; $.getJSON('/users/' + username + '/projects', function (allData) { var mappedProjects = $.map(allData.projectList, function (item) { return new Project(item) }); self.projects(mappedProjects); }); } getUserProjects(); } $.ajaxSetup({ cache: false }); ko.applyBindings(new UserViewModel());
/** * Author: Josh Adam <josh.adam@phac-aspc.gc.ca> * Date: 2013-04-17 * Time: 9:41 AM */ var username = $('#username').text(); function Project (data) { "use strict"; this.name = data.name; } function UserViewModel () { "use strict"; self.projects = ko.observableArray([]); function getUserProjects () { "use strict"; $.getJSON('/users/' + username + '/projects', function (allData) { var mappedProjects = $.map(allData.projectResources.projects, function (item) { return new Project(item) }); self.projects(mappedProjects); }); } getUserProjects(); } $.ajaxSetup({ cache: false }); ko.applyBindings(new UserViewModel());
Change the expected JSON format for user projects.
Change the expected JSON format for user projects.
JavaScript
apache-2.0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
c68b6772d435d76bfe290e40e0ae0539c1ba5d76
src/js/model/Contacts.js
src/js/model/Contacts.js
var ContactView = require('../view/Contact'); /** * Creates a new Contact * @constructor * @arg {Object} options - Object hash used to populate instance * @arg {string} options.firstName - First name of the contact * @arg {string} options.firstName - Last name of the contact * @arg {string} options.tel - name of the contact */ var Contact = function(options) { if (typeof options !== 'object') { throw console.error('`options` is not properly defined'); } this.init(options); }; Contact.prototype = { firstName: '', lastName: '', tel: '', /** * @description Creates a new instance of Contact */ init: function(options) { var opts = Object.keys(options); opts.forEach(function(currentValue){ this[currentValue] = options[currentValue]; }, this); console.log(this); this.save(); }, save: function() { var key = localStorage.length; var contact = { firstName: this.firstName, lastName: this.lastName, tel: this.tel }; localStorage.setItem(key, JSON.stringify(contact)); var contactView = new ContactView(key, contact); } }; Contact.remove = function(id) { localStorage.removeItem(id); }; module.exports = Contact;
var ContactView = require('../view/Contact'); /** * Creates a new Contact. * @constructor * @arg {Object} options - Object hash used to populate instance. * @arg {string} options.firstName - First name of the contact. * @arg {string} options.firstName - Last name of the contact. * @arg {string} options.tel - Telephone number of the contact. */ var Contact = function(options) { if (typeof options !== 'object') { throw console.error('`options` is not properly defined'); } this.init(options); }; Contact.prototype = { firstName: '', lastName: '', tel: '', /** * @description Creates a new instance of Contact. */ init: function(options) { var opts = Object.keys(options); opts.forEach(function(currentValue){ this[currentValue] = options[currentValue]; }, this); console.log(this); this.save(); }, save: function() { var key = localStorage.length; var contact = { firstName: this.firstName, lastName: this.lastName, tel: this.tel }; localStorage.setItem(key, JSON.stringify(contact)); var contactView = new ContactView(key, contact); } }; Contact.remove = function(id) { localStorage.removeItem(id); }; module.exports = Contact;
Use periods on senteces in docs
Use periods on senteces in docs
JavaScript
isc
bitfyre/contacts
061563eb253e72812e45aa454455288d194f3cc5
app/scripts/components/player-reaction.js
app/scripts/components/player-reaction.js
import m from 'mithril'; import classNames from '../classnames.js'; class PlayerReactionComponent { oninit({ attrs: { session, player } }) { this.player = player; session.on('send-reaction', ({ reactingPlayer, reaction }) => { if (reactingPlayer.color === this.player.color) { // Immediately update the reaction if another reaction was sent before // the current reaction disappears clearTimeout(this.player.reaction ? this.player.reaction.timer : null); this.player.reaction = reaction; // The reaction should disappear after the specified duration this.player.reaction.timer = setTimeout(() => { this.player.reaction.timer = null; m.redraw(); }, PlayerReactionComponent.reactionDuration); m.redraw(); } }); } // The oninit() call (and therefore the send-reaction listener) only runs once // for the lifetime of this component instance, however the player object may // change during that time, so we need to ensure the above listener has an // dynamic reference to the freshest instance of the player onupdate({ attrs: { player } }) { this.player = player; } view({ attrs: { player } }) { return m('div.player-reaction', m('div.player-reaction-symbol', { class: classNames({ 'show': player.reaction && player.reaction.timer }) }, player.reaction ? player.reaction.symbol : null)); } } // The duration a reaction is shown before disappearing PlayerReactionComponent.reactionDuration = 1500; export default PlayerReactionComponent;
import m from 'mithril'; import classNames from '../classnames.js'; class PlayerReactionComponent { oninit({ attrs: { session, player } }) { this.player = player; session.on('send-reaction', ({ reactingPlayer, reaction }) => { if (reactingPlayer.color === this.player.color) { // Immediately update the reaction if another reaction was sent before // the current reaction disappears clearTimeout(this.player.reaction ? this.player.reaction.timer : null); this.player.reaction = reaction; // The reaction should disappear after the specified duration this.player.reaction.timer = setTimeout(() => { if (this.player.reaction) { this.player.reaction.timer = null; } m.redraw(); }, PlayerReactionComponent.reactionDuration); m.redraw(); } }); } // The oninit() call (and therefore the send-reaction listener) only runs once // for the lifetime of this component instance, however the player object may // change during that time, so we need to ensure the above listener has an // dynamic reference to the freshest instance of the player onupdate({ attrs: { player } }) { this.player = player; } view({ attrs: { player } }) { return m('div.player-reaction', m('div.player-reaction-symbol', { class: classNames({ 'show': player.reaction && player.reaction.timer }) }, player.reaction ? player.reaction.symbol : null)); } } // The duration a reaction is shown before disappearing PlayerReactionComponent.reactionDuration = 1500; export default PlayerReactionComponent;
Fix race condition when setTimeout callback is run
Fix race condition when setTimeout callback is run The player object may change by the time the callback is run, and therefore this.player.reactions may not exist at that point.
JavaScript
mit
caleb531/connect-four
547cb0360680e20025e086895f1926ea93c3a205
lib/generators/loaders/ESNextReactLoader.js
lib/generators/loaders/ESNextReactLoader.js
module.exports = { test: /\.es6\.js$|\.js$|\.jsx$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015-native-modules', 'stage-2', 'react', ], plugins: [ 'transform-class-properties', 'transform-react-constant-elements', 'transform-react-inline-elements', 'lodash', // fixes the babel budnling issue ], } };
module.exports = { test: /\.es6\.js$|\.js$|\.jsx$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015-native-modules', 'stage-2', 'react', ].map(function(p) { return require.resolve('babel-preset-' + p) }), plugins: [ 'transform-class-properties', 'transform-react-constant-elements', 'transform-react-inline-elements', 'lodash', // fixes the babel budnling issue ].map(function(p) { return require.resolve('babel-plugin-' + p) }), } };
Revert "Revert "Fix module resolution for npm-link'd packages""
Revert "Revert "Fix module resolution for npm-link'd packages"" This reverts commit 8dc3d9b82be05fe3077e2cc82963a229858930b5.
JavaScript
mit
reddit/node-build
17b597513cb8c7aab777cd1ea5fe7228cd15c166
pogo-protos.js
pogo-protos.js
const fs = require('fs'), protobuf = require('protobufjs'); const builder = protobuf.newBuilder(), protoDir = __dirname + '/proto'; fs.readdirSync(protoDir) .filter(filename => filename.match(/\.proto$/)) .forEach(filename => protobuf.loadProtoFile(protoDir + '/' + filename, builder)); module.exports = builder.build("POGOProtos");
const fs = require('fs'), protobuf = require('protobufjs'); const builder = protobuf.newBuilder(), protoDir = __dirname + '/proto'; fs.readdirSync(protoDir) .filter(filename => filename.match(/\.proto$/)) .forEach(filename => protobuf.loadProtoFile(protoDir + '/' + filename, builder)); // Recursively add the packed=true to all packable repeated fields. // Repeated fields are packed by default in proto3 but protobuf.js incorrectly does not set the option. // See also: https://github.com/dcodeIO/protobuf.js/issues/432 function addPackedOption(ns) { if (ns instanceof protobuf.Reflect.Message) { ns.getChildren(protobuf.Reflect.Field).forEach(field => { if (field.repeated && protobuf.PACKABLE_WIRE_TYPES.indexOf(field.type.wireType) != -1) { field.options.packed = true; } }); } else if (ns instanceof protobuf.Reflect.Namespace) { ns.children.forEach(addPackedOption); } } addPackedOption(builder.lookup('POGOProtos')); module.exports = builder.build("POGOProtos");
Set packed=true for all repeated packable types
Set packed=true for all repeated packable types Workaround for https://github.com/dcodeIO/protobuf.js/issues/432
JavaScript
mit
cyraxx/node-pogo-protos,cyraxx/node-pogo-protos
f677fef8a3474eacd62a22ddedc25a3c91ec9c3f
src/js/components/interests/CardContentList.js
src/js/components/interests/CardContentList.js
import React, { PropTypes, Component } from 'react'; import CardContent from '../ui/CardContent'; export default class CardContentList extends Component { static propTypes = { contents : PropTypes.array.isRequired, userId : PropTypes.number.isRequired, otherUserId : PropTypes.number, onReport : PropTypes.func, }; constructor(props) { super(props); this.onReport = this.onReport.bind(this); } onReport(contentId, reason) { if (this.props.onReport) { this.props.onReport(contentId, reason); } } render() { const {contents, userId, otherUserId, onClickHandler} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} onReport={this.onReport}/>)} </div> ); } }
import React, { PropTypes, Component } from 'react'; import CardContent from '../ui/CardContent'; export default class CardContentList extends Component { static propTypes = { contents : PropTypes.array.isRequired, userId : PropTypes.number.isRequired, otherUserId : PropTypes.number, onReport : PropTypes.func, }; constructor(props) { super(props); this.onReport = this.onReport.bind(this); } onReport(contentId, reason) { this.props.onReport(contentId, reason); } render() { const {contents, userId, otherUserId} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} onReport={this.props.onReport ? this.onReport : null}/>)} </div> ); } }
Make report optional in CardContent
QS-1341: Make report optional in CardContent
JavaScript
agpl-3.0
nekuno/client,nekuno/client
65a3be9065227ba11ab0680f85c109d99b860bb4
tools/cli/default-npm-deps.js
tools/cli/default-npm-deps.js
import buildmessage from "../utils/buildmessage.js"; import { pathJoin, statOrNull, writeFile, unlink, } from "../fs/files"; const INSTALL_JOB_MESSAGE = "installing npm dependencies"; export function install(appDir, options) { const packageJsonPath = pathJoin(appDir, "package.json"); const needTempPackageJson = ! statOrNull(packageJsonPath); if (needTempPackageJson) { const { dependencies } = require("../static-assets/skel-minimal/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file. writeFile( packageJsonPath, JSON.stringify({ dependencies }, null, 2) + "\n", "utf8", ); } const ok = buildmessage.enterJob(INSTALL_JOB_MESSAGE, function () { const npmCommand = ["install"]; if (options && options.includeDevDependencies) { npmCommand.push("--production=false"); } const { runNpmCommand } = require("../isobuild/meteor-npm.js"); const installResult = runNpmCommand(npmCommand, appDir); if (! installResult.success) { buildmessage.error( "Could not install npm dependencies for test-packages: " + installResult.error); return false; } return true; }); if (needTempPackageJson) { // Clean up the temporary package.json file created above. unlink(packageJsonPath); } return ok; }
import buildmessage from "../utils/buildmessage.js"; import { pathJoin, statOrNull, writeFile, unlink, } from "../fs/files"; const INSTALL_JOB_MESSAGE = "installing npm dependencies"; export function install(appDir, options) { const packageJsonPath = pathJoin(appDir, "package.json"); const needTempPackageJson = ! statOrNull(packageJsonPath); if (needTempPackageJson) { // NOTE we need skel-minimal to pull in jQuery which right now is required for Blaze const { dependencies } = require("../static-assets/skel-blaze/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file. writeFile( packageJsonPath, JSON.stringify({ dependencies }, null, 2) + "\n", "utf8", ); } const ok = buildmessage.enterJob(INSTALL_JOB_MESSAGE, function () { const npmCommand = ["install"]; if (options && options.includeDevDependencies) { npmCommand.push("--production=false"); } const { runNpmCommand } = require("../isobuild/meteor-npm.js"); const installResult = runNpmCommand(npmCommand, appDir); if (! installResult.success) { buildmessage.error( "Could not install npm dependencies for test-packages: " + installResult.error); return false; } return true; }); if (needTempPackageJson) { // Clean up the temporary package.json file created above. unlink(packageJsonPath); } return ok; }
Fix test-packages in browser testing
Fix test-packages in browser testing
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
4313cae1c10e687123c18625126537004ceb5131
lib/util/request-browser.js
lib/util/request-browser.js
/*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** Browser replacement for the request module using jQuery. */ var EventEmitter = require('events').EventEmitter, SingleIterator = require('../../lib/iterators/Iterator').SingleIterator; require('setimmediate'); // Requests the given resource as an iterator function createRequest(settings) { var request = new EventEmitter(); // Delegate the request to jQuery's AJAX module var jqXHR = jQuery.ajax({ url: settings.url, timeout: settings.timeout, type: settings.method, headers: { accept: settings.headers && settings.headers.accept || '*/*' }, }) // Emit the result as a readable response iterator .success(function () { var response = new SingleIterator(jqXHR.responseText || ''); response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); }); request.abort = function () { jqXHR.abort(); }; return request; } module.exports = createRequest;
/*! @license ©2013 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */ /** Browser replacement for the request module using jQuery. */ var EventEmitter = require('events').EventEmitter, SingleIterator = require('../../lib/iterators/Iterator').SingleIterator; require('setimmediate'); // Requests the given resource as an iterator function createRequest(settings) { var request = new EventEmitter(); // Delegate the request to jQuery's AJAX module var jqXHR = jQuery.ajax({ url: settings.url, timeout: settings.timeout, type: settings.method, headers: { accept: settings.headers && settings.headers.accept || '*/*' }, }) // Emit the result as a readable response iterator .success(function () { var response = new SingleIterator(jqXHR.responseText || ''); response.statusCode = jqXHR.status; response.headers = { 'content-type': jqXHR.getResponseHeader('content-type') }; request.emit('response', response); }) // Emit an error if the request fails .fail(function () { request.emit('error', new Error('Error requesting ' + settings.url)); }); // Aborts the request request.abort = function () { jqXHR.abort(); }; return request; } module.exports = createRequest;
Add error handling to browser requests.
Add error handling to browser requests.
JavaScript
mit
infitude/Client.js
c848a715cb5423085cb76c3bd958a1141ec2defd
public/app.js
public/app.js
$(document).ready(function() { var options = { chart: { renderTo: 'chart', type: 'spline', }, title: { text: 'Recent Water Values' }, xAxis: { type: 'datetime', title: { text: 'Date' } }, yAxis: { labels: { formatter: function() { return this.value == 1 ? 'Wet' : 'Dry'; } }, min: 0, max: 1, tickInterval: 1, title: { text: null } }, legend: { enabled: false }, series: [{}] }; $.getJSON('data.json', function(data) { var series = []; // Store some stats while parsing through var lastStatus; var lastWet; var lastDry; $.each(data, function(key, value) { series.push([Date.parse(key), value]); lastStatus = value; if (value == 1) { lastWet = key; } if (value == 0) { lastDry = key; } }); $('#current').text(lastStatus ? 'Wet' : 'Dry'); $('#lastWet').text(lastWet); $('#lastDry').text(lastDry); options.series[0].data = series; options.series[0].color = '#449944'; options.series[0].name = 'Water Value'; var chart = new Highcharts.Chart(options); }); });
$(document).ready(function() { var options = { chart: { renderTo: 'chart', type: 'spline', }, title: { text: 'Recent Water Values' }, xAxis: { type: 'datetime', title: { text: 'Date' } }, yAxis: { labels: { formatter: function() { return this.value == 1 ? 'Wet' : 'Dry'; } }, min: 0, max: 1, tickInterval: 1, title: { text: null } }, legend: { enabled: false }, series: [{}] }; // Don't cache the json :) $.ajaxSetup({ cache:false }); $.getJSON('data.json', function(data) { var series = []; // Store some stats while parsing through var lastStatus; var lastWet; var lastDry; $.each(data, function(key, value) { series.push([Date.parse(key), value]); lastStatus = value; if (value == 1) { lastWet = key; } if (value == 0) { lastDry = key; } }); $('#current').text(lastStatus ? 'Wet' : 'Dry'); $('#lastWet').text(lastWet); $('#lastDry').text(lastDry); options.series[0].data = series; options.series[0].color = '#449944'; options.series[0].name = 'Water Value'; var chart = new Highcharts.Chart(options); }); });
Remove cacheing of the json
Remove cacheing of the json
JavaScript
mit
amcolash/WaterPi,amcolash/WaterPi,amcolash/WaterPi,amcolash/WaterIoT,amcolash/WaterIoT,amcolash/WaterPi,amcolash/WaterIoT,amcolash/WaterIoT
ba68dfed99a9616724512b11c9a7189552e71161
node-tests/unit/utils/rasterize-list-test.js
node-tests/unit/utils/rasterize-list-test.js
'use strict'; const expect = require('../../helpers/expect'); const fs = require('fs'); const sizeOf = require('image-size'); const RasterizeList = require('../../../src/utils/rasterize-list'); describe('RasterizeList', function() { // Hitting the file system is slow this.timeout(0); context('when src and toRasterize', () => { const src = 'node-tests/fixtures/icon.svg'; const toRasterize = [ { size: 60, name: 'icon-60', path: 'tmp/icon-60.png' } ]; afterEach(() => { toRasterize.forEach((rasterize) => { fs.unlinkSync(rasterize.path); }); }); it('returns a promise that resolves to an array', (done) => { expect( RasterizeList({src: src, toRasterize: toRasterize}) ).to.eventually.be.a('array').notify(done); }); it('writes the files to rasterize at the right size', (done) => { RasterizeList({src: src, toRasterize: toRasterize}).then(() => { toRasterize.forEach((rasterize) => { expect(fs.existsSync(rasterize.path)).to.equal(true); expect(sizeOf(rasterize.path).width).to.equal(rasterize.size); expect(sizeOf(rasterize.path).height).to.equal(rasterize.size); }); done(); }); }); }); });
'use strict'; const expect = require('../../helpers/expect'); const fs = require('fs'); const sizeOf = require('image-size'); const RasterizeList = require('../../../src/utils/rasterize-list'); describe('RasterizeList', function() { // Hitting the file system is slow this.timeout(0); context('when src and toRasterize', () => { const src = 'node-tests/fixtures/icon.svg'; const toRasterize = [ { size: 60, name: 'icon-60', path: 'tmp/icon-60.png' } ]; let subject; before(() => { subject = RasterizeList({src: src, toRasterize: toRasterize}); }); after(() => { toRasterize.forEach((rasterize) => { fs.unlinkSync(rasterize.path); }); }); it('returns a promise that resolves to an array', (done) => { expect(subject).to.eventually.be.a('array').notify(done); }); it('writes the files to rasterize at the right size', (done) => { subject.then(() => { toRasterize.forEach((rasterize) => { expect(fs.existsSync(rasterize.path)).to.equal(true); expect(sizeOf(rasterize.path).width).to.equal(rasterize.size); expect(sizeOf(rasterize.path).height).to.equal(rasterize.size); }); done(); }); }); }); });
Update test to improve speed by only writing and unlinking files once
refactor(rasterize-list): Update test to improve speed by only writing and unlinking files once
JavaScript
mit
isleofcode/splicon
b5994cb13469f3d48f589a2a7910149ef46b0516
build/npm/stop-server.js
build/npm/stop-server.js
/* * Copyright (C) 2017 Steven Soloff * * This software is licensed under the terms of the GNU Affero General Public * License version 3 or later (https://www.gnu.org/licenses/). */ import config from './config' import del from 'del' import fs from 'fs' import kill from 'tree-kill' const serverPid = fs.readFileSync(config.paths.serverPid, { encoding: config.encodings.serverPid }) del(config.paths.serverPid) kill(serverPid)
/* * Copyright (C) 2017 Steven Soloff * * This software is licensed under the terms of the GNU Affero General Public * License version 3 or later (https://www.gnu.org/licenses/). */ import config from './config' import fs from 'fs' import kill from 'tree-kill' const serverPid = fs.readFileSync(config.paths.serverPid, { encoding: config.encodings.serverPid }) fs.unlinkSync(config.paths.serverPid) kill(serverPid)
Use fs.unlinkSync() to delete files
Use fs.unlinkSync() to delete files
JavaScript
agpl-3.0
ssoloff/hazelslack-server-core
91fabd5f82b18a1b1e2acae87160be3488efc044
tests/helpers/start-app.js
tests/helpers/start-app.js
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; // use defaults, but you can override let attributes = Ember.assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; let assign = Ember.assign || Ember.merge // use defaults, but you can override let attributes = assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
Fix tests for ember v2.4.x
Fix tests for ember v2.4.x
JavaScript
mit
josemarluedke/ember-cli-numeral,jayphelps/ember-cli-numeral,josemarluedke/ember-cli-numeral
8963d5f14cf34b4771a5dbcdad7181680aef7881
example/src/screens/types/Drawer.js
example/src/screens/types/Drawer.js
import React from 'react'; import {StyleSheet, View, Text} from 'react-native'; class MyClass extends React.Component { render() { return ( <View style={styles.container}> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, width: 300, alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', }, }); export default MyClass;
import React from 'react'; import {StyleSheet, View, Button} from 'react-native'; class MyClass extends React.Component { onShowModal = () => { this.props.navigator.toggleDrawer({ side: 'left' }); this.props.navigator.showModal({ screen: 'example.Types.Modal', title: `Modal` }); }; render() { return ( <View style={styles.container}> <View style={styles.button}> <Button onPress={this.onShowModal} title="Show Modal"/> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, width: 300, alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', }, button: { marginTop: 16 } }); export default MyClass;
Add show modal button to SideMenu
Add show modal button to SideMenu
JavaScript
mit
junedomingo/react-native-navigation,junedomingo/react-native-navigation,junedomingo/react-native-navigation,junedomingo/react-native-navigation
c120257c591597d8bf291396180e18f40bb3b1fa
common/components/utils/ghostApi.js
common/components/utils/ghostApi.js
// @flow import GhostContentAPI from "@tryghost/content-api"; const ghostContentAPI = window.GHOST_URL && window.GHOST_CONTENT_API_KEY && new GhostContentAPI({ url: window.GHOST_URL, key: window.GHOST_CONTENT_API_KEY, version: "v3", }); export type GhostPost = {| title: string, url: string, excerpt: ?string, custom_excerpt: ?string, feature_image: string, |}; class ghostApiHelper { static browse( tag: string, successCallback: ($ReadOnlyArray<GhostPost>) => void, errCallback: string => void ) { ghostContentAPI.posts .browse({ filter: "tag:" + tag, fields: "title, url, excerpt, custom_excerpt, feature_image", }) .then(postsResponse => { successCallback ? successCallback(postsResponse) : console.log(JSON.stringify(postsResponse)); }) .catch(err => { errCallback ? errCallback(err) : console.error(err); }); } static isConfigured(): boolean { return !!ghostContentAPI; } } export default ghostApiHelper;
// @flow import GhostContentAPI from "@tryghost/content-api"; const ghostContentAPI = window.GHOST_URL && window.GHOST_CONTENT_API_KEY && new GhostContentAPI({ url: window.GHOST_URL, key: window.GHOST_CONTENT_API_KEY, version: "v3", }); export type GhostPost = {| title: string, url: string, slug: string, excerpt: ?string, custom_excerpt: ?string, feature_image: string, |}; class ghostApiHelper { static browse( tag: string, successCallback: ($ReadOnlyArray<GhostPost>) => void, errCallback: string => void ) { ghostContentAPI.posts .browse({ filter: "tag:" + tag, fields: "title, url, slug, excerpt, custom_excerpt, feature_image", }) .then(postsResponse => { successCallback ? successCallback(postsResponse) : console.log(JSON.stringify(postsResponse)); }) .catch(err => { errCallback ? errCallback(err) : console.error(err); }); } static isConfigured(): boolean { return !!ghostContentAPI; } } export default ghostApiHelper;
Include slugs in ghost response
Include slugs in ghost response
JavaScript
mit
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
3c2b0a9140c8dd101bf6e277550e156af3fc8acc
test/fluce-component.spec.js
test/fluce-component.spec.js
/* @flow */ import React from 'react' import {addons} from 'react/addons' var {TestUtils} = addons var {createRenderer} = TestUtils import Fluce from '../src/fluce-component' import createFluce from '../src/create-fluce' describe('<Fluce />', () => { it('Should throw when rendered with many children', () => { var renderer = createRenderer() var err: any try { renderer.render(<Fluce><div/><div/></Fluce>) } catch (e) { err = e } expect(err.message).toBe('Invariant Violation: onlyChild must be passed a children with exactly one child.') }) it('Should pass `fluce` to the child', () => { var fluce = createFluce() var renderer = createRenderer() renderer.render(<Fluce fluce={fluce}><div foo='bar' /></Fluce>) var result = renderer.getRenderOutput() expect(result.type).toBe('div') expect(result.props).toEqual({foo: 'bar', fluce}) }) it('This should fail', () => { expect(1).toBe(2) }) })
/* @flow */ import React from 'react' import {addons} from 'react/addons' var {TestUtils} = addons var {createRenderer} = TestUtils import Fluce from '../src/fluce-component' import createFluce from '../src/create-fluce' describe('<Fluce />', () => { it('Should throw when rendered with many children', () => { var renderer = createRenderer() var err: any try { renderer.render(<Fluce><div/><div/></Fluce>) } catch (e) { err = e } expect(err.message).toBe('Invariant Violation: onlyChild must be passed a children with exactly one child.') }) it('Should pass `fluce` to the child', () => { var fluce = createFluce() var renderer = createRenderer() renderer.render(<Fluce fluce={fluce}><div foo='bar' /></Fluce>) var result = renderer.getRenderOutput() expect(result.type).toBe('div') expect(result.props).toEqual({foo: 'bar', fluce}) }) })
Revert "check if travis works"
Revert "check if travis works" This reverts commit fbd645ae10b6b8c41befe416765ea7b6bc3343d9.
JavaScript
mit
rpominov/fluce,rpominov/fluce
08e299491da581b1d64d8fda499a0fd94d8427a1
client/ember/tests/unit/models/config-test.js
client/ember/tests/unit/models/config-test.js
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('config'); test('it exists', function(assert) { var model = this.subject(); // var store = this.store(); assert.ok(!!model); });
import { moduleForModel, test } from 'ember-qunit'; import Ember from 'ember'; var configMock = { id: 1, images: { base_url: "http://image.tmdb.org/t/p/", secure_base_url: "https://image.tmdb.org/t/p/", backdrop_sizes: [ "w300", "w780", "w1280", "original" ], logo_sizes: [ "w45", "w92", "w154", "w185", "w300", "w500", "original" ], poster_sizes: [ "w92", "w154", "w185", "w342", "w500", "w780", "original" ], profile_sizes: [ "w45", "w185", "h632", "original" ], still_sizes: [ "w92", "w185", "w300", "original" ] } }; moduleForModel('config'); test('It stores movies', function() { var store = this.store(); var record = null; Ember.run(function() { store.createRecord('config', configMock); record = store.find('config', 1); }); equal(record.get('images.base_url'), configMock.images.base_url); equal(record.get('images.secure_base_url'), configMock.images.secure_base_url); equal(record.get('images.backdrop_sizes'), configMock.images.backdrop_sizes); });
Add test for config model
Add test for config model
JavaScript
mit
ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix
4e771acd0015b67506747ff16ce0c971884fea8e
compiler/ast/FunctionDeclaration.js
compiler/ast/FunctionDeclaration.js
'use strict'; var Node = require('./Node'); var ok = require('assert').ok; class FunctionDeclaration extends Node { constructor(def) { super('FunctionDeclaration'); this.name = def.name; this.params = def.params; this.body = this.makeContainer(def.body); } generateCode(codegen) { var name = this.name; var params = this.params; var body = this.body; var statement = this.statement; if (name != null) { ok(typeof name === 'string', 'Function name should be a string'); } codegen.write('function' + (name ? ' ' + name : '') + '('); if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) { if (i !== 0) { codegen.write(', '); } var param = params[i]; if (typeof param === 'string') { codegen.write(param); } else { if (param.type !== 'Identifier') { throw new Error('Illegal param: ' + param); } codegen.generateCode(param); } } } codegen.write(') '); var oldInFunction = codegen.inFunction; codegen.inFunction = true; codegen.generateBlock(body); codegen.inFunction = oldInFunction; if (statement) { codegen.write('\n'); } } isCompoundExpression() { return true; } } module.exports = FunctionDeclaration;
'use strict'; var Node = require('./Node'); var ok = require('assert').ok; class FunctionDeclaration extends Node { constructor(def) { super('FunctionDeclaration'); this.name = def.name; this.params = def.params; this.body = this.makeContainer(def.body); } generateCode(codegen) { var name = this.name; var params = this.params; var body = this.body; var statement = this.statement; if (name != null) { ok(typeof name === 'string' || name.type === 'Identifier', 'Function name should be a string or Identifier'); } if (name) { codegen.write('function '); codegen.generateCode(name); codegen.write('('); } else { codegen.write('function('); } if (params && params.length) { for (let i=0, paramsLen = params.length; i<paramsLen; i++) { if (i !== 0) { codegen.write(', '); } var param = params[i]; if (typeof param === 'string') { codegen.write(param); } else { if (param.type !== 'Identifier') { throw new Error('Illegal param: ' + param); } codegen.generateCode(param); } } } codegen.write(') '); var oldInFunction = codegen.inFunction; codegen.inFunction = true; codegen.generateBlock(body); codegen.inFunction = oldInFunction; if (statement) { codegen.write('\n'); } } isCompoundExpression() { return true; } } module.exports = FunctionDeclaration;
Allow function declaration name to be an Identifier node
Allow function declaration name to be an Identifier node
JavaScript
mit
marko-js/marko,marko-js/marko
f6f4b6fc44b0e5e09ea38cfe92be0c0ff28a4cf1
src/stores/topicStore.js
src/stores/topicStore.js
import TopicReducer from "reducers/topicReducer"; import thunkMiddleware from "redux-thunk"; import {createStore, combineReducers, applyMiddleware} from 'redux'; import createLogger from 'redux-logger'; const loggerMiddleware = createLogger(); /** * Creates the topic store. * * This is designed to be used isomorphically. * @returns {*} */ export default function topicStore() { const reducer = combineReducers({TopicReducer}); const store = createStore(reducer, applyMiddleware(thunkMiddleware, loggerMiddleware)); return store; };
import TopicReducer from "reducers/topicReducer"; import thunkMiddleware from "redux-thunk"; import {createStore, combineReducers, applyMiddleware} from 'redux'; import createLogger from 'redux-logger'; const loggerMiddleware = createLogger(); const createTopicStore = function createTopicStore(middlewares, reducers) { const reducer = combineReducers(reducers); const store = createStore(reducer, applyMiddleware(...middlewares)); return store; }; /** * Creates the topic store. * * This is designed to be used isomorphically. * @returns {*} */ export default function topicStore() { return createTopicStore([thunkMiddleware, loggerMiddleware], {TopicReducer}); };
Make store creation more flexible.
Make store creation more flexible. This will help us to create stores with no logging middleware later if we want (amongst other things).
JavaScript
bsd-3-clause
Seinzu/word-cloud
638fea7b838166e3fe75a482835c06db7c12bdb1
client/webpack.config.js
client/webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), }, module: { rules: [ { use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], }, }, test: /\.js$/, exclude: /node_modules/, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', }), ], };
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', entry: './src/index.js', output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), }, module: { rules: [ { use: { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', '@babel/preset-react', { plugins: ['@babel/plugin-proposal-class-properties'] }, ], }, }, test: /\.js$/, exclude: /node_modules/, }, ], }, plugins: [ new HtmlWebpackPlugin({ template: 'src/index.html', }), ], };
Set `@babel/plugin-proposal-class-properties` as option in webpack
Set `@babel/plugin-proposal-class-properties` as option in webpack Fixes webpack build error due to class properties https://stackoverflow.com/a/52693007/452233
JavaScript
mit
ultranaut/react-chat,ultranaut/react-chat
b110e315ecd6339108848f6cea23b7d336dabbf1
src/Resend.js
src/Resend.js
var MatrixClientPeg = require('./MatrixClientPeg'); var dis = require('./dispatcher'); module.exports = { resend: function(event) { MatrixClientPeg.get().resendEvent( event, MatrixClientPeg.get().getRoom(event.getRoomId()) ).done(function() { dis.dispatch({ action: 'message_sent', event: event }); }, function() { dis.dispatch({ action: 'message_send_failed', event: event }); }); dis.dispatch({ action: 'message_resend_started', event: event }); }, };
var MatrixClientPeg = require('./MatrixClientPeg'); var dis = require('./dispatcher'); module.exports = { resend: function(event) { MatrixClientPeg.get().resendEvent( event, MatrixClientPeg.get().getRoom(event.getRoomId()) ).done(function() { dis.dispatch({ action: 'message_sent', event: event }); }, function() { dis.dispatch({ action: 'message_send_failed', event: event }); }); dis.dispatch({ action: 'message_resend_started', event: event }); }, removeFromQueue: function(event) { MatrixClientPeg.get().getScheduler().removeEventFromQueue(event); var room = MatrixClientPeg.get().getRoom(event.getRoomId()); if (!room) { return; } room.removeEvents([event.getId()]); } };
Add removeFromQueue function to cancel sending a queued event
Add removeFromQueue function to cancel sending a queued event
JavaScript
apache-2.0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk
c0142bb488e5fa5edb0cefd205be96a806389ac6
server/models/essentials.js
server/models/essentials.js
const mongoose = require('mongoose'); const logger = require('../logging'); // connecting to db mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost'); const db = mongoose.connection; db.on('error', (err) => { logger.error('Could not connect to database.', { err }); });
const mongoose = require('mongoose'); const logger = require('../logging'); const DB_URL = process.env.SDF_DATABASE_URL; const DB_NAME = process.env.SDF_DATABASE_NAME || 'sdf'; const DB_CONN_STR = DB_URL || `mongodb://localhost/${DB_NAME}`; // connecting to db console.log(`Connecting to mongodb using '${DB_CONN_STR}'`); mongoose.Promise = global.Promise; mongoose.connect(DB_CONN_STR); const db = mongoose.connection; db.on('error', (err) => { logger.error('Could not connect to database.', { err }); });
Make connecting to mongodb a bit more pluggy
Make connecting to mongodb a bit more pluggy
JavaScript
mit
dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta
cd4023e5f54afd97cf9d6cfa2f2d9e092cde8cee
snippets/sheets/is_range_a_cell/code.js
snippets/sheets/is_range_a_cell/code.js
/* eslint-disable camelcase */ /** * Checks if a range is a cell * @param {GoogleAppsScript.Spreadsheet.Range} range * @return {boolean} */ function isRangeACell_(range) { return !/:/.test(range.getA1Notation()); } /** * Run the snippet */ function run_test() { const cell = SpreadsheetApp.getActive().getRange('B3'); const range = SpreadsheetApp.getActive().getRange('B3:B4'); const active = SpreadsheetApp.getActiveRange(); console.log([cell, range, active].map(isRangeACell_)); }
/* eslint-disable camelcase */ /** * Checks if a range is a cell * @param {GoogleAppsScript.Spreadsheet.Range} range * @return {boolean} */ function isRangeACell_(range) { return !~range.getA1Notation().indexOf(':'); } /** * Run the snippet */ function run_test() { const cell = SpreadsheetApp.getActive().getRange('B3'); const range = SpreadsheetApp.getActive().getRange('B3:B4'); const active = SpreadsheetApp.getActiveRange(); console.log([cell, range, active].map(isRangeACell_)); }
Update is ceaal a reange
Update is ceaal a reange Signed-off-by: Alex Ivanov <141a92417f71895e56c4a5da05f3e98fc78e2220@contributor.pw>
JavaScript
unlicense
oshliaer/google-apps-script-snippets,oshliaer/google-apps-script-snippets,oshliaer/google-apps-script-snippets
71776730dcd36f9d3e606b8f109434056d47beb7
lib/web/scripts/capabilities/home/HomeCapabilityView.js
lib/web/scripts/capabilities/home/HomeCapabilityView.js
const Marionette = require('backbone.marionette'); const HomeCardsView = require('./HomeCardsView.js'); module.exports = class HomeCapabilityView extends Marionette.View { template = Templates['capabilities/home/home']; className() { return 'home-capability'; } regions() { return {cards: '.cards-container'}; } serializeData() { const hour = (new Date()).getHours(); // XXX Force this to update occasionally return { greeting: (hour < 4 || hour >= 19) ? 'Good evening.' : ((hour < 12) ? 'Good morning.' : 'Good afternoon.') }; } onRender() { this.showChildView('cards', new HomeCardsView({collection: window.app.cards})); } }
const Marionette = require('backbone.marionette'); const HomeCardsView = require('./HomeCardsView.js'); module.exports = class HomeCapabilityView extends Marionette.View { template = Templates['capabilities/home/home']; className() { return 'home-capability'; } regions() { return {cards: '.cards-container'}; } initialize() { // Update the greeting... this.refreshInterval = setInterval(this.render.bind(this), 1000 * 60 * 5); } serializeData() { const hour = (new Date()).getHours(); return { greeting: (hour < 4 || hour >= 19) ? 'Good evening' : ((hour < 12) ? 'Good morning' : 'Good afternoon') }; } onRender() { this.showChildView('cards', new HomeCardsView({collection: window.app.cards})); } onDestroy() { clearInterval(this.refreshInterval); } }
Update the home screen greeting sometimes
Update the home screen greeting sometimes
JavaScript
mit
monitron/jarvis-ha,monitron/jarvis-ha
568abc38f0d1ef58ede0af5fcdcc31d0e99d595d
src/game/vue-game-plugin.js
src/game/vue-game-plugin.js
import GameStateManager from "./GameStates/GameStateManager"; // import CommandParser from "./Commands/CommandParser"; import GenerateName from "./Generators/NameGenerator"; export default { install: (Vue) => { Vue.prototype.$game = { startGame() { return GameStateManager.StartGame(); }, generateName() { return GenerateName(); }, parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); } } } }
import GameStateManager from "./GameStates/GameStateManager"; // import CommandParser from "./Commands/CommandParser"; import GenerateName from "./Generators/NameGenerator"; export default { install: (Vue) => { Vue.prototype.$game = { start() { GameStateManager.StartGame(); }, receiveInput(input) { console.log(input); GameStateManager.receiveInput(input); }, generateName() { return GenerateName(); }, parseCommand(command) { // return CommandParser.ParseCommand(command); console.log("Parsing " + command); }, getCurrentState() { return GameStateManager.currentState; } } } }
Add new game methods for state/input management
Add new game methods for state/input management
JavaScript
mit
Trymunx/Dragon-Slayer,Trymunx/Dragon-Slayer
1b55bfd142856c2d2fcda4a21a23df323e4ad5b1
addon/pods/components/frost-tabs/component.js
addon/pods/components/frost-tabs/component.js
import Ember from 'ember' import layout from './template' import PropTypesMixin, { PropTypes } from 'ember-prop-types' import uuid from 'ember-simple-uuid' export default Ember.Component.extend(PropTypesMixin, { // == Component properties ================================================== layout: layout, classNames: ['frost-tabs'], // == State properties ====================================================== propTypes: { tabs: PropTypes.array.isRequired, selectedTab: PropTypes.string, targetOutlet: PropTypes.string, onChange: PropTypes.func, hook: PropTypes.string }, getDefaultProps () { return { targetOutlet: `frost-tab-content-${uuid()}` } } })
import Ember from 'ember' import layout from './template' import PropTypesMixin, { PropTypes } from 'ember-prop-types' import uuid from 'ember-simple-uuid' export default Ember.Component.extend(PropTypesMixin, { // == Component properties ================================================== layout: layout, classNames: ['frost-tabs'], // == State properties ====================================================== propTypes: { tabs: PropTypes.array.isRequired, selectedTab: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, hook: PropTypes.string.isRequired, targetOutlet: PropTypes.string }, getDefaultProps () { return { targetOutlet: `frost-tab-content-${uuid()}` } } })
Put some property as required.
Put some property as required.
JavaScript
mit
ciena-frost/ember-frost-tabs,ciena-frost/ember-frost-tabs,ciena-frost/ember-frost-tabs
254d2831fcab758f55302a01032fe73c3fe49e10
www/modules/core/components/session.service.js
www/modules/core/components/session.service.js
(function() { 'use strict'; angular.module('Core') .service('sessionService', sessionService); sessionService.$inject = ['commonService']; function sessionService(commonService) { var service = this; service.isUserLoggedIn = isUserLoggedIn; /* ======================================== Var ==================================================== */ service.userData = { }; /* ======================================== Services =============================================== */ /* ======================================== Public Methods ========================================= */ function isUserLoggedIn() { // Check if user is logged in } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
(function() { 'use strict'; angular.module('Core') .service('sessionService', sessionService); sessionService.$inject = []; function sessionService() { var service = this; service.isUserLoggedIn = isUserLoggedIn; /* ======================================== Var ==================================================== */ service.userData = { }; /* ======================================== Services =============================================== */ /* ======================================== Public Methods ========================================= */ function isUserLoggedIn() { // Check if user is logged in } /* ======================================== Private Methods ======================================== */ function init() { } init(); } })();
Remove commonSvc dependency to prevent circular dependency
Remove commonSvc dependency to prevent circular dependency
JavaScript
mit
tlkiong/cxa_test,tlkiong/cxa_test
e7bef4ca97a6c73ce6a0f547387f2864d2c61d6e
module.js
module.js
var fs = require("fs"); var cur_pid = parseInt(fs.readFileSync(".muon").toString()); if (!isNaN(cur_pid)){ console.log("Server already running: process id "+cur_pid); process.kill(); } fs.writeFileSync(".muon",process.pid); process.on('SIGINT', function() { fs.writeFileSync(".muon",""); process.kill(); }); module.exports = { "server": function() { return require("./lib/app.js") }, "plugin" : function() { return require("./server/plugin.js") } };
var fs = require("fs"); var cur_pid = parseInt(fs.readFileSync(".muon").toString()); if (cur_pid != process.pid && !isNaN(cur_pid)){ console.log("Server already running: process id "+cur_pid); process.kill(); } fs.writeFileSync(".muon",process.pid); process.on('SIGINT', function() { fs.writeFileSync(".muon",""); process.kill(); }); module.exports = { "server": function() { return require("./lib/app.js") }, "plugin" : function() { return require("./server/plugin.js") } };
Check process id when reloading
Check process id when reloading
JavaScript
mit
Kreees/muon,Kreees/muon
1b62d12de0c1f9c9b3a08290a1bb9cee14d3039d
index.js
index.js
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
Change tabular to 4 spaces
Change tabular to 4 spaces
JavaScript
mit
sam3d/git-date
55dd1989d910d34fffdef9788192e7d0f7a7e48e
index.js
index.js
var git = require('edge-git'); var repo = new git.repository('./.git/'); console.log(repo.BranchesSync());
var git = require('edge-git'); var repo = new git.repository('./.git/'); console.log(repo.BranchesSync()[0].CommitsSync());
Add a more interesting example
Add a more interesting example
JavaScript
mit
itsananderson/edge-git-example
81f103f34e711a5283762deee89704350aba20d6
index.js
index.js
#!/usr/bin/env node 'use strict'; const child_process = require('child_process'); const commander = require('commander'); const version = require('./package').version; commander .version(version) .usage('[options] <cmd...>'); commander.parse(process.argv); const args = process.argv.slice(2); if (args.length < 2) { commander.help(); } console.log(args); let proc = child_process.spawn(args[0], args.slice(1)); proc.on('close', (code) => { if (code !== 0) { console.error('HODOR!'); } else { console.log('Hodor.'); } });
#!/usr/bin/env node 'use strict'; const child_process = require('child_process'); const commander = require('commander'); const version = require('./package').version; commander .version(version) .usage('[options] <cmd...>'); commander.parse(process.argv); let args = process.argv.slice(2); if (!args.length) { commander.help(); } let proc = child_process.spawn(args[0], args.slice(1)); proc.on('close', (code) => { if (code !== 0) { console.error('HODOR!'); } else { console.log('Hodor.'); } });
Allow commands with no arguments
Allow commands with no arguments
JavaScript
mit
pjdietz/hodo
8f5c1e3234dd32588143f3ca51c01281b577ea17
index.js
index.js
'use strict'; module.exports = function (str, opts) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } opts = opts || {}; return str + ' & ' + (opts.postfix || 'rainbows'); };
'use strict'; module.exports = function (str, opts) { var request = require('sync-request'); var options_obj = { 'headers': { 'user-agent': 'http://github.com/icyflame/gh-gist-owner' } }; var res = request('GET', 'https://api.github.com/gists/' + str, options_obj); var body = JSON.parse(res.getBody()); return body.owner.login; };
Complete the request and return username
Complete the request and return username Signed-off-by: Siddharth Kannan <805f056820c7a1cecc4ab591b8a0a604b501a0b7@gmail.com>
JavaScript
mit
icyflame/gh-gist-owner
e794cbfa89778eab9aae959a1ad90223afeea1e6
index.js
index.js
require( 'dotenv' ).config(); var dropboxModule = require( './modules/dropbox.js' ); var googleDocsModule = require( './modules/googleDocs.js' ); var paypalModule = require( './modules/paypal.js' ); var express = require( 'express' ); var app = express(); app.set( 'port', ( process.env.Port || 30000 ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) { googleDocsModule.googleAPIAuthorize( request, response ); }); app.get( '/trigger', function( request, response ) { googleDocsModule.verifySecrets() .then(function( res ) { console.log( 'Application verified! Fetching PayPal rate.' ); paypalModule.fetchPaypalRate(); response.send( 'Triggered!' ); }) .catch(function( error ) { var errorMessage = 'Failed to authenticate! (' + error + ')'; console.log( errorMessage ); response.send( errorMessage ); }); }); app.listen( app.get( 'port' ), function() { console.log( 'Node app is running at localhost:' + app.get( 'port' ) ); });
require( 'dotenv' ).config(); var dropboxModule = require( './modules/dropbox.js' ); var googleDocsModule = require( './modules/googleDocs.js' ); var paypalModule = require( './modules/paypal.js' ); var express = require( 'express' ); var app = express(); app.set( 'port', ( process.env.PORT ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) { googleDocsModule.googleAPIAuthorize( request, response ); }); app.get( '/trigger', function( request, response ) { googleDocsModule.verifySecrets() .then(function( res ) { console.log( 'Application verified! Fetching PayPal rate.' ); paypalModule.fetchPaypalRate(); response.send( 'Triggered!' ); }) .catch(function( error ) { var errorMessage = 'Failed to authenticate! (' + error + ')'; console.log( errorMessage ); response.send( errorMessage ); }); }); app.listen( app.get( 'port' ), function() { console.log( 'Node app is running at localhost:' + app.get( 'port' ) ); });
Fix a port related issue that persists.
Fix a port related issue that persists.
JavaScript
mit
kmgalanakis/node-js-paypal-rate
f71c6785131adcc85b91789da0d0a0b9f1a9713f
index.js
index.js
var path = require('path'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } var matches = 0, processedSource; processedSource = source.replace(/React\.createClass/g, function (match) { matches++; return '__hotUpdateAPI.createClass'; }); if (!matches) { return source; } return [ 'var __hotUpdateAPI = (function () {', ' var React = require("react");', ' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');', ' return getHotUpdateAPI(React, ' + JSON.stringify(path.basename(this.resourcePath)) + ', module.id);', '})();', processedSource, 'if (module.hot) {', ' module.hot.accept();', ' module.hot.dispose(function () {', ' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');', ' nextTick(__hotUpdateAPI.updateMountedInstances);', ' });', '}' ].join('\n'); };
var path = require('path'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } var matches = 0, processedSource; processedSource = source.replace(/React\.createClass\s*\(\s*\{/g, function (match) { matches++; return '__hotUpdateAPI.createClass({'; }); if (!matches) { return source; } return [ 'var __hotUpdateAPI = (function () {', ' var React = require("react");', ' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');', ' return getHotUpdateAPI(React, ' + JSON.stringify(path.basename(this.resourcePath)) + ', module.id);', '})();', processedSource, 'if (module.hot) {', ' module.hot.accept();', ' module.hot.dispose(function () {', ' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');', ' nextTick(__hotUpdateAPI.updateMountedInstances);', ' });', '}' ].join('\n'); };
Use more precise React.createClass call regex to avoid matching own code
Use more precise React.createClass call regex to avoid matching own code
JavaScript
mit
gaearon/react-hot-loader,gaearon/react-hot-loader
562375c8256c65be9223fb8622fc7ad4fde90b31
index.js
index.js
var buildContents = require('./lib/buildContents'); var buildImports = require('./lib/buildImports'); var buildSection = require('./lib/buildSection'); var extend = require('util')._extend; var fs = require('fs'); var path = require('path'); var processSassDoc = require('./lib/processSassDoc'); var sassdoc = require('sassdoc'); module.exports = function(files, options, cb) { options = extend({ title: 'Settings', output: '_settings.scss', groups: {}, imports: [] }, options); sassdoc.parse(files).then(parse); function parse(data) { var outputPath = path.join(process.cwd(), options.output); data = processSassDoc(data, options.groups); // Erase the existing file if necessary if (fs.existsSync(outputPath)) { fs.unlinkSync(outputPath); } var outputStream = fs.createWriteStream(outputPath, {flags: 'w'}); // Generate the table of contents var titleText = buildContents(options.title, Object.keys(data)); outputStream.write(titleText); // Generate the import list var importText = buildImports(options.imports); outputStream.write(importText); // Iterate through each component var n = 1; for (var i in data) { outputStream.write(buildSection(i, n, data[i])); n++; } cb(); } }
var buildContents = require('./lib/buildContents'); var buildImports = require('./lib/buildImports'); var buildSection = require('./lib/buildSection'); var extend = require('util')._extend; var fs = require('fs'); var path = require('path'); var processSassDoc = require('./lib/processSassDoc'); var sassdoc = require('sassdoc'); module.exports = function(files, options, cb) { options = extend({ title: 'Settings', output: '_settings.scss', groups: {}, imports: [] }, options); if (typeof files === 'string') { files = [files]; } sassdoc.parse(files).then(parse); function parse(data) { var outputPath = path.join(process.cwd(), options.output); data = processSassDoc(data, options.groups); // Erase the existing file if necessary if (fs.existsSync(outputPath)) { fs.unlinkSync(outputPath); } var outputStream = fs.createWriteStream(outputPath, {flags: 'w'}); // Generate the table of contents var titleText = buildContents(options.title, Object.keys(data)); outputStream.write(titleText); // Generate the import list var importText = buildImports(options.imports); outputStream.write(importText); // Iterate through each component var n = 1; for (var i in data) { outputStream.write(buildSection(i, n, data[i])); n++; } cb(); } }
Allow glob search pattern to be passed as a string
Allow glob search pattern to be passed as a string
JavaScript
mit
zurb/octophant,zurb/foundation-settings-parser
0be5cfbe8579f116666d2cd444f8c5c6de330d64
index.js
index.js
var Promise = require('bluebird'); var mapValues = require('lodash.mapvalues'); var assign = require('lodash.assign'); var curry = require('lodash.curry'); function FileWebpackPlugin(files) { this.files = files || {}; } FileWebpackPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('emit', function(compiler, done) { var data = {}; var assetPromises = mapValues(self.files, function(asyncTemplate, filename) { return Promise .fromNode(asyncTemplate.bind(null, data)) .then(createAssetFromContents); }); Promise.props(assetPromises) .then(addAssetsToCompiler(compiler)) .nodeify(done); }); }; var addAssetsToCompiler = curry(function(compiler, assets) { assign(compiler.assets, assets); }); function createAssetFromContents(contents) { return { source: function() { return contents; }, size: function() { return contents.length; } }; } module.exports = FileWebpackPlugin;
var Promise = require('bluebird'); var mapValues = require('lodash.mapvalues'); var assign = require('lodash.assign'); var curry = require('lodash.curry'); function FileWebpackPlugin(files) { this.files = files || {}; } FileWebpackPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('emit', function(compiler, done) { var data = {}; var assetPromises = mapValues(self.files, function(asyncTemplate, filename) { return Promise .fromNode(asyncTemplate.bind(null, data)) .then(createAssetFromContents); }); Promise.props(assetPromises) .then(addAssetsToCompiler(compiler)) .nodeify(done); }); }; var createAssetFromContents = function(contents) { return { source: function() { return contents; }, size: function() { return contents.length; } }; }; var addAssetsToCompiler = curry(function(compiler, assets) { assign(compiler.assets, assets); }); module.exports = FileWebpackPlugin;
Sort functions in order of usage
Sort functions in order of usage
JavaScript
mit
markdalgleish/file-webpack-plugin
c303f40444becc57113d04560705be4f88832b5b
routes/poem.js
routes/poem.js
var _ = require('underscore'); var PoemsRepository = require('../lib/repositories/poems_repository.js'); var poemsRepo = new PoemsRepository(); exports.list = function(req, res) { poemsRepo.all(function(err, poems) { res.render('poem/list', { poems: poems }); }); }; exports.edit = function(req, res) { poemsRepo.read(req.params.id, function(err, poem) { res.render('poem/edit', { poem: poem }); }); }; exports.createform = function(req, res) { res.render('poem/new'); }; exports.create = function(req, res) { poemsRepo.create({ name: req.body.name }, function(err, poem) { res.redirect('/poem/' + poem.id); }); };
var _ = require('underscore'), fs = require('fs'), path = require('path'), PoemsRepository = require('../lib/repositories/poems_repository.js'); var dbConfig; if(fs.existsSync(path.join(__dirname, "../db/config.json"))) { dbConfig = require("../db/config.json"); } else { console.log("The database config file was not found!"); process.exit(1); } var poemsRepo = new PoemsRepository(dbConfig); exports.list = function(req, res) { poemsRepo.all(function(err, poems) { res.render('poem/list', { poems: poems }); }); }; exports.edit = function(req, res) { poemsRepo.read(req.params.id, function(err, poem) { res.render('poem/edit', { poem: poem }); }); }; exports.createform = function(req, res) { res.render('poem/new'); }; exports.create = function(req, res) { poemsRepo.create({ name: req.body.name }, function(err, poem) { res.redirect('/poem/' + poem.id); }); };
Read database config from file. Exit process if file not found.
Read database config from file. Exit process if file not found.
JavaScript
mit
jimguys/poemlab,jimguys/poemlab
259a882114def098b30101aefdcc67366b067aab
src/config.js
src/config.js
module.exports = function(data) { /** * Read in config file and tidy up data * Prefer application to require minimum config as possible */ var config = require('../config.' + environment + '.js'); if (!config.server) config.server = { port: 3000 } if (!config.app) config.app = {} if (!config.cookie) config.cookie = {} config.cookie.key = 'connect.sid'; if (!config.app.useOptimised) { config.app.useOptimised = ('development' == environment) ? false : true; } if (!config.project) config.project = { name: "PinItTo.me" , title: "Welcome!" , _layoutFile: 'layouts/main' , pageName: 'Index' } if (!config.captcha) { config.captcha = { type: 'captcha' } } if (!config.transports || (0 == config.transports.length)) config.transports = config.transports || ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'] config.app.version = data.version config.app.environment = environment config.project.errors = {} config.project.captcha = '' if (!config.app.limits) { config.app.limits = { card: { wait: 0.5 } } } return config }
module.exports = function(data) { /** * Read in config file and tidy up data * Prefer application to require minimum config as possible */ var config = require('../config.' + environment + '.js'); if (!config.server) config.server = { port: 3000 } if (!config.app) config.app = {} if (!config.cookie) config.cookie = {} if (!config.cookie.secret) { config.cookie.secret = 'do-not-tell' console.log('No cookie secret set'.red) } config.cookie.key = 'connect.sid'; if (!config.app.useOptimised) { config.app.useOptimised = ('development' == environment) ? false : true; } if (!config.project) config.project = { name: "PinItTo.me" , title: "Welcome!" , _layoutFile: 'layouts/main' , pageName: 'Index' } if (!config.captcha) { config.captcha = { type: 'captcha' } } if (!config.transports || (0 == config.transports.length)) config.transports = config.transports || ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'] config.app.version = data.version config.app.environment = environment config.project.errors = {} config.project.captcha = '' if (!config.app.limits) { config.app.limits = { card: { wait: 0.5 } } } return config }
Set default cookie secret value
Set default cookie secret value
JavaScript
apache-2.0
pinittome/pinitto.me,pinittome/pinitto.me,pinittome/pinitto.me
26ba50793f316564c6ce0f00e131ccc8b668989a
src/router.js
src/router.js
var controllers = require('./controllers'); var mid = require('./middleware'); var router = function(app) { app.get('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.get('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signupPage); app.get('/logout', mid.requiresSecure, mid.requiresLogin, controllers.Account.logout); app.get('/maker', mid.requiresLogin, controllers.Domo.makerPage); app.get('/', mid.requiresLogout, controllers.Account.loginPage); app.post('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.login); app.post('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signup); app.post('/maker', mid.requiresLogin, controllers.Domo.make); }; module.exports = router;
var controllers = require('./controllers'); var mid = require('./middleware'); var router = function(app) { app.get('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.get('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signupPage); app.get('/logout', mid.requiresSecure, mid.requiresLogin, controllers.Account.logout); app.get('/maker', mid.requiresLogin, controllers.Domo.makerPage); app.get('/', mid.requiresSecure, mid.requiresLogout, controllers.Account.loginPage); app.post('/login', mid.requiresSecure, mid.requiresLogout, controllers.Account.login); app.post('/signup', mid.requiresSecure, mid.requiresLogout, controllers.Account.signup); app.post('/maker', mid.requiresLogin, controllers.Domo.make); }; module.exports = router;
Add secure requirement to root page.
Add secure requirement to root page.
JavaScript
apache-2.0
cognettings/nefarious-octo-prune,cognettings/nefarious-octo-prune
d0e488c8c8da1ed827c5c51382c99c2b25f6819a
addon/utils/init-measure-label.js
addon/utils/init-measure-label.js
import MapLabel from './map-label'; import featureCenter from './feature-center'; import getMeasurement from './get-measurement'; export default function initMeasureLabel(result, map) { if (!result) { return; } if (result.mode === 'measure') { let center = featureCenter(result.feature); let measurement = getMeasurement(result.type, result.feature); result.label = new MapLabel(center, { defaultLabel: `${measurement.value} ${measurement.unit}` }); if (map) { result.label.setMap(map); } } }
import MapLabel from './map-label'; import featureCenter from './feature-center'; import getMeasurement from './get-measurement'; export default function initMeasureLabel(result, map) { if (!result) { return; } if (result.mode === 'measure') { let center = featureCenter(result.feature); let measurement = getMeasurement(result.type, result.feature); result.label = new MapLabel(center); result.label.label = `${measurement.value} ${measurement.unit}`; if (map) { result.label.setMap(map); } } }
Fix measurement label not showing on first load
Fix measurement label not showing on first load After importing the label didn't show up because `defaultLabel` option was removed
JavaScript
mit
knownasilya/google-maps-markup,knownasilya/google-maps-markup
b88680fdb87dfd4975dbd568a7ac253315354935
express-res-links.js
express-res-links.js
import {stringify as stringifyLinks} from 'http-header-link' export default function (req, res, next) { res.links = function links (linkObj, lang = false) { let val = this.get('Link') || '' lang = lang || this.get('Content-Language') || linkObj.defaultLang const newLinks = stringifyLinks(linkObj, lang) if (val) { val = val.trim() if (newLinks) { val += ', ' } } val += newLinks this.set('Link', val) } next() }
import {stringify as stringifyLinks} from 'http-header-link' export default function (req, res, next) { res.links = function links (linkObj, lang = false) { if (typeof linkObj !== 'object') { throw new Error('res.links expects linkObj to be an object') } let val = this.get('Link') || '' lang = lang || this.get('Content-Language') || linkObj.defaultLang const newLinks = stringifyLinks(linkObj, lang) if (val) { val = val.trim() if (newLinks) { val += ', ' } } val += newLinks this.set('Link', val) } next() }
Enforce arg0 being an object
Enforce arg0 being an object
JavaScript
mit
ileri/express-res-links
05e26d001bc0c577472c7284dccafd0d3526408a
ui.apps/src/main/webpack/bundles/components.js
ui.apps/src/main/webpack/bundles/components.js
// https://webpack.js.org/guides/dependency-management/#require-context const cache = {}; function importAll(r) { r.keys().forEach((key) => { return cache[key] = r(key); }); } // Include all files named "index.js" in a "webpack.modules/" folder. importAll(require.context('./../../content/jcr_root/', true, /\/webpack\.module\/index\.js$/));
/** * Uncomment the following line to include Babel's polyfill. * Note that this increases the size of the bundled JavaScript file. * So be smart about when and where to include the polyfill. */ // import 'babel-polyfill'; // https://webpack.js.org/guides/dependency-management/#require-context const cache = {}; function importAll(r) { r.keys().forEach((key) => { return cache[key] = r(key); }); } // Include all files named "index.js" in a "webpack.modules/" folder. importAll(require.context('./../../content/jcr_root/', true, /\/webpack\.module\/index\.js$/));
Add note about Babel Polyfill
Add note about Babel Polyfill
JavaScript
mit
infielddigital/aem-webpack-example,infielddigital/aem-webpack-example
3f8e0dd1bb6261f7991790d78f3c20b9df9a2ace
tasks/jscs.js
tasks/jscs.js
"use strict"; var Vow = require( "vow" ); module.exports = function( grunt ) { var filter = Array.prototype.filter, JSCS = require( "./lib/jscs" ).init( grunt ); grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ config: null }), jscs = new JSCS( options ), checks = this.filesSrc.map(function( path ) { return jscs.check( path ); }); Vow.allResolved( checks ).spread(function() { // Filter unsuccessful promises var results = filter.call( arguments, function( promise ) { return promise.isFulfilled(); // Make array of errors }).map(function( promise ) { return promise.valueOf()[ 0 ]; }); jscs.setErrors( results ).report().notify(); done( options.force || !jscs.count() ); }); }); };
"use strict"; var Vow = require( "vow" ); module.exports = function( grunt ) { var filter = Array.prototype.filter, JSCS = require( "./lib/jscs" ).init( grunt ); grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() { var done = this.async(), options = this.options({ // null is a default value, but its equivalent to `true`, // with this way it's easy to distinguish specified value config: null }), jscs = new JSCS( options ), checks = this.filesSrc.map(function( path ) { return jscs.check( path ); }); Vow.allResolved( checks ).spread(function() { // Filter unsuccessful promises var results = filter.call( arguments, function( promise ) { return promise.isFulfilled(); // Make array of errors }).map(function( promise ) { return promise.valueOf()[ 0 ]; }); jscs.setErrors( results ).report().notify(); done( options.force || !jscs.count() ); }); }); };
Add comment for null as default value
Add comment for null as default value
JavaScript
mit
jscs-dev/grunt-jscs,BridgeAR/grunt-jscs
d2eb3ebfb3e82d1fc86b867fed795b97a692c5cd
app/assets/javascripts/application/specialist_guide_pagination.js
app/assets/javascripts/application/specialist_guide_pagination.js
$(function() { var container = $(".specialistguide .govspeak"); var navigation = $(".specialistguide #document_sections"); container.splitIntoPages("h2"); pages = container.find(".page"); pages.hide(); var showDefaultPage = function() { pages.first().show(); } var showPage = function(hash) { var heading = $(hash); if (heading.is(":visible")) { return; } pages.hide(); heading.parents(".page").show(); $('html, body').animate({scrollTop:heading.offset().top}, 0); } navigation.find(">li").each(function(el){ var li = $(this), pageNav = li.find('>ol'), chapterSelector = '#' + li.find('>a').attr('href').split('#')[1], inPageNavigation = $("<div class='in-page-navigation'><h3>On this page</h3></div>"); if (pageNav.length > 0) { inPageNavigation.append(pageNav); $(chapterSelector).after(inPageNavigation); } }); $(window).hashchange(function() { if ((location.hash == "") || (location.hash == "#undefined")) { showDefaultPage(); } else { showPage(location.hash); } }) $(window).hashchange(); })
$(function() { var container = $(".specialistguide .govspeak"); var navigation = $(".specialistguide #document_sections"); container.splitIntoPages("h2"); pages = container.find(".page"); pages.hide(); var showPage = function() { var heading = $(location.hash); if (heading.length == 0) { pages.first().show(); return; } if (heading.is(":visible")) { return; } pages.hide(); heading.parents(".page").show(); $('html, body').animate({scrollTop:heading.offset().top}, 0); } navigation.find(">li").each(function(el){ var li = $(this), pageNav = li.find('>ol'), chapterSelector = '#' + li.find('>a').attr('href').split('#')[1], inPageNavigation = $("<div class='in-page-navigation'><h3>On this page</h3></div>"); if (pageNav.length > 0) { inPageNavigation.append(pageNav); $(chapterSelector).after(inPageNavigation); } }); $(window).hashchange(showPage) $(window).hashchange(); })
Simplify and strengthen specialist guide hide/display page ccode.
Simplify and strengthen specialist guide hide/display page ccode. If the page for the hash can't be found, the first page is shown, preventing js errors if people hack in different hashes (or click on old links)
JavaScript
mit
hotvulcan/whitehall,ggoral/whitehall,ggoral/whitehall,robinwhittleton/whitehall,alphagov/whitehall,hotvulcan/whitehall,alphagov/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,askl56/whitehall,YOTOV-LIMITED/whitehall,robinwhittleton/whitehall,askl56/whitehall,robinwhittleton/whitehall,askl56/whitehall,hotvulcan/whitehall,askl56/whitehall,ggoral/whitehall,YOTOV-LIMITED/whitehall,YOTOV-LIMITED/whitehall,hotvulcan/whitehall,robinwhittleton/whitehall,alphagov/whitehall,alphagov/whitehall
813fede79c31161c54edea2fd706de79ba9c9769
src/api/properties/array.js
src/api/properties/array.js
const { parse, stringify } = window.JSON; export default { coerce (val) { return Array.isArray(val) ? val : [val]; }, default () { return []; }, deserialize (val) { return parse(val); }, serialize (val) { return stringify(val); } };
export default { coerce: val => Array.isArray(val) ? val : [val], default: () => [], deserialize: JSON.parse, serialize: JSON.stringify };
Make code a bit more concise.
Make code a bit more concise.
JavaScript
mit
skatejs/skatejs,chrisdarroch/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs
8bf0cb0069d886b8afe6dc52a31b806496568253
public/theme/portalshit/script.js
public/theme/portalshit/script.js
(function() { var target = $('.archives li').slice(7); target.each(function() { $(this).css("display", "none"); }) $('#show_more_archive_list').click(function() { target.each(function() { $(this).slideDown(); }) $(this).hide(); $('#show_less_archive_list').show(); }) $('#show_less_archive_list').click(function() { target.each(function() { $(this).slideUp(); }) $(this).hide(); $('#show_more_archive_list').show(); }) var init = function(node) { } document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){ var node = evt.target; var requestURL = evt.newValue; var parentNode = evt.relatedNode; init(node); }, false); init(document); })(); window.onload = function() { // fit image for iPad if (navigator.userAgent.match(/iPad/)) { $('.article img').each(function() { var newWidth = document.body.offsetWidth - 60; var imageRatio = this.naturalHeight / this.naturalWidth; if (this.naturalWidth > newWidth) { this.width = newWidth; this.height = newWidth * imageRatio; } }); } };
(function() { var target = $('.archives li').slice(7); target.each(function() { $(this).css("display", "none"); }) $('#show_more_archive_list').click(function() { target.each(function() { $(this).slideDown(); }) $(this).hide(); $('#show_less_archive_list').show(); }) $('#show_less_archive_list').click(function() { target.each(function() { $(this).slideUp(); }) $(this).hide(); $('#show_more_archive_list').show(); }) var init = function(node) { // fit image for iPhone /* if (navigator.userAgent.match(/iPad/)) { */ /* } */ } document.body.addEventListener('AutoPagerize_DOMNodeInserted',function(evt){ var node = evt.target; var requestURL = evt.newValue; var parentNode = evt.relatedNode; init(node); }, false); init(document); })(); window.onload = function() { $('.article img').each(function() { var newWidth = document.body.offsetWidth - 60; var imageRatio = this.naturalHeight / this.naturalWidth; if (this.naturalWidth > newWidth) { this.width = newWidth; this.height = newWidth * imageRatio; } }); };
Revert "Resize only when UA matches iPad"
Revert "Resize only when UA matches iPad" This reverts commit d5260394049c993a4f4ddcea3cbe694212c36f38.
JavaScript
mit
morygonzalez/portalshit.net,morygonzalez/portalshit.net,morygonzalez/portalshit.net,morygonzalez/portalshit.net
d8dac75e6bbbdecfb3ca6f37326dfc35de28da8c
lib/insert.js
lib/insert.js
'use strict' module.exports = function insertInit (showErrors, showStdout) { var callback if (showErrors && showStdout) { callback = function (e, result) { if (e) { console.error(e) return } console.log(JSON.stringify(result.ops[0])) } } else if (showErrors && !showStdout) { callback = function (e) { if (e) { console.error(e) } } } else if (!showErrors && showStdout) { callback = function (e, result) { console.log(JSON.stringify(result.ops[0])) } } return function insert (collection, log) { collection.insertOne(log, { forceServerObjectId: true }, callback) } }
'use strict' module.exports = function insertInit (showErrors, showStdout) { var callback if (showErrors && showStdout) { callback = function (e, result) { if (e) { console.error(e) return } process.stdout.write(JSON.stringify(result.ops[0]) + '\n') } } else if (showErrors && !showStdout) { callback = function (e) { if (e) { console.error(e) } } } else if (!showErrors && showStdout) { callback = function (e, result) { process.stdout.write(JSON.stringify(result.ops[0]) + '\n') } } return function insert (collection, log) { collection.insertOne(log, { forceServerObjectId: true }, callback) } }
Replace console.log to process.stdout to write without formatting
Replace console.log to process.stdout to write without formatting
JavaScript
mit
ViktorKonsta/pino-mongodb
a2c6b35869dd5b9b9bd918f076756bad55d9901c
app/js/arethusa.relation/directives/nested_menu.js
app/js/arethusa.relation/directives/nested_menu.js
"use strict"; angular.module('arethusa.relation').directive('nestedMenu', [ '$compile', 'relation', function($compile, relation) { return { restrict: 'A', scope: { relObj: '=', labelObj: '=', label: '=', property: '=', ancestors: '=' }, link: function(scope, element, attrs) { var html = '\ <ul\ nested-menu-collection\ current="relObj"\ property="property"\ ancestors="ancestors"\ all="labelObj.nested">\ </ul>\ '; if (scope.labelObj.nested) { element.append($compile(html)(scope)); } scope.selectLabel = function() { scope.relObj[scope.property] = scope.label; relation.buildLabel(scope.relObj); }; element.bind('click', function(event) { scope.$apply(function() { if (event.eventPhase === 2) { // at target, three would be bubbling! scope.selectLabel(); if (scope.ancestors) { relation.resetAncestors(scope.relObj); } } if (scope.ancestors) { relation.addAncestor(scope.relObj, scope.label); } }); }); }, template: '{{ label }}' }; } ]);
"use strict"; angular.module('arethusa.relation').directive('nestedMenu', [ '$compile', 'relation', function($compile, relation) { return { restrict: 'A', scope: { relObj: '=', labelObj: '=', label: '=', property: '=', ancestors: '=' }, link: function(scope, element, attrs) { var html = '\ <ul\ nested-menu-collection\ current="relObj"\ property="property"\ ancestors="ancestors"\ all="labelObj.nested">\ </ul>\ '; if (scope.labelObj.nested) { element.append($compile(html)(scope)); element.addClass('nested'); } scope.selectLabel = function() { scope.relObj[scope.property] = scope.label; relation.buildLabel(scope.relObj); }; element.bind('click', function(event) { scope.$apply(function() { if (event.eventPhase === 2) { // at target, three would be bubbling! scope.selectLabel(); if (scope.ancestors) { relation.resetAncestors(scope.relObj); } } if (scope.ancestors) { relation.addAncestor(scope.relObj, scope.label); } }); }); }, template: '{{ label }}' }; } ]);
Add a nested class for nested menus
Add a nested class for nested menus
JavaScript
mit
Masoumeh/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,Masoumeh/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa
645cd395a670abc82b4ca2312899ded66e80d2eb
app/mixins/handles-validation-errors-for-inputs.js
app/mixins/handles-validation-errors-for-inputs.js
import Ember from 'ember'; export default Ember.Mixin.create({ errors: [], showError: false, syncErrors: function () { if (this.get('isDestroyed')) return; this.set('errors', this.get('parentModel.errors.' + this.get('name'))); }, observeErrors: function () { if (!this.get('parentModel')) return; this.get('parentModel').addObserver('errors.' + this.get('name'), this, this.syncErrors); }.on('didInsertElement'), // Propagate showError changes to parentModel errorVisibilityForModel: function () { var parentModel = this.get('parentModel'); if (this.get('showError')) { parentModel.trigger('shouldShowValidationError', this.get('name')); } else { parentModel.trigger('shouldDismissValidationError', this.get('name')); } }.observes('showError', 'name') });
import Ember from 'ember'; export default Ember.Mixin.create({ errors: [], showError: false, syncErrors: function () { if (this.get('isDestroyed')) return; this.set('errors', this.get('parentModel.errors.' + this.get('name'))); }, observeErrors: function () { if (!this.get('parentModel')) return; this.get('parentModel').addObserver('errors.' + this.get('name'), this, this.syncErrors); }.on('didInsertElement'), // Propagate showError changes to parentModel errorVisibilityForModel: function () { var parentModel = this.get('parentModel'); if (!parentModel) return; if (this.get('showError')) { parentModel.trigger('shouldShowValidationError', this.get('name')); } else { parentModel.trigger('shouldDismissValidationError', this.get('name')); } }.observes('showError', 'name') });
Return created PaymentMethod when user's 401's in /your-account/billing
Return created PaymentMethod when user's 401's in /your-account/billing
JavaScript
mit
dollarshaveclub/ember-uni-form,dollarshaveclub/ember-uni-form
2c7ae72aba286d62526643326e71a942965cee60
app/js/filters/dotToDash.js
app/js/filters/dotToDash.js
'use strict'; angular.module('gisto.filter.dotToDash', []).filter('dotToDash', function () { return function (input) { return input.replace('.','-'); }; });
'use strict'; angular.module('gisto.filter.dotToDash', []).filter('dotToDash', function () { return function (input) { var output = input; if(input.charAt(0) === '.') { output = input.substr(1); } return output.replace('.','-'); }; });
FIX (dotfiles in gist): fix links of dotfiles
FIX (dotfiles in gist): fix links of dotfiles - fix links of dotfiles not handled correctly by "dotToDash" custom filter
JavaScript
mit
Gisto/Gisto,Gisto/Gisto,Gisto/Gisto,shmool/Gisto,shmool/Gisto,shmool/Gisto,Gisto/Gisto
40db9627f80e15aadc231fc3c4ad73fd4afff028
scripts/command-line-utilities.js
scripts/command-line-utilities.js
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable no-console, global-require */ import path from 'path'; const exec = ({ command, isExecuted = true, message, dir = '.', rootPath, verbose = true }, callback) => { if (isExecuted) { if (message) { console.log(message); } const child = require('child_process').exec(command, { cwd: path.resolve(rootPath, dir), maxBuffer: 1024 * 500 }, (err) => { callback(err); }); if (verbose === true) { child.stdout.on('data', (data) => process.stdout.write(data.toString())); } } }; export { exec as default };
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable no-console, global-require */ import path from 'path'; const exec = ({ command, message, dir = '.', rootPath, verbose = true }, callback) => { if (message) { console.log(message); } const child = require('child_process').exec(command, { cwd: path.resolve(rootPath, dir), maxBuffer: 1024 * 500 }, (err) => { callback(err); }); if (verbose === true) { child.stdout.on('data', (data) => process.stdout.write(data.toString())); } }; export { exec as default };
Remove isExecuted from CLI utils
Remove isExecuted from CLI utils
JavaScript
bsd-3-clause
salesforce/design-system-react,salesforce/design-system-react,salesforce/design-system-react
431c9354ae176f0ab2020776145e85bef2dfcd58
app/assets/javascripts/refresh.js
app/assets/javascripts/refresh.js
function refresh () { $(".refresh-link").on("click", function(event) { event.preventDefault(); var $target = $(event.target); var url = $target.attr("href"); var id = url.match(/(\d+)(?!.*\d)/)[0].toString(); var dateTimeIn24Hours = new Date(); var $dateSpan = $(".data" + id); var $timeRemainingSpan = $(".time-remaining" + id); var longest = parseInt($("#longest" + id).text(), 10); var current = parseInt($("#current" + id).text(), 10); $.ajax({ url: url, type: "get" }).done(function(response) { countdown(); }); }); }
function refresh () { $(".refresh-link").on("click", function(event) { event.preventDefault(); var $target = $(event.target); var url = $target.attr("href"); var id = url.match(/(\d+)(?!.*\d)/)[0].toString(); var dateTimeIn24Hours = new Date(); var $dateSpan = $(".data" + id); var $timeRemainingSpan = $(".time-remaining" + id); var longest = parseInt($("#longest" + id).text(), 10); var current = parseInt($("#current" + id).text(), 10); $.ajax({ url: url, type: "get" }).done(function(response) { if ($timeRemainingSpan.text() === "Chain broken:") { $timeRemainingSpan.html("Time remaining: "); $dateSpan.attr("data-countdown", formatCurrentDateTime(dateTimeIn24Hours)); } else { $dateSpan.data("countdown", formatCurrentDateTime(dateTimeIn24Hours)); } incrementStreak(current, longest, id); countdown(); }); }); }
Add conditional to check if chain is currently broken or active
Add conditional to check if chain is currently broken or active
JavaScript
mit
costolo/chain,costolo/chain,costolo/chain