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
36a42af4fa6a02fa45c357020269ca52ca9e27d1
modules/udp.js
modules/udp.js
module.exports = { events: { udp: function (bot, msg, rinfo) { if (rinfo.address === bot.config.get('yakc.ip')) { bot.fireEvents('yakc', msg.toString(), rinfo) } else { bot.notice(bot.config.get('udp.channel'), msg.toString()) } } } }
module.exports = { events: { udp: function (bot, msg, rinfo) { if (rinfo.address === bot.config.get('yakc.ip')) { bot.fireEvents('yakc', msg.toString(), rinfo) } else { bot.notice(bot.config.get('udp.channel'), msg.toString()) // copy https://github.com/zuzak/twitter-irc-udp messages from verified users: if (msg.toString().includes('✓')) { bot.notice(bot.config.get('irc.control'), msg.toString()) } } } } }
Copy interesting tweets to control channel
Copy interesting tweets to control channel
JavaScript
isc
zuzakistan/civilservant,zuzakistan/civilservant
36c93b468c7957a5b793c4eacb1a739c61100ef3
src/Overview.js
src/Overview.js
/* global fetch */ import React from 'react'; import TotalWidget from './TotalWidget'; import NextTripWidget from './NextTripWidget'; import TripTable from './TripTable'; import Map from './Map'; import './scss/overview.scss'; class Overview extends React.Component { constructor() { super(); this.loading = true; this.state = { trips: [] }; } componentDidMount() { this.getData(); } getData() { fetch('http://localhost:4444/trips') .then((response) => { return response.json(); }) .then((trips) => { this.loading = false; this.setState({ trips }); }); } render() { return ( <div className="container"> { this.loading ? <span>Loading..</span> : <section> <div className="row"> <NextTripWidget color="light" nextTrip={this.state.trips.next} /> <TotalWidget color="medium" totals={this.state.trips.total} /> </div> <Map countries={this.state.trips.allCountries} selector="visitedMap" /> <TripTable trips={this.state.trips.visited} /> <h1>Wishlist</h1> <Map countries={this.state.trips.wishlist} selector="wishlistMap" /> </section> } </div> ); } } export default Overview;
/* global fetch document */ import React from 'react'; import TotalWidget from './TotalWidget'; import NextTripWidget from './NextTripWidget'; import TripTable from './TripTable'; import Map from './Map'; import './scss/overview.scss'; class Overview extends React.Component { constructor() { super(); this.loading = true; this.state = { trips: [] }; } componentDidMount() { this.getData(); } getData() { fetch(`${document.location.protocol}//${document.location.hostname}:4444/trips`) .then((response) => { return response.json(); }) .then((trips) => { this.loading = false; this.setState({ trips }); }); } render() { return ( <div className="container"> { this.loading ? <span>Loading..</span> : <section> <div className="row"> <NextTripWidget color="light" nextTrip={this.state.trips.next} /> <TotalWidget color="medium" totals={this.state.trips.total} /> </div> <Map countries={this.state.trips.allCountries} selector="visitedMap" /> <TripTable trips={this.state.trips.visited} /> <h1>Wishlist</h1> <Map countries={this.state.trips.wishlist} selector="wishlistMap" /> </section> } </div> ); } } export default Overview;
Make fetch URL less specific
Make fetch URL less specific
JavaScript
mpl-2.0
MichaelKohler/where,MichaelKohler/where
d25293f6af7ce9d646d64c681b59983d442eab42
js/main.js
js/main.js
$(document).ready(function(){ // Include common elements $("#footer").load("common/footer.html"); $("#header").load("common/header.html", function() { // Add current navigation class based on url locations = location.pathname.split("/"); $('#topnav a[href^="' + locations[locations.length - 1] + '"]').parent().addClass('current'); /** * Handles toggling the navigation menu for small screens. */ var button = document.getElementById( 'topnav' ).getElementsByTagName( 'div' )[0], menu = document.getElementById( 'topnav' ).getElementsByTagName( 'ul' )[0]; if ( undefined === button ) return false; if ( undefined === menu || ! menu.childNodes.length ) { button.style.display = 'none'; return false; } button.onclick = function() { if ( -1 == menu.className.indexOf( 'srt-menu' ) ) menu.className = 'srt-menu'; if ( -1 != button.className.indexOf( 'toggled-on' ) ) { button.className = button.className.replace( ' toggled-on', '' ); menu.className = menu.className.replace( ' toggled-on', '' ); } else { button.className += ' toggled-on'; menu.className += ' toggled-on'; } }; }); });
$(document).ready(function(){ // Include common elements $("#footer").load("common/footer.html"); $("#header").load("common/header.html", function() { // Add current navigation class based on url locations = location.pathname.split("/"); current = $('#topnav a[href^="' + locations[locations.length - 1] + '"]') if (current.length == 0) { current = $('#topnav a[href^="index.html"]'); } current.parent().addClass('current'); /** * Handles toggling the navigation menu for small screens. */ var button = document.getElementById( 'topnav' ).getElementsByTagName( 'div' )[0], menu = document.getElementById( 'topnav' ).getElementsByTagName( 'ul' )[0]; if ( undefined === button ) return false; if ( undefined === menu || ! menu.childNodes.length ) { button.style.display = 'none'; return false; } button.onclick = function() { if ( -1 == menu.className.indexOf( 'srt-menu' ) ) menu.className = 'srt-menu'; if ( -1 != button.className.indexOf( 'toggled-on' ) ) { button.className = button.className.replace( ' toggled-on', '' ); menu.className = menu.className.replace( ' toggled-on', '' ); } else { button.className += ' toggled-on'; menu.className += ' toggled-on'; } }; }); });
Select first nav li by default
Select first nav li by default
JavaScript
mit
mbdimitrova/bmi-fmi,mbdimitrova/bmi-fmi
b30d1d1e94b6c65babb2c9351cfe49153926d3b9
js/main.js
js/main.js
var updatePreviewTarget = function(data, status) { $('.spinner').hide(); $('#preview-target').html(data); renderLatexExpressions(); } var renderLatexExpressions = function() { $('.latex-container').each( function(index) { katex.render( this.textContent, this, { displayMode: $(this).data('displaymode') == 'block' } ); } ); } var main = function() { $('div code').each(function(i, block) { hljs.highlightBlock(block); }); $('button#preview').click( function() { $('#preview-target').html(''); $('.spinner').show(); $('h1.preview').text($('input[name=title]').val()) $.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget); } ); renderLatexExpressions(); }; function searchRedirect(event, searchpage) { var term = (arguments.length == 2) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value; window.location = '/search/' + term + '/'; event.preventDefault(event); } $(main);
var updatePreviewTarget = function(data, status) { $('.spinner').hide(); $('#preview-target').html(data); renderLatexExpressions(); } var renderLatexExpressions = function() { $('.latex-container').each( function(index) { katex.render( this.textContent, this, { displayMode: $(this).data('displaymode') == 'block' } ); } ); } var main = function() { $('div code').each(function(i, block) { hljs.highlightBlock(block); }); $('button#preview').click( function() { $('#preview-target').html(''); $('.spinner').show(); $('h1.preview').text($('input[name=title]').val()) $.post('/note_preview', {text: $('#note-txt').val()}, updatePreviewTarget); } ); renderLatexExpressions(); $("textarea[name='footnotes']").focusin(function(){ $(this).height($(this).height() + 300); }).focusout(function(){ $(this).height($(this).height() - 300); }); }; function searchRedirect(event, searchpage) { var term = (arguments.length == 2) ? document.getElementById('mainsearch').value : document.getElementById('searchbox').value; window.location = '/search/' + term + '/'; event.preventDefault(event); } $(main);
Make footnote textarea expand upon focus
Make footnote textarea expand upon focus
JavaScript
mit
erettsegik/erettsegik.hu,erettsegik/erettsegik.hu,erettsegik/erettsegik.hu
08229bff7728a349aa93eb0dc8db248106cbda97
scripts/export_map.js
scripts/export_map.js
var casper = require('casper').create(); // casper.on('remote.message', function(message) { // console.log(message); // }); var out_dir = 'static/tmp/'; var key = casper.cli.get(0); var url = casper.cli.get(1); var filepath = out_dir + key + '.png'; casper.start(); casper.viewport(1024, 650).thenOpen(url, function() { this.wait(1000); this.capture(filepath); casper.echo(filepath); }); casper.run();
var casper = require('casper').create(); // casper.on('remote.message', function(message) { // console.log(message); // }); var out_dir = 'static/tmp/'; var key = casper.cli.get(0); var url = casper.cli.get(1); var filepath = out_dir + key + '.png'; casper.start(); casper.viewport(1024, 650).thenOpen(url, function() { casper.then(function() { this.wait(2000, (function() { return function() { casper.capture(filepath); casper.echo(filepath); } })()) }); }); casper.run();
Use casper.wait to wait until image are loaded and transitioned
Use casper.wait to wait until image are loaded and transitioned
JavaScript
mit
AstunTechnology/NRW_FishMapMon,AstunTechnology/NRW_FishMapMon,AstunTechnology/NRW_FishMapMon,AstunTechnology/NRW_FishMapMon
b13fd8658d216732d4e54e40e029a8246e73202d
main.js
main.js
'use strict'; var app = require('app'); var dribbbleapi = require('./dribbbleapi'); var mainWindow = null; var dribbbleData = null; var menubar = require('menubar') var mb = menubar({ index: 'file://' + __dirname + '/app/index.html', icon: __dirname + '/app/assets/HotshotIcon.png', width: 400, height: 700, 'max-width': 440, 'min-height': 300, 'min-width': 300, preloadWindow: true }); app.on('window-all-closed', function() { app.quit(); }); mb.on('show', function(){ // mb.window.webContents.send('focus'); mb.window.openDevTools(); });
'use strict'; var app = require('app'); var mainWindow = null; var dribbbleData = null; var menubar = require('menubar') var mb = menubar({ index: 'file://' + __dirname + '/app/index.html', icon: __dirname + '/app/assets/HotshotIcon.png', width: 400, height: 700, 'max-width': 440, 'min-height': 300, 'min-width': 300, preloadWindow: true }); app.on('window-all-closed', function() { app.quit(); }); mb.on('show', function(){ // mb.window.webContents.send('focus'); mb.window.openDevTools(); });
Remove reference to deleted dribbbleApi.js
Remove reference to deleted dribbbleApi.js
JavaScript
cc0-1.0
andrewnaumann/hotshot,andrewnaumann/hotshot
21f7adb8f7e293f205c7b0813726c10a2a1224f1
tests/dummy/config/dependency-lint.js
tests/dummy/config/dependency-lint.js
/* eslint-env node */ 'use strict'; module.exports = { allowedVersions: { 'ember-in-element-polyfill': '*', 'ember-get-config': '0.3.0 || 0.4.0 || 0.5.0', '@embroider/util': '*', }, };
/* eslint-env node */ 'use strict'; module.exports = { allowedVersions: { 'ember-in-element-polyfill': '*', }, };
Remove unneeded dependency lint overrides
Remove unneeded dependency lint overrides
JavaScript
mit
ilios/common,ilios/common
14fb941b6db1aa53e7906a46e8cf7f6d4abb6d94
Rightmove_Enhancement_Suite.user.js
Rightmove_Enhancement_Suite.user.js
// ==UserScript== // @name Rightmove Enhancement Suite // @namespace https://github.com/chigley/ // @description Keyboard shortcuts // @include http://www.rightmove.co.uk/* // @version 1 // @grant GM_addStyle // @grant GM_getResourceText // @resource style style.css // ==/UserScript== var $ = unsafeWindow.jQuery; GM_addStyle(GM_getResourceText("style")); $("#summaries li").mouseenter(function () { $(this).addClass("hovered"); }); $("#summaries li").mouseleave(function () { $(this).removeClass("hovered"); });
// ==UserScript== // @name Rightmove Enhancement Suite // @namespace https://github.com/chigley/ // @description Keyboard shortcuts // @include http://www.rightmove.co.uk/* // @version 1 // @grant GM_addStyle // @grant GM_getResourceText // @resource style style.css // ==/UserScript== var $ = unsafeWindow.jQuery; GM_addStyle(GM_getResourceText("style")); $("[name=summary-list-item]").mouseenter(function () { $(this).addClass("hovered"); }); $("[name=summary-list-item]").mouseleave(function () { $(this).removeClass("hovered"); });
Fix selector to only match list items
Fix selector to only match list items
JavaScript
mit
chigley/rightmove-enhancement-suite
c2b47f8a3c1d3f844152127c9218d90dfa66bbf2
packages/storefront/app/routes/yebo/taxons/show.js
packages/storefront/app/routes/yebo/taxons/show.js
// Ember! import Ember from 'ember'; import SearchRoute from 'yebo-ember-storefront/mixins/search-route'; /** * Taxons show page * This page shows products related to the current taxon */ export default Ember.Route.extend(SearchRoute, { /** * Define the search rules */ searchRules(query, params) { // Create a new taxonomy rule let rule = new YeboSDK.Products.Rules.taxonomy([]); // Set its values rule.values = [params.taxon]; // Set it into the query query.and(rule); }, // Change the current controller setupController: function(controller, model) { // This is indispensable, if out, the model won't be passed to the view controller.set('model', model); // the component that requires current taxon and taxonomies is in application let appController = this.controllerFor('application'); // Define some values let taxon = model.taxon; let taxonomies = model.taxonomies; // Set the values to the application controller appController.set('currentTaxonomy', taxon.get('taxonomy')); appController.set('taxonomies', taxonomies); }, /** * This values will be returned into the route (with the route model) */ searchModel(params) { // Search all the taxonomies and the current taxon return { taxonomies: this.yebo.store.findAll('taxonomy'), taxon: this.yebo.store.find('taxon', params.taxon), }; } });
// Ember! import Ember from 'ember'; import SearchRoute from 'yebo-ember-storefront/mixins/search-route'; /** * Taxons show page * This page shows products related to the current taxon */ export default Ember.Route.extend(SearchRoute, { /** * Define the search rules */ searchRules(query, params) { // Create a new taxonomy rule let rule = new YeboSDK.Products.Rules.taxonomy([]); // Set its values rule.values = [params.taxon]; // Set it into the query query.and(rule); }, // Change the current controller setupController: function(controller, model) { // This is indispensable, if out, the model won't be passed to the view controller.set('model', model); // the component that requires current taxon and taxonomies is in application let appController = this.controllerFor('application'); // Define some values let taxon = model.taxon; let taxonomies = model.taxonomies; // Set the values to the application controller appController.set('currentTaxonomy', taxon.get('taxonomy')); appController.set('taxonomies', taxonomies); }, /** * This values will be returned into the route (with the route model) */ searchModel(params) { // Search all the taxonomies and the current taxon return Ember.RSVP.hash({ taxonomies: this.yebo.store.findAll('taxonomy'), taxon: this.yebo.store.find('taxon', params.taxon), }); } });
Return a promise in the searchModel method
Return a promise in the searchModel method
JavaScript
mit
yebo-ecommerce/ember,yebo-ecommerce/ember,yebo-ecommerce/ember
764743d6b08899286262a50203b11410d90f9694
cypress/support/commands.js
cypress/support/commands.js
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add("login", (email, password) => { ... }) // //mm // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) Cypress.Commands.add('setRadioInput', (selector, value) => { const selectorValue = value === 'Yes' ? '0' : '1' cy.get(`#${selector}-${selectorValue}`).check(); }) Cypress.Commands.add('setTextInput', (selector, value) => { cy.get(`#${selector}`).type(value); })
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add("login", (email, password) => { ... }) // //mm // -- This is a child command -- // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... }) // // // -- This is a dual command -- // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... }) // // // -- This will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) Cypress.Commands.add('setRadioInput', (selector, value) => { const selectorValue = value === 'Yes' ? '0' : '1' cy.get(`#${selector}-${selectorValue}`).check(); }) Cypress.Commands.add('setTextInput', (selector, value) => { cy.get(`#${selector}`).type(value); }) Cypress.Commands.add('setCheckboxInput', (selector) => { cy.get(`#${selector}`).check(); })
Add functionality for filling in checkboxes
Add functionality for filling in checkboxes
JavaScript
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
205535d3723b96163f74e4d18a3dd3a5fa84dcf9
screens/MemoriesScreen.js
screens/MemoriesScreen.js
import React from "react"; import { Text } from "react-native"; export default class MemoriesScreen extends React.Component { render() { return ( <Text>My memories</Text> ); } } MemoriesScreen.route = { navigationBar: { title: "My memories", } };
import React from "react"; import { Text } from "react-native"; var memory = { eventName: "Tree planting", eventDate: Date(), image: require("../static/content/images/memories/01.jpg") }; var userData = { name: "Sara", image: require("../static/content/images/people/users/01_sara_douglas.jpg"), memories: [] }; for (var i = 0; i < 10; i++) { userData.memories.push(memory); } export default class MemoriesScreen extends React.Component { render() { return ( <Text>My memories</Text> ); } } MemoriesScreen.route = { navigationBar: { title: "My memories", } };
Add sample data example to memories screen for UI dev
Add sample data example to memories screen for UI dev
JavaScript
mit
ottobonn/roots
8caa309f6a807555825f277e5f277007544b9957
js/end_game.js
js/end_game.js
var endGame = function(game){ if (game.player.lives > 0) { missBall(game.ball, game.player) } else if (game.player.lives <= 0 ){ gameOver() } } var missBall = function(ball, player){ if ( ball.bottomEdge().y == canvas.height){ return player.loseLife() } return false } function gameOver() { console.log('game over!') alert('Game Over!'); window.location.reload() }
var endGame = function(game){ if (game.player.lives > 0) { missBall(game.ball, game.player) } else if (game.player.lives <= 0 ){ gameOver() } if (stillBricks(game.bricks)) { winGame() } } var missBall = function(ball, player){ if ( ball.bottomEdge().y == canvas.height){ console.log("Lost Life") return player.loseLife() }; } function gameOver() { console.log('game over!') alert('Game Over!'); window.location.reload() } function winGame() { console.log("You Win!") alert("You are the Winner") window.location.reload() } var stillBricks = function (bricks) { var counter = 0 for (var layer in bricks){ bricks[layer].map(function(brick){ if (brick == null){ counter += 1; }; }); } if (counter == 16){ return true } }
Implement win game prompt after all bricks destroyed
Implement win game prompt after all bricks destroyed
JavaScript
mit
theomarkkuspaul/Brick-Breaker,theomarkkuspaul/Brick-Breaker
7388412cc4908793883e0de2348f8b44b72e2256
js/main.js
js/main.js
document.addEventListener('DOMContentLoaded', function() { var searchButton = document.getElementById('search'); searchButton.addEventListener('click', (function() { var query = document.getElementById('form').query.value; var engine = document.querySelector('input[name="engine"]:checked').value; var urls = { 'hackage': 'https://www.haskell.org/hoogle/?hoogle=', 'lts': 'https://www.stackage.org/lts/hoogle?q=', 'nightly': 'https://www.stackage.org/nightly/hoogle?q=' }; var url = urls[engine] + query; chrome.tabs.create({url: url}); })); });
document.addEventListener('DOMContentLoaded', function() { var searchButton = document.getElementById('search'); document.querySelector('input[name="engine"]:checked').focus(); searchButton.addEventListener('click', (function() { var query = document.getElementById('form').query.value; var engine = document.querySelector('input[name="engine"]:checked').value; var urls = { 'hackage': 'https://www.haskell.org/hoogle/?hoogle=', 'lts': 'https://www.stackage.org/lts/hoogle?q=', 'nightly': 'https://www.stackage.org/nightly/hoogle?q=' }; var url = urls[engine] + query; chrome.tabs.create({url: url}); })); });
Add focus on the first radio button
Add focus on the first radio button
JavaScript
mit
yu-i9/HoogleSwitcher,yu-i9/HoogleSwitcher
5641a9bc6a72b30572840e4067c9421ecd973f27
app/assets/javascripts/angular/main/register-controller.js
app/assets/javascripts/angular/main/register-controller.js
(function(){ 'use strict'; angular .module('secondLead') .controller('RegisterCtrl', [ 'Restangular', '$state', 'store', 'UserModel', function (Restangular, $state, store, UserModel) { var register = this; register.newUser = {}; register.onSubmit = function () { UserModel.register(register.newUser) .then(function(response){ if (response.errors){ register.error = response.errors[0]; } else { store.set('jwt',response.token); store.set('user',response.user); $state.go('user.lists', {userID: response.user.id}); register.reset(); } }); }; register.reset = function () { register.newUser = {}; }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .controller('RegisterCtrl', [ 'Restangular', '$state', 'store', 'UserModel', function (Restangular, $state, store, UserModel) { var register = this; register.newUser = {}; register.onSubmit = function () { UserModel.register(register.newUser) .then(function(response){ if (response.errors){ register.error = response.errors[0]; } else { UserModel.setLoggedIn(true); store.set('jwt',response.token); store.set('user',response.user); $state.go('user.lists', {userID: response.user.id}); register.reset(); } }); }; register.reset = function () { register.newUser = {}; }; }]) })();
Add update to usermodel upon signup with register controller
Add update to usermodel upon signup with register controller
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
917b47168540b27682825b50155aaf34ecef3b62
compassion.colleague/ua.js
compassion.colleague/ua.js
var cadence = require('cadence') var util = require('util') function UserAgent (ua) { this._ua = ua } UserAgent.prototype.send = cadence(function (async, properties, body) { var url = util.format('http://%s/kibitz', properties.location) this._ua.fetch({ url: url, post: { islandName: properties.islandName, colleagueId: properties.colleagueId, kibitz: body }, nullify: true }, async()) }) module.exports = UserAgent
var cadence = require('cadence') var util = require('util') function UserAgent (ua) { this._ua = ua } UserAgent.prototype.send = cadence(function (async, properties, body) { var url = util.format('http://%s/kibitz', properties.location) this._ua.fetch({ url: url, post: { key: '(' + properties.islandName + ')' + properties.colleagueId, post: { kibitz: body } }, nullify: true }, async()) }) module.exports = UserAgent
Adjust user agent for new keyed protocol.
Adjust user agent for new keyed protocol.
JavaScript
mit
bigeasy/compassion
4025d7a5b28d6b3b88af5d78b5b31c304d0afca6
assets/src/stories-editor/helpers/test/addAMPExtraProps.js
assets/src/stories-editor/helpers/test/addAMPExtraProps.js
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'generates a unique ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, {} ); expect( props ).toHaveProperty( 'id' ); } ); it( 'uses the existing anchor attribute as the ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { anchor: 'foo' } ); expect( props ).toStrictEqual( { id: 'foo' } ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
Remove tests that are not relevant anymore.
Remove tests that are not relevant anymore.
JavaScript
apache-2.0
ampproject/amp-toolbox-php,ampproject/amp-toolbox-php
e5c906b30e793d73972b133cc3099f48a0a1a919
adapter.js
adapter.js
(function() { var global = this; var karma = global.__karma__; karma.start = function(runner) { var suites = global.__karma_benchmark_suites__; var hasTests = !!suites.length; var errors = []; if (!hasTests) { return complete(); } runNextSuite(); function logResult(event) { var suite = this; var result = event.target; karma.result({ id: result.id, description: suite.name+': '+result.name, suite: [], success: errors.length === 0, log: errors, skipped: false, time: result.stats.mean * 1000, benchmark: { suite: suite.name, name: result.name, stats: result.stats, count: result.count, cycles: result.cycles, error: result.error, hz: result.hz } }); } function logError(evt) { errors.push(evt.target.error); } function runNextSuite() { if (!suites.length) { return complete(); } suites.shift() .on('cycle', logResult) .on('abort error', logError) .on('complete', runNextSuite) .run({ async: true }); } function complete() { karma.complete({ coverage: global.__coverage__ }); } }; }).call(this);
(function() { var global = this; var karma = global.__karma__; karma.start = function(runner) { var suites = global.__karma_benchmark_suites__; var hasTests = !!suites.length; var errors = []; if (!hasTests) { return complete(); } runNextSuite(); function logResult(event) { var suite = this; var result = event.target; karma.result({ id: result.id, description: suite.name+': '+result.name, suite: [], success: errors.length === 0, log: errors, skipped: false, time: result.stats.mean * 1000, benchmark: { suite: suite.name, name: result.name, stats: result.stats, count: result.count, cycles: result.cycles, error: result.error, hz: result.hz } }); // Reset errors errors = []; } function logError(evt) { errors.push(evt.target.error.toString()); } function runNextSuite() { if (!suites.length) { return complete(); } suites.shift() .on('cycle', logResult) .on('abort error', logError) .on('complete', runNextSuite) .run({ async: true }); } function complete() { karma.complete({ coverage: global.__coverage__ }); } }; }).call(this);
Fix logging of errors, Karma expects a string. Reset errors after every cycle.
Fix logging of errors, Karma expects a string. Reset errors after every cycle.
JavaScript
mit
JamieMason/karma-benchmark,JamieMason/karma-benchmark
474fbf5b088004ad676fe71b15f3031755b02b74
src/index.js
src/index.js
import middleware from './internal/middleware' export default middleware export { runSaga } from './internal/runSaga' export { END, eventChannel, channel } from './internal/channel' export { buffers } from './internal/buffers' export { takeEvery, takeLatest } from './internal/sagaHelpers' import { CANCEL } from './internal/proc' import * as effects from './effects' import * as utils from './utils' export function delay(ms, val=true) { let timeoutId; const promise = new Promise((resolve) => { timeoutId = setTimeout(resolve, ms, val); }); promise[CANCEL] = () => clearTimeout(timeoutId); return promise; } export { CANCEL, effects, utils }
import middleware from './internal/middleware' export default middleware export { runSaga } from './internal/runSaga' export { END, eventChannel, channel } from './internal/channel' export { buffers } from './internal/buffers' export { takeEvery, takeLatest } from './internal/sagaHelpers' import { CANCEL } from './internal/proc' import * as effects from './effects' import * as utils from './utils' export function delay(ms, val=true) { let timeoutId; const promise = new Promise((resolve) => { timeoutId = setTimeout(() => resolve(val), ms); }); promise[CANCEL] = () => clearTimeout(timeoutId); return promise; } export { CANCEL, effects, utils }
Replace `setTimeout` call with 2-args version
Replace `setTimeout` call with 2-args version
JavaScript
mit
yelouafi/redux-saga,eiriklv/redux-saga,HansDP/redux-saga,baldwmic/redux-saga,redux-saga/redux-saga,yelouafi/redux-saga,redux-saga/redux-saga,HansDP/redux-saga,eiriklv/redux-saga,granmoe/redux-saga,baldwmic/redux-saga,ipluser/redux-saga,granmoe/redux-saga,ipluser/redux-saga
3a1caf79f987bfa48d53ae06e1a4156fd09a313a
js/models/geonames-data.js
js/models/geonames-data.js
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var GeoNamesData = function(url) { this._url = url; this._loadPromise = null; this._data = []; }; GeoNamesData.prototype.load = function() { if (!this._loadPromise) { this._loadPromise = dom.loadJSON(this._url).then(function(data) { this._data = data; }.bind(this)); } return this._loadPromise; }; if (typeof module !== 'undefined' && module.exports) { module.exports = GeoNamesData; } else { app.GeoNamesData = GeoNamesData; } })(this.app || (this.app = {}));
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var Events = app.Events || require('../base/events.js'); var GeoNamesData = function(url) { this._url = url; this._loadPromise = null; this._data = []; this._events = new Events(); }; GeoNamesData.prototype.on = function() { return Events.prototype.on.apply(this._events, arguments); }; GeoNamesData.prototype.load = function() { if (!this._loadPromise) { this._events.emit('loading'); this._loadPromise = dom.loadJSON(this._url).then(function(data) { this._data = data; this._events.emit('loaded'); }.bind(this)); } return this._loadPromise; }; if (typeof module !== 'undefined' && module.exports) { module.exports = GeoNamesData; } else { app.GeoNamesData = GeoNamesData; } })(this.app || (this.app = {}));
Make events of GeoNames data
Make events of GeoNames data
JavaScript
mit
ionstage/loclock,ionstage/loclock
90ef58c5a31967bf1e172f792bdbff3fba9e7f4a
src/_assets/scripts/components/app/reddit.posts.js
src/_assets/scripts/components/app/reddit.posts.js
import React from 'react'; import { BaseViewComponent } from '../higher-order/index.js'; class RedditPosts extends BaseViewComponent { constructor(props) { super(props); } render() { return ( <div className="posts"> <div className="posts-fetch"> <p onClick={this.props.fetchPosts}>Fetch posts</p> </div> <div className="posts-list"> {this.props.posts.map(function renderPosts(post) { return ( <div key={post.id} className="posts"> <p>{post.title}</p> </div> ); })} </div> </div> ); } } RedditPosts.propTypes = { posts: React.PropTypes.array.isRequired, fetchPosts: React.PropTypes.func.isRequired }; export default RedditPosts;
import React from 'react'; import { Avatar, List, ListItem } from 'material-ui'; import { BaseViewComponent } from '../higher-order/index.js'; class RedditPosts extends BaseViewComponent { constructor(props) { super(props); } render() { return ( <div className="posts"> <div className="posts-fetch"> <p onClick={this.props.fetchPosts}>Fetch posts</p> </div> <div className="posts-list"> <List> {this.props.posts.map(function renderPosts(post) { let avatar = (<Avatar src={post.thumbnail} />); return ( <ListItem leftAvatar={avatar}> <div key={post.id} className="posts"> {post.title} </div> </ListItem> ); })} </List> </div> </div> ); } } RedditPosts.propTypes = { posts: React.PropTypes.array.isRequired, fetchPosts: React.PropTypes.func.isRequired }; export default RedditPosts;
Make songs-list a list of list-items
Make songs-list a list of list-items
JavaScript
mit
yanglinz/reddio,yanglinz/reddio
9fec01f2148a57035bea95fc93f56937473cb510
chrome/browser/resources/net_internals/http_cache_view.js
chrome/browser/resources/net_internals/http_cache_view.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on the HTTP cache. * @constructor */ function HttpCacheView() { const mainBoxId = 'http-cache-view-tab-content'; const statsDivId = 'http-cache-view-cache-stats'; DivView.call(this, mainBoxId); this.statsDiv_ = $(statsDivId); // Register to receive http cache info. g_browser.addHttpCacheInfoObserver(this); } inherits(HttpCacheView, DivView); HttpCacheView.prototype.onLoadLogFinish = function(data) { return this.onHttpCacheInfoChanged(data.httpCacheInfo); }; HttpCacheView.prototype.onHttpCacheInfoChanged = function(info) { this.statsDiv_.innerHTML = ''; if (!info) return false; // Print the statistics. var statsUl = addNode(this.statsDiv_, 'ul'); for (var statName in info.stats) { var li = addNode(statsUl, 'li'); addTextNode(li, statName + ': ' + info.stats[statName]); } return true; };
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on the HTTP cache. */ var HttpCacheView = (function() { // IDs for special HTML elements in http_cache_view.html const MAIN_BOX_ID = 'http-cache-view-tab-content'; const STATS_DIV_ID = 'http-cache-view-cache-stats'; // We inherit from DivView. var superClass = DivView; /** * @constructor */ function HttpCacheView() { // Call superclass's constructor. superClass.call(this, MAIN_BOX_ID); this.statsDiv_ = $(STATS_DIV_ID); // Register to receive http cache info. g_browser.addHttpCacheInfoObserver(this); } cr.addSingletonGetter(HttpCacheView); HttpCacheView.prototype = { // Inherit the superclass's methods. __proto__: superClass.prototype, onLoadLogFinish: function(data) { return this.onHttpCacheInfoChanged(data.httpCacheInfo); }, onHttpCacheInfoChanged: function(info) { this.statsDiv_.innerHTML = ''; if (!info) return false; // Print the statistics. var statsUl = addNode(this.statsDiv_, 'ul'); for (var statName in info.stats) { var li = addNode(statsUl, 'li'); addTextNode(li, statName + ': ' + info.stats[statName]); } return true; } }; return HttpCacheView; })();
Refactor HttpCacheView to be defined inside an anonymous namespace.
Refactor HttpCacheView to be defined inside an anonymous namespace. BUG=90857 Review URL: http://codereview.chromium.org/7544008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@94868 0039d316-1c4b-4281-b951-d872f2087c98
JavaScript
bsd-3-clause
ropik/chromium,adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium
9b12e26b863386ae30b34d5756a45f598b1e0ba0
packages/components/containers/members/MemberAddresses.js
packages/components/containers/members/MemberAddresses.js
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { msgid, c } from 'ttag'; import { SimpleDropdown, DropdownMenu } from 'react-components'; const MemberAddresses = ({ member, addresses }) => { const list = addresses.map(({ ID, Email }) => ( <div key={ID} className="inbl w100 pt0-5 pb0-5 pl1 pr1 ellipsis"> {Email} </div> )); const n = list.length; const addressesTxt = ` ${c('Info').ngettext(msgid`address`, `addresses`, n)}`; const contentDropDown = ( <> {n} <span className="nomobile">{addressesTxt}</span> </> ); // trick for responsive and mobile display return ( <> <SimpleDropdown className="pm-button--link" content={contentDropDown}> <DropdownMenu>{list}</DropdownMenu> <div className="alignright p1"> <Link className="pm-button" to={`/settings/addresses/${member.ID}`}>{c('Link').t`Manage`}</Link> </div> </SimpleDropdown> </> ); }; MemberAddresses.propTypes = { member: PropTypes.object.isRequired, addresses: PropTypes.array.isRequired, }; export default MemberAddresses;
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { msgid, c } from 'ttag'; import { SimpleDropdown, DropdownMenu } from 'react-components'; const MemberAddresses = ({ member, addresses }) => { const list = addresses.map(({ ID, Email }) => ( <div key={ID} className="w100 flex flex-nowrap pl1 pr1 pt0-5 pb0-5"> {Email} </div> )); const n = list.length; const addressesTxt = ` ${c('Info').ngettext(msgid`address`, `addresses`, n)}`; const contentDropDown = ( <> {n} <span className="nomobile">{addressesTxt}</span> </> ); // trick for responsive and mobile display return ( <> <SimpleDropdown className="pm-button--link" content={contentDropDown}> <div className="dropDown-item pt0-5 pb0-5 pl1 pr1 flex"> <Link className="pm-button w100 aligncenter" to={`/settings/addresses/${member.ID}`}>{c('Link') .t`Manage`}</Link> </div> <DropdownMenu>{list}</DropdownMenu> </SimpleDropdown> </> ); }; MemberAddresses.propTypes = { member: PropTypes.object.isRequired, addresses: PropTypes.array.isRequired, }; export default MemberAddresses;
Fix dropdown width in adresses settings
Fix dropdown width in adresses settings
JavaScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
11ee849dab45f6f3d8f3a6fd23d179b561937ece
packages/tslint/index.js
packages/tslint/index.js
/** * Tslint webpack block. * * @see https://github.com/wbuchwalter/tslint-loader */ module.exports = tslint /** * @param {object} [options] See https://github.com/wbuchwalter/tslint-loader#usage * @return {Function} */ function tslint (options) { options = options || {} const loader = (context, extra) => Object.assign({ test: context.fileType('application/x-typescript'), loaders: [ 'tslint-loader' ] }, extra) const module = (context) => ({ loaders: [ loader(context, { enforce: 'pre' }) ] }) const setter = (context) => ({ module: module(context), plugins: [ new context.webpack.LoaderOptionsPlugin({ options: { tslint: options } }) ] }) return Object.assign(setter, { pre }) } function pre (context) { const registeredTypes = context.fileType.all() if (!('application/x-typescript' in registeredTypes)) { context.fileType.add('application/x-typescript', /\.(ts|tsx)$/) } }
/** * Tslint webpack block. * * @see https://github.com/wbuchwalter/tslint-loader */ module.exports = tslint /** * @param {object} [options] See https://github.com/wbuchwalter/tslint-loader#usage * @return {Function} */ function tslint (options) { options = options || {} const setter = (context, helpers) => prevConfig => { const _addLoader = helpers.addLoader({ test: context.fileType('application/x-typescript'), loaders: [ 'tslint-loader' ], enforce: 'pre' }) const _addPlugin = helpers.addPlugin( new context.webpack.LoaderOptionsPlugin({ options: { tslint: options } }) ) return _addLoader(_addPlugin(prevConfig)) } return Object.assign(setter, { pre }) } function pre (context) { const registeredTypes = context.fileType.all() if (!('application/x-typescript' in registeredTypes)) { context.fileType.add('application/x-typescript', /\.(ts|tsx)$/) } }
Update tslint block to use new API
Update tslint block to use new API
JavaScript
mit
andywer/webpack-blocks,andywer/webpack-blocks,andywer/webpack-blocks
4b120aabea20e0f8631b61cc1d9ea4a306b03aad
cypress/integration/list_view.js
cypress/integration/list_view.js
context('List View', () => { before(() => { cy.login('Administrator', 'qwe'); cy.visit('/desk'); cy.window().its('frappe').then(frappe => { frappe.call("frappe.tests.test_utils.setup_workflow"); cy.reload(); }); }); it('Bulk Workflow Action', () => { cy.go_to_list('ToDo'); cy.get('.level-item.list-row-checkbox.hidden-xs').click({ multiple: true, force: true }); }); });
context('List View', () => { before(() => { cy.login('Administrator', 'qwe'); cy.visit('/desk'); cy.window().its('frappe').then(frappe => { frappe.call("frappe.tests.test_utils.setup_workflow"); cy.reload(); }); }); it('enables "Actions" button', () => { const actions = ['Approve', 'Reject', 'Edit', 'Assign To', 'Print','Delete']; cy.go_to_list('ToDo'); cy.get('.level-item.list-row-checkbox.hidden-xs').click({ multiple: true, force: true }); cy.get('.btn.btn-primary.btn-sm.dropdown-toggle').contains('Actions').should('be.visible').click(); cy.get('.dropdown-menu li:visible').should('have.length', 6).each((el, index) => { cy.wrap(el).contains(actions[index]); }).then((elements) => { cy.server(); cy.route({ method: 'POST', url:'api/method/frappe.model.workflow.bulk_workflow_approval' }).as('bulk-approval'); cy.route({ method: 'GET', url:'api/method/frappe.desk.reportview.get*' }).as('update-list'); cy.wrap(elements).contains('Approve').click(); cy.wait(['@bulk-approval', '@update-list']); cy.get('.list-row-container:visible').each(el => { cy.wrap(el).contains('Approved'); }); }); }); });
Update list view UI test
test: Update list view UI test
JavaScript
mit
vjFaLk/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,yashodhank/frappe,mhbu50/frappe,saurabh6790/frappe,yashodhank/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,frappe/frappe,vjFaLk/frappe,saurabh6790/frappe,mhbu50/frappe,frappe/frappe,mhbu50/frappe,StrellaGroup/frappe,StrellaGroup/frappe,adityahase/frappe,vjFaLk/frappe,yashodhank/frappe,StrellaGroup/frappe,saurabh6790/frappe,yashodhank/frappe,almeidapaulopt/frappe,frappe/frappe,adityahase/frappe,saurabh6790/frappe,mhbu50/frappe,vjFaLk/frappe
aee10877af895edd2a8016ddf547ed3f89aed51c
app/config.js
app/config.js
// Use this file to change prototype configuration. // Note: prototype config can be overridden using environment variables (eg on heroku) module.exports = { // Service name used in header. Eg: 'Renew your passport' serviceName: '[Service Name]', // Default port that prototype runs on port: '3000', // Enable or disable password protection on production useAuth: 'true', // Automatically stores form data, and send to all views useAutoStoreData: 'true', // Enable or disable built-in docs and examples. useDocumentation: 'true', // Force HTTP to redirect to HTTPs on production useHttps: 'true', // Cookie warning - update link to service's cookie page. cookieText: 'GOV.UK uses cookies to make the site simpler. <a href="#">Find out more about cookies</a>', // Enable or disable Browser Sync useBrowserSync: 'true' }
// Use this file to change prototype configuration. // Note: prototype config can be overridden using environment variables (eg on heroku) module.exports = { // Service name used in header. Eg: 'Renew your passport' serviceName: 'Dart crossing charge', // Default port that prototype runs on port: '3000', // Enable or disable password protection on production useAuth: 'true', // Automatically stores form data, and send to all views useAutoStoreData: 'true', // Enable or disable built-in docs and examples. useDocumentation: 'true', // Force HTTP to redirect to HTTPs on production useHttps: 'true', // Cookie warning - update link to service's cookie page. cookieText: 'GOV.UK uses cookies to make the site simpler. <a href="#">Find out more about cookies</a>', // Enable or disable Browser Sync useBrowserSync: 'true' }
Update service name to Dart crossing charge for testing
Update service name to Dart crossing charge for testing
JavaScript
mit
soniaturcotte/make-adhoc-payment,soniaturcotte/make-adhoc-payment,soniaturcotte/make-adhoc-payment
908eb28bac7678ddfc89e9009caea52c47f602f7
src/Leaves/Admin/Products/ProductVariations/ProductVariationsViewBridge.js
src/Leaves/Admin/Products/ProductVariations/ProductVariationsViewBridge.js
scms.create('ProductVariationsViewBridge', function(){ return { attachEvents:function () { var self = this; $(this.viewNode, '.product-variation-tab').click(function(event) { if (!event.target.classList.contains('fa')) { self.changeTab($(this).parent()); } else { if (confirm('Are you sure you want to remove this variation?')) { self.raiseServerEvent('VariationDelete', $(this).data('id')); } } }); }, changeTab:function(tab){ var lastSelected = $('.product-list-tabs.active a'); this.raiseProgressiveServerEvent('changeVariation', lastSelected.data('id'), tab.data('id')); lastSelected.removeClass('active'); tab.addClass('active'); } }; });
scms.create('ProductVariationsViewBridge', function(){ return { attachEvents:function () { var self = this; $('.product-variation-tab', this.viewNode).click(function(event) { if (!event.target.classList.contains('fa')) { self.changeTab($(this).parent()); } else { if (confirm('Are you sure you want to remove this variation?')) { self.raiseServerEvent('VariationDelete', $(this).data('id')); } } }); }, changeTab:function(tab){ var lastSelected = $('.product-list-tabs.active'); this.raiseProgressiveServerEvent('changeVariation', lastSelected.data('id'), tab.data('id')); lastSelected.removeClass('active'); tab.addClass('active'); } }; });
Fix for active class not being set properly
Fix for active class not being set properly
JavaScript
apache-2.0
rojr/SuperCMS,rojr/SuperCMS
5796d850680779441489c60730d1655d8ee5444a
js/validate.js
js/validate.js
var ContextElement = require('./contextElement') module.exports = function (el, cb) { if ( ! (el instanceof ContextElement)) return cb('Given element is not a ContextElement.') var attributes = el.getMapping().attributes for (var i in attributes) { var attr = attributes[i] if ( ! Array.isArray(attr.metadatas)) continue var value = el.getAttributeValue(attr.name) attr.metadatas.forEach(function (meta) { if (meta.name === 'min' && meta.type === 'number') { value = Math.max(value, meta.value) } else if (meta.name === 'min' && meta.type === 'number') { value = Math.min(value, meta.value) } }) el.setAttributeValue(attr.name, value) } cb() }
var ContextElement = require('./contextElement') var validators = { min: function (current, valid) { return Math.max(current, valid) }, max: function (current, valid) { return Math.min(current, valid) }, } module.exports = function (el, cb) { if ( ! (el instanceof ContextElement)) return cb('Given element is not a ContextElement.') var attributes = el.getMapping().attributes for (var i in attributes) { var attr = attributes[i] if ( ! Array.isArray(attr.metadatas)) continue var value = el.getAttributeValue(attr.name) attr.metadatas.forEach(function (meta) { var fn = validators[meta.name] if (typeof fn !== 'function') { console.error('No validator for meta', meta) return } value = fn(value, meta.value) }) el.setAttributeValue(attr.name, value) } cb() }
Make it easy to add validators.
Make it easy to add validators.
JavaScript
mit
kukua/concava
b14dd5a3691cc906209194ba82becfad17a9abde
src/index.js
src/index.js
/** * _____ __ * / ___// /_ _____ * \__ \/ / / / / _ \ * ___/ / / /_/ / __/ * /____/_/\__, /\___/ * /____/ * Copyright 2017 Slye Development Team. All Rights Reserved. * Licence: MIT License */ const tree = require('./core/tree'); const compile = require('./core/compile'); const modules = require('./core/modules'); const blocks = require('./core/blocks'); const configs = require('./core/config'); const cache = require('./core/cache'); var esy_lang = { tree : tree, compile : compile, cache : cache, configs : configs, block : blocks.add, modules : modules._esy(esy_lang) }; module.exports = esy_lang;
/** * _____ __ * / ___// /_ _____ * \__ \/ / / / / _ \ * ___/ / / /_/ / __/ * /____/_/\__, /\___/ * /____/ * Copyright 2017 Slye Development Team. All Rights Reserved. * Licence: MIT License */ const tree = require('./core/tree'); const compile = require('./core/compile'); const modules = require('./core/modules'); const blocks = require('./core/blocks'); const configs = require('./core/config'); const cache = require('./core/cache'); const glob = require('glob'); const path = require('path'); var esy_lang = { tree : tree, compile : compile, cache : cache, configs : configs, block : blocks.add, }; esy_lang['modules'] = modules._esy(esy_lang); // Load modules (function () { var modules = glob.sync('../modules/*/index.js', {cwd: __dirname}), len = modules.length, i = 0; for(;i < len;i++) esy_lang.modules.load(path.join(__dirname, modules[i])) })(); module.exports = esy_lang;
Load modules from modules dir
Load modules from modules dir
JavaScript
mit
Slye-team/esy-language
df1b6c8807ea91bb0f8f5fa5131427699e1d05ca
ignite-base/App/Containers/Styles/ListviewExampleStyle.js
ignite-base/App/Containers/Styles/ListviewExampleStyle.js
// @flow import { StyleSheet } from 'react-native' import { ApplicationStyles, Metrics, Colors } from '../../Themes/' export default StyleSheet.create({ ...ApplicationStyles.screen, container: { flex: 1, marginTop: Metrics.navBarHeight, backgroundColor: Colors.background }, row: { flex: 1, backgroundColor: Colors.fire, marginVertical: Metrics.smallMargin, justifyContent: 'center' }, boldLabel: { fontWeight: 'bold', alignSelf: 'center', color: Colors.snow, textAlign: 'center', marginBottom: Metrics.smallMargin }, label: { textAlign: 'center', color: Colors.snow }, listContent: { marginTop: Metrics.baseMargin } })
// @flow import { StyleSheet } from 'react-native' import { ApplicationStyles, Metrics, Colors } from '../../Themes/' export default StyleSheet.create({ ...ApplicationStyles.screen, container: { flex: 1, marginTop: Metrics.navBarHeight, backgroundColor: Colors.background }, row: { flex: 1, backgroundColor: Colors.fire, marginVertical: Metrics.smallMargin, justifyContent: 'center' }, boldLabel: { fontWeight: 'bold', alignSelf: 'center', color: Colors.snow, textAlign: 'center', marginVertical: Metrics.smallMargin }, label: { textAlign: 'center', color: Colors.snow, marginBottom: Metrics.smallMargin }, listContent: { marginTop: Metrics.baseMargin } })
Modify listview styles for search listview and general margin
Modify listview styles for search listview and general margin
JavaScript
mit
ruddell/ignite,infinitered/ignite,infinitered/ignite,infinitered/ignite,infinitered/ignite,infinitered/ignite,infinitered/ignite,ruddell/ignite,infinitered/ignite,ruddell/ignite,infinitered/ignite
7dc9c68f59884e13e93dd9d79eff89da545b9315
js/site.js
js/site.js
// Here be the site javascript! $(document).ready(function () { $(".button-collapse").sideNav(); $('.scrollspy').scrollSpy(); $("form").submit(function (event) { event.preventDefault(); $("#send-msg").attr("disabled", true); $("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin"); var msg = $("#message").val(); var mail = $("#email").val(); var subject = $("#subject").val(); payload = {subject: subject, email: mail, message: msg}; // Send mail to the local python mail server $.ajax({ type: "POST", url: "http://46.101.248.58:5000/sendmail", crossDomain: true, data: payload, complete: function (data, status, req) { $("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin"); $("#message").val(""); $("#email").val(""); $("#subject").val(""); $("#send-msg").attr("disabled", false); $('#modal1').openModal(); } }); }); });
// Here be the site javascript! $(document).ready(function () { $(".button-collapse").sideNav(); $('.scrollspy').scrollSpy(); $("form").submit(function (event) { event.preventDefault(); $("#send-msg").attr("disabled", true); $("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin"); var msg = $("#message").val(); var mail = $("#email").val(); var subject = $("#subject").val(); payload = {subject: subject, email: mail, message: msg}; // Send mail to the local python mail server $.ajax({ type: "POST", url: "http://mattij.com:5000/sendmail", crossDomain: true, data: payload, complete: function (data, status, req) { $("#fa-send").toggleClass("fa-envelope-o").toggleClass("fa-spinner").toggleClass("fa-spin"); $("#message").val(""); $("#email").val(""); $("#subject").val(""); $("#send-msg").attr("disabled", false); $('#modal1').openModal(); } }); }); });
Add url to contact form
Add url to contact form
JavaScript
mit
melonmanchan/My-Website,melonmanchan/My-Website,melonmanchan/My-Website,melonmanchan/My-Website
83bfffe5280fb58d27525f18495e0c3ddd8fa6a4
favit/static/js/favorite.js
favit/static/js/favorite.js
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); $('.btn.favorite').click(function() { var $obj = $(this); var target_id = $obj.attr('id').split('_')[1]; $obj.prop('disabled', true); $.ajax({ url: $obj.attr('href'), type: 'POST', data: {target_model: $obj.attr('model'), target_object_id: target_id}, success: function(response) { if (response.status == 'added') { $obj.children().removeClass('icon-star-empty').addClass('icon-star');} else { $obj.children().removeClass('icon-star').addClass('icon-star-empty');} $obj.parent('.favorite').children('.fav-count').text(response.fav_count); $obj.prop('disabled', false); } }); });
$('.btn.favorite').click(function() { var $obj = $(this); var target_id = $obj.attr('id').split('_')[1]; $obj.prop('disabled', true); $.ajax({ url: $obj.attr('href'), type: 'POST', data: {target_model: $obj.attr('model'), target_object_id: target_id}, success: function(response) { if (response.status == 'added') { $obj.children().removeClass('icon-star-empty').addClass('icon-star');} else { $obj.children().removeClass('icon-star').addClass('icon-star-empty');} $obj.parent('.favorite').children('.fav-count').text(response.fav_count); $obj.prop('disabled', false); } }); });
Remove jQuery ajax CSRF headers setting
Remove jQuery ajax CSRF headers setting This should not be done by a library, this is standard Django configuration that should be in any project that uses ajax posting. Also, this conflicts with custom CSRF settings, like different cookie name.
JavaScript
mit
mjroson/django-favit,streema/django-favit,mjroson/django-favit,streema/django-favit,streema/django-favit,mjroson/django-favit
651fd66f865d4a091a507ef935cf204522ff687e
src/background/contexts/speeddial/SpeeddialContext.js
src/background/contexts/speeddial/SpeeddialContext.js
var SpeeddialContext = function() { this.properties = {}; global.opr.speeddial.get(function(speeddialProperties) { this.properties.url = speeddialProperties.url; this.properties.title = speeddialProperties.title; // Set WinTabs feature to LOADED deferredComponentsLoadStatus['SPEEDDIAL_LOADED'] = true; }.bind(this)); }; SpeeddialContext.prototype.constructor = SpeeddialContext; SpeeddialContext.prototype.__defineGetter__('url', function() { return this.properties.url || ""; }); // read SpeeddialContext.prototype.__defineSetter__('url', function(val) { global.opr.speeddial.update({ 'url': val }, function(speeddialProperties) { this.properties.url = speeddialProperties.url; }.bind(this)); }); // write SpeeddialContext.prototype.__defineGetter__('title', function() { return this.properties.title || ""; }); // read SpeeddialContext.prototype.__defineSetter__('title', function(val) { global.opr.speeddial.update({ 'title': val }, function(speeddialProperties) { this.properties.title = speeddialProperties.title; }.bind(this)); }); // write
var SpeeddialContext = function() { this.properties = {}; global.opr.speeddial.get(function(speeddialProperties) { this.properties.url = speeddialProperties.url; this.properties.title = speeddialProperties.title; // Set WinTabs feature to LOADED deferredComponentsLoadStatus['SPEEDDIAL_LOADED'] = true; }.bind(this)); }; SpeeddialContext.prototype.constructor = SpeeddialContext; SpeeddialContext.prototype.__defineGetter__('url', function() { return this.properties.url || ""; }); // read SpeeddialContext.prototype.__defineSetter__('url', function(val) { this.properties.url = val; global.opr.speeddial.update({ 'url': val }, function() {}); }); // write SpeeddialContext.prototype.__defineGetter__('title', function() { return this.properties.title || ""; }); // read SpeeddialContext.prototype.__defineSetter__('title', function(val) { this.properties.title = val; global.opr.speeddial.update({ 'title': val }, function() {}); }); // write
Update Speed Dial API implementation to set attributes independent of Chromium call to update attributes.
Update Speed Dial API implementation to set attributes independent of Chromium call to update attributes.
JavaScript
mit
operasoftware/operaextensions.js,operasoftware/operaextensions.js,operasoftware/operaextensions.js
48229ca6df978a16a071259083b0a3655d66cfd8
lib/Node/prototype/_replace-content.js
lib/Node/prototype/_replace-content.js
'use strict'; var normalize = require('../../Document/prototype/normalize'); module.exports = function (child/*, …child*/) { var oldNodes = this.childNodes, df, nu, i = 0, old; df = normalize.apply(this.ownerDocument, arguments); while ((nu = df.firstChild)) { old = oldNodes[i++]; if (old !== nu) { if (old) this.replaceChild(nu, old); else this.appendChild(nu); } } while (oldNodes.length > i) this.removeChild(oldNodes[i]); return this; };
'use strict'; var normalize = require('../../Document/prototype/normalize') , isDF = require('../../DocumentFragment/is-document-fragment'); module.exports = function (child/*, …child*/) { var oldNodes = this.childNodes, dom, nu, i = 0, old; dom = normalize.apply(this.ownerDocument, arguments); if (isDF(dom)) { while ((nu = dom.firstChild)) { old = oldNodes[i++]; if (old !== nu) { if (old) this.replaceChild(nu, old); else this.appendChild(nu); } } } else if (dom) { old = oldNodes[i++]; if (old !== dom) { if (old) this.replaceChild(dom, old); else this.appendChild(dom); } } while (oldNodes.length > i) this.removeChild(oldNodes[i]); return this; };
Update up to change in normalize
Update up to change in normalize
JavaScript
mit
medikoo/dom-ext
d2a8b435cd8af2788f213163dad7d12bddb4bc11
lib/dictionaries/jscs/requireSpaceAfterKeywords.js
lib/dictionaries/jscs/requireSpaceAfterKeywords.js
/** * @fileoverview Translation for `requireSpaceAfterKeywords` (JSCS) to ESLint * @author Breno Lima de Freitas <https://breno.io> * @copyright 2016 Breno Lima de Freitas. All rights reserved. * See LICENSE file in root directory for full license. */ 'use strict' //------------------------------------------------------------------------------ // Rule Translation Definition //------------------------------------------------------------------------------ module.exports = 2;
/** * @fileoverview Translation for `requireSpaceAfterKeywords` (JSCS) to ESLint * @author Breno Lima de Freitas <https://breno.io> * @copyright 2016 Breno Lima de Freitas. All rights reserved. * See LICENSE file in root directory for full license. */ 'use strict' //------------------------------------------------------------------------------ // Rule Translation Definition //------------------------------------------------------------------------------ module.exports = { name: 'keyword-spacing', truthy: [ 2, 'always' ] };
Fix `missing rule name` eslint conversion error
Fix `missing rule name` eslint conversion error
JavaScript
mit
brenolf/polyjuice
b759f8c8cb9dee4797dd9dd1741d3dc274403eba
tests/spec/SpecHelper.js
tests/spec/SpecHelper.js
beforeEach(function() { this.addMatchers({ toBeLessThan: function(expected) { return this.actual < expected; }, toHaveAllValuesInRange: function (low, high) { for (var idx = 0; idx < this.actual.length; idx += 1) { if (this.actual[idx] < low || this.actual[idx] > high) { return false; } } return true; } }); });
beforeEach(function() { this.addMatchers({ toBeLessThan: function(expected) { return this.actual < expected; }, toHaveAllValuesInRange: function (low, high) { for (var idx = 0; idx < this.actual.length; idx += 1) { if (this.actual[idx] < low || this.actual[idx] > high) { return false; } } return true; } }); }); function setIfUndefined(variable, defaultValue) { variable = (typeof variable === "undefined") ? defaultValue : variable; return variable; }
Add test helper to set default values on variables
Add test helper to set default values on variables
JavaScript
mit
sbnb/capensis-steganography
283d7b238b0a778971a9b77d929acf697b4bd501
lib/resolve-script/find-executables.js
lib/resolve-script/find-executables.js
var _ = require('lodash') var globFirst = require('./glob-first') var log = require('../run/log') var path = require('path') var async = require('async') var isExecutable = require('./is-executable') module.exports = function (patterns, cb) { globFirst(patterns, function (er, results) { if (er) return cb(er) async.map(results, function (result, cb) { isExecutable(result, function (er, itIsExecutable) { if (itIsExecutable) { cb(er, path.resolve(result)) } else { log( 'Warning: scripty - ignoring script "' + result + '" because it' + ' was not executable. Run `chmod +x "' + result + '" if you want' + ' scripty to run it.' ) cb(er, undefined) } }) }, function (er, results) { cb(er, _.compact(results)) }) }) }
var _ = require('lodash') var globFirst = require('./glob-first') var log = require('../run/log') var path = require('path') var async = require('async') var isExecutable = require('./is-executable') module.exports = function (patterns, cb) { globFirst(patterns, function (er, results) { if (er) return cb(er) async.map(results, function (result, cb) { isExecutable(result, function (er, itIsExecutable) { if (itIsExecutable) { cb(er, path.resolve(result)) } else { log( 'Warning: scripty - ignoring script "%s" because it' + ' was not executable. Run `chmod +x "%s" if you want' + ' scripty to run it.', result, result) cb(er, undefined) } }) }, function (er, results) { cb(er, _.compact(results)) }) }) }
Leverage util.format for printf-style logging
Leverage util.format for printf-style logging
JavaScript
mit
testdouble/scripty,testdouble/scripty
78e4bb29dce00ed1a5edcd296790dcbb0959f40b
src/index.js
src/index.js
/* eslint-disable no-console */ console.log('hi'); // Old ES5 way of creating a Class Component // var HelloWorld = React.createClass({ // render: function() { // return ( // <h1>Hello world!</h1> // ); // }; // }); //Old ES5 Stateless Functional Component // var HelloWorld = function(props) { // return ( // <h1>Hello World!</h1> // ); // };
/* eslint-disable no-console */ console.log('hi'); // Old ES5 way of creating a Class Component // var HelloWorld = React.createClass({ // render: function() { // return ( // <h1>Hello world!</h1> // ); // }; // }); //Old ES5 Stateless Functional Component // var HelloWorld = function(props) { // return ( // <h1>Hello World!</h1> // ); // }; //ES6 Stateless Functional Component // const HelloWorld = (props) => { // return ( // <h1>Hello ES6 World!</h1> // ) // }; //Even simpler ES6 Statelss Functional Component // const HelloWorld = props => ( // <h1>Hello ES6 World, simplified!</h1> // );
Add ES6 examples for component creation
Add ES6 examples for component creation
JavaScript
mit
mtheoryx/react-redux-es6,mtheoryx/react-redux-es6
79ff48d6a9ea971e23087791dba13c8faf4086a4
src/index.js
src/index.js
import createFormatters from './createFormatters'; // Check for globally defined Immutable and add an install method to it. if (typeof Immutable !== "undefined") { Immutable.installDevTools = install.bind(null, Immutable); } // I imagine most people are using Immutable as a CommonJS module though... let installed = false; function install(Immutable) { if (typeof window === "undefined") { throw new Error("Can only install immutable-devtools in a browser environment."); } // Don't install more than once. if (installed === true) { return; } window.devtoolsFormatters = window.devtoolsFormatters || []; const { RecordFormatter, OrderedMapFormatter, OrderedSetFormatter, ListFormatter, MapFormatter, SetFormatter, StackFormatter } = createFormatters(Immutable); window.devtoolsFormatters.push( RecordFormatter, OrderedMapFormatter, OrderedSetFormatter, ListFormatter, MapFormatter, SetFormatter, StackFormatter ); installed = true; } module.exports = install; export default install;
import createFormatters from './createFormatters'; // Check for globally defined Immutable and add an install method to it. if (typeof Immutable !== "undefined") { Immutable.installDevTools = install.bind(null, Immutable); } // I imagine most people are using Immutable as a CommonJS module though... let installed = false; function install(Immutable) { const gw = typeof window === "undefined" ? global : window; // Don't install more than once. if (installed === true) { return; } gw.devtoolsFormatters = gw.devtoolsFormatters || []; const { RecordFormatter, OrderedMapFormatter, OrderedSetFormatter, ListFormatter, MapFormatter, SetFormatter, StackFormatter } = createFormatters(Immutable); gw.devtoolsFormatters.push( RecordFormatter, OrderedMapFormatter, OrderedSetFormatter, ListFormatter, MapFormatter, SetFormatter, StackFormatter ); installed = true; } module.exports = install; export default install;
Add support for server side Immutable DevTools
Add support for server side Immutable DevTools Fixes issue #31
JavaScript
bsd-3-clause
andrewdavey/immutable-devtools,andrewdavey/immutable-devtools
26a5db8b6f14d411fc9f05ff016e35558a6c18da
src/index.js
src/index.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Odometer from 'odometer'; export default class ReactOdometer extends Component { static propTypes = { value: PropTypes.number.isRequired, options: PropTypes.object, }; componentDidMount() { this.odometer = new Odometer({ el: ReactDOM.findDOMNode(this), value: this.props.value, ...this.props.options, }); } componentDidUpdate() { this.odometer.update(this.props.value); } render() { return React.createElement('div'); } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Odometer from 'odometer'; export default class ReactOdometer extends Component { static defaultProps = { options: {}, }; static propTypes = { value: PropTypes.number.isRequired, options: PropTypes.object, }; componentDidMount() { const { value, options } = this.props; this.odometer = new Odometer({ el: this.node, value, ...options, }); } componentDidUpdate() { this.odometer.update(this.props.value); } render() { return React.createElement('div', { ref: (node) => { this.node = node; }, }); } }
Use ref instead of findDOMNode
Use ref instead of findDOMNode
JavaScript
mit
inferusvv/react-odometerjs
405b7f10323ba2780a2e2f2376430bf467d9582a
lib/weather.js
lib/weather.js
const needle = require('needle'); const config = require('../config'); const _ = require('lodash'); const weather = { getWeatherInfo: function(req, res){ //TODO add country/city validation here const url = getOpenWeatherUrl(req); needle.get(url, function(error, response) { if (!error && response.statusCode === 200){ res.status(200).send(_.get(response, 'body.weather[0].description')); }else{ console.log(error, response); res.status(404); res.send('Error retrieving data'); } }); }, }; function getOpenWeatherUrl(req) { const city = req.query.city; const country = req.query.country; const url = config.base_url + '?appid=' + process.env.API_KEY + '&q=' + city + ',' + country; return url; } module.exports = weather;
const needle = require('needle'); const _ = require('lodash'); const config = require('../config'); const countriesCities = require('../countries-cities'); const weather = { getWeatherInfo: function(req, res){ const city = req.query.city? req.query.city.toLowerCase():req.query.city; const country = req.query.country?req.query.country.toLowerCase(): req.query.country; const validationResult = validateCityAndCountry(city, country); if(validationResult.message!=='ok'){ res.status(400); res.json({"status":"400", "message":validationResult.message}); return; } const url = getOpenWeatherUrl(city, country); needle.get(url, function(error, response) { if (!error && response.statusCode === 200){ res.status(200).send(_.get(response, 'body.weather[0].description')); }else{ console.log(error, response); res.status(404).send('Error retrieving data'); } }); }, }; function getOpenWeatherUrl(city, country) { return config.base_url + '?appid=' + process.env.API_KEY + '&q=' + city + ',' + country; } function validateCityAndCountry(city, country){ if(country && countriesCities[country]){ if(city && countriesCities[country].indexOf(city)!==-1){ return {message: "ok"} }else{ return {message: "Invalid city " + city + "- pass the full name of a city in "+country.toUpperCase()} } }else{ return {message: "Invalid country " + country + "- pass two character ISO-3166 code"} } } module.exports = weather;
Add validation for city and country
Add validation for city and country
JavaScript
mit
umasudhan/weather
5162dba0bcf51d1d86c64deebe289000eb966ad5
lib/short-url-controller.js
lib/short-url-controller.js
"use strict"; let db = require('./db'); function generateStub(length) { let result = "" for(let i = 0; i < length; i++) { let value = Math.round(Math.random() * 35) if (value > 9) result += String.fromCharCode(value + 87); else result += value } return result; } function shortenUrl(req, res) { let url = req.params.url; let nurl = generateStub(5); let collision = false; while(collision) { db.oneOrNone('select exists(select * from urls where nurl = $1 limit 1);', nurl) .then(function(data) { if (data.exists) { nurl = generateStub(5); collision = true; } else collision = false; }).catch(function(error) { console.log('Error: ' + error); res.send(500); }); } db.none('insert into urls(url, nurl) values($1, $2);', [url, nurl]); res.jsonp({ "oldurl" : url, "newurl" : req.host + '/' + nurl }); } module.exports = shortenUrl;
"use strict"; let db = require('./db'); function generateBase36Stub(length) { let result = "" for(let i = 0; i < length; i++) { let value = Math.round(Math.random() * 35) if (value > 9) result += String.fromCharCode(value + 87); else result += value } return result; } function shortenUrl(req, res) { let url = req.params.url; let nurl = generateBase36Stub(5); let collision = false; while(collision) { db.oneOrNone('select exists(select * from urls where nurl = $1 limit 1);', nurl) .then(function(data) { if (data.exists) { nurl = generateBase36Stub(5); collision = true; } else collision = false; }).catch(function(error) { console.log('Error: ' + error); res.send(500); }); } db.none('insert into urls(url, nurl) values($1, $2);', [url, nurl]); res.jsonp({ "oldurl" : url, "newurl" : req.host + '/' + nurl }); } module.exports = shortenUrl;
Make function name more descript
Make function name more descript
JavaScript
mit
glynnw/url-shortener,glynnw/url-shortener
d8384f73dd7b4e8b447634b3111fc58ae19e1435
content.js
content.js
var themes = [ "faded", "grayscale", "sepia", "wide-blur", "overexposed", "flip-hue", "none" ]; function defaultTheme() { return "faded"; } document.body.classList.add("ugly-http-status-loaded"); if (!window.isSecureContext) { chrome.storage.local.get({ theme: "default" }, function(items) { var theme = items.theme; if (themes.indexOf(theme) === -1) { theme = defaultTheme(); } document.body.classList.add("ugly-http-theme-" + theme); }); }
var themes = [ "faded", "grayscale", "sepia", "wide-blur", "overexposed", "flip-hue", "none" ]; function defaultTheme() { return "faded"; } if (!window.isSecureContext) { chrome.storage.local.get({ theme: "default" }, function(items) { var theme = items.theme; if (themes.indexOf(theme) === -1) { theme = defaultTheme(); } document.body.classList.add("ugly-http-theme-" + theme); }); } setTimeout(function() { document.body.classList.add("ugly-http-status-loaded"); }, 10);
Remove loading dimmer briefly *after* applying theme.
Remove loading dimmer briefly *after* applying theme. Otherwise, the page can briefly flash in full color before the theme is applied.
JavaScript
mit
lgarron/ugly-http-extension,lgarron/ugly-http-extension
4ca56946ccc518ce57188ef64e9327f97f6f30be
tests/unit/utils/build-provider-asset-path-test.js
tests/unit/utils/build-provider-asset-path-test.js
import buildProviderAssetPath from 'preprint-service/utils/build-provider-asset-path'; import { module, test } from 'qunit'; module('Unit | Utility | build provider asset path'); // Replace this with your real tests. test('it works', function(assert) { let result = buildProviderAssetPath(); assert.ok(result); });
import config from 'ember-get-config'; import buildProviderAssetPath from 'preprint-service/utils/build-provider-asset-path'; import { module, test } from 'qunit'; module('Unit | Utility | build provider asset path'); test('build correct path for domain', function(assert) { let result = buildProviderAssetPath('foo', 'bar.baz', true); assert.equal(result, `${config.providerAssetsURL}foo/bar.baz`); }); test('build correct path for non-domain', function(assert) { let result = buildProviderAssetPath('foo', 'bar.baz', false); assert.equal(result, `${config.providerAssetsURL}foo/bar.baz`); });
Update buildProviderAssetPath unit test to do something useful
Update buildProviderAssetPath unit test to do something useful
JavaScript
apache-2.0
baylee-d/ember-preprints,CenterForOpenScience/ember-preprints,laurenrevere/ember-preprints,laurenrevere/ember-preprints,CenterForOpenScience/ember-preprints,baylee-d/ember-preprints
ca9dfe7879ff24cf241e6edbc7c3507562193d77
DynamixelServo.Quadruped.WebInterface/wwwroot/js/VideoStreaming.js
DynamixelServo.Quadruped.WebInterface/wwwroot/js/VideoStreaming.js
let videoImage = document.getElementById('video_image'); videoImage.src = `http://${document.domain}:8080/?action=stream`; let cameraJoystick = { zone: videoImage, color: 'red' }; let cameraJoystickManager = nipplejs.create(cameraJoystick); const clickTimeout = 500; var lastStartClick = Date.now(); cameraJoystickManager.on('added', function (evt, nipple) { nipple.on('move', function (evt, arg) { var json = JSON.stringify({ joystickType: 'camera', angle: arg.angle.radian, MessageType: 'movement', distance: arg.distance }); serverSocket.send(json); }); nipple.on('start', function () { if (Date.now() - lastStartClick < clickTimeout) { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'reset' }); serverSocket.send(json); } else { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'start' }); serverSocket.send(json); } lastStartClick = Date.now(); }); nipple.on('end', function () { var json = JSON.stringify({ joystickType: 'camera', MessageType: 'stop' }); serverSocket.send(json); }); });
let videoImage = document.getElementById('video_image'); videoImage.src = `http://${document.domain}:8080/?action=stream`; let cameraJoystick = { zone: videoImage, color: 'red' }; let cameraJoystickManager = nipplejs.create(cameraJoystick); const clickTimeout = 500; var lastStopClick = Date.now(); cameraJoystickManager.on('added', function (evt, nipple) { nipple.on('move', function (evt, arg) { var json = JSON.stringify({ joystickType: 'camera', angle: arg.angle.radian, MessageType: 'movement', distance: arg.distance }); serverSocket.send(json); }); nipple.on('start', function () { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'start' }); serverSocket.send(json); }); nipple.on('end', function () { if (Date.now() - lastStopClick < clickTimeout) { const json = JSON.stringify( { joystickType: 'camera', MessageType: 'reset' }); serverSocket.send(json); } else { var json = JSON.stringify({ joystickType: 'camera', MessageType: 'stop' }); serverSocket.send(json); } lastStopClick = Date.now(); }); });
Move reset to on stop
Move reset to on stop
JavaScript
apache-2.0
dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo
72c21eee8ad0dfc11b10a70fc2da23ded965b4ec
speclib/jasmineHelpers.js
speclib/jasmineHelpers.js
beforeEach(function () { this.addMatchers({ // Expects that property is synchronous toHold: function () { var actual = this.actual; var notText = this.isNot ? " not" : ""; var r = jsc.check(actual, { quiet: true }); var counterExampleText = r === true ? "" : "Counter example found: " + JSON.stringify(r.counterexample); this.message = function() { return "Expected property to " + notText + " to not hold." + counterExampleText; }; return r === true; }, }); });
beforeEach(function () { this.addMatchers({ // Expects that property is synchronous toHold: function () { var actual = this.actual; var notText = this.isNot ? " not" : ""; /* global window */ var quiet = window && !(/verbose=true/).test(window.location.search); var r = jsc.check(actual, { quiet: quiet }); var counterExampleText = r === true ? "" : "Counter example found: " + JSON.stringify(r.counterexample); this.message = function() { return "Expected property to " + notText + " to not hold." + counterExampleText; }; return r === true; }, }); });
Add verbose=true flag to toHold matcher
Add verbose=true flag to toHold matcher
JavaScript
mit
vilppuvuorinen/jsverify,StoneCypher/jsverify,jsverify/jsverify,jsverify/jsverify,dmitriid/jsverify,izaakschroeder/jsverify,StoneCypher/jsverify
6625342ffa4c5746a19eef757e539f32290f2925
lib/irc.js
lib/irc.js
/* eslint no-console: 0 */ 'use strict'; const irc = require('irc'); const server = process.env.IRC_SERVER; const user = process.env.IRC_USER; const channel = process.env.IRC_CHANNEL; const client = module.exports.client = new irc.Client(server, user, { debug: true, autoConnect: false, autoRejoin: true, channels: [channel], showErrors: true, }); client.connect(5, function() { console.log(arguments); }); if (process.env.NODE_ENV !== 'testing') { client.on('registered', function clientOnRegisterd(message) { console.log(new Date(), '[IRC]', message.args[1]); }); } client.on('error', function clientOnError(error) { console.error(error); console.error('Shutting Down...'); process.exit(1); }); module.exports.notify = function ircPost(nodes, callback) { nodes.forEach(function nodesForEach(node) { // let name = `[${node.name}](${jenkins}/computer/${node.name})`; if (node.offline) { client.say(channel, `Jenkins slave ${node.name} is offline`); } else { client.say(channel, `Jenkins slave ${node.name} is online`); } }); callback(null); };
/* eslint no-console: 0 */ 'use strict'; const irc = require('irc'); const server = process.env.IRC_SERVER; const user = process.env.IRC_USER; const channel = process.env.IRC_CHANNEL; const client = module.exports.client = new irc.Client(server, user, { autoConnect: false, autoRejoin: true, channels: [channel], showErrors: true, }); client.connect(5, function() { console.log(new Date(), '[IRC]', 'Connected!'); }); if (process.env.NODE_ENV !== 'testing') { client.on('registered', function clientOnRegisterd(message) { console.log(new Date(), '[IRC]', message.args[1]); }); } client.on('error', function clientOnError(error) { console.error(error); console.error('Shutting Down...'); process.exit(1); }); module.exports.notify = function ircPost(nodes, callback) { nodes.forEach(function nodesForEach(node) { // let name = `[${node.name}](${jenkins}/computer/${node.name})`; if (node.offline) { client.say(channel, `Jenkins slave ${node.name} is offline`); } else { client.say(channel, `Jenkins slave ${node.name} is online`); } }); callback(null); };
Make IRC handler a bit less verbose
Make IRC handler a bit less verbose
JavaScript
mit
Starefossen/jenkins-monitor
1252f56a802deb2528cfabb2b7cdcedc4d17a1fe
models/vote.js
models/vote.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var VoteSchema = new Schema( { value : Number, created : {type : Date, default : Date.now}, lastEdited : {type : Date, default : Date.now}, project : {type: mongoose.Schema.Types.ObjectId, ref: 'Project'}, author : {type: mongoose.Schema.Types.ObjectId, ref: 'User'} }); module.exports = mongoose.model('Vote', VoteSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var VoteSchema = new Schema( { value : Number, created : {type : Date, default : Date.now}, lastEdited : {type : Date, default : Date.now}, project : {type: mongoose.Schema.Types.ObjectId, ref: 'Project'}, author : {type: mongoose.Schema.Types.ObjectId, ref: 'User'} }); module.exports = mongoose.model('Vote', VoteSchema); module.exports.Value = {}; module.exports.Value.Negative = -1; module.exports.Value.Neutral = 0; module.exports.Value.Positive = 1;
Add value constants to Vote model
Add value constants to Vote model
JavaScript
mit
asso-labeli/labeli-api,asso-labeli/labeli-api,asso-labeli/labeli-api
1b17a79157db5681fb31fd8d911ee2d47a645b9d
wdio.conf.js
wdio.conf.js
exports.config = { specs: [ "./e2e-tests/**/*.tests.js" ], exclude: [], maxInstances: 10, sync: true, logLevel: "result", coloredLogs: true, screenshotPath: "./error-screenshots", baseUrl: "http://the8-dev.azurewebsites.net", waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: "jasmine", jasmineNodeOpts: { defaultTimeoutInterval: 10000 }, reporters: ["spec", "json"], reporterOptions: { outputDir: "./e2e-tests/test-results" }, services: ["selenium-standalone"], capabilities: [ { maxInstances: 5, browserName: "chrome" } ] }
exports.config = { specs: [ "./e2e-tests/**/*.tests.js" ], exclude: [], maxInstances: 10, sync: true, logLevel: "result", coloredLogs: true, screenshotPath: "./error-screenshots", baseUrl: "http://the8-dev.azurewebsites.net", waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: "jasmine", jasmineNodeOpts: { defaultTimeoutInterval: 10000 }, reporters: ["spec", "json"], reporterOptions: { outputDir: "./e2e-tests/test-results" }, services: ["phantomjs"], capabilities: [ { maxInstances: 5, browserName: "chrome" } ] }
Use PhantomJS for e2e tests
Use PhantomJS for e2e tests
JavaScript
mit
joekrie/the8,joekrie/the8,joekrie/the8
de57ef6dcbf79559c50bb6b9298578def2c98529
src/app/lib/api_limits.js
src/app/lib/api_limits.js
const Promise = require('bluebird'); const PERIOD_TIME = 30000; const REQUESTS_PER_PERIOD = 10; function currentTime() { return Date.now(); } class APILimiter { constructor() { this.lastPeriod = 0; this.requests = 0; } makeRequest() { if(this._isPeriodTimedOut()) { this._beginPeriod(); } this.requests = this.requests + 1; if(this.requests >= REQUESTS_PER_PERIOD) { LOG.warn("Max requests reached! Requests are getting delayed."); } } awaitFreeLimit() { if(this.canMakeRequest()) { return Promise.resolve(); } else { return Promise.delay(PERIOD_TIME - (currentTime() - this.lastPeriod)); } } canMakeRequest() { return this._isPeriodTimedOut() || this.requests < REQUESTS_PER_PERIOD; } _beginPeriod() { this.lastPeriod = currentTime(); this.requests = 0; } _isPeriodTimedOut() { return currentTime() - this.lastPeriod > PERIOD_TIME; } } module.exports = APILimiter;
const Promise = require('bluebird'); const PERIOD_TIME = 30000; const REQUESTS_PER_PERIOD = 10; function currentTime() { return Date.now(); } class APILimiter { constructor() { this.lastPeriod = 0; this.requests = 0; } makeRequest() { if(this._isPeriodTimedOut()) { this._beginPeriod(); } this.requests = this.requests + 1; if(this.requests >= REQUESTS_PER_PERIOD) { LOG.warn("Max requests reached! Requests are getting delayed."); } } awaitFreeLimit() { if(this.canMakeRequest()) { return Promise.resolve(); } else { return Promise.delay(PERIOD_TIME - (currentTime() - this.lastPeriod)).then(() => { return this.awaitFreeLimit(); }); } } canMakeRequest() { return this._isPeriodTimedOut() || this.requests < REQUESTS_PER_PERIOD; } _beginPeriod() { this.lastPeriod = currentTime(); this.requests = 0; } _isPeriodTimedOut() { return currentTime() - this.lastPeriod > PERIOD_TIME; } } module.exports = APILimiter;
Make sure to wait for a free limit even after delay
Make sure to wait for a free limit even after delay We have to (possibly) wait again after initially delaying the request when reaching the API Limit. Reason being that more requests get piled up than the next limit is allowing to get through. By waiting for the limit again we ensure that if more requests than the limit would allow got queued up, don't allow all of them to go through. This is subtle but is still important to not run into limits as we're trying to avoid those.
JavaScript
mit
kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop
6593af6c87d41248d9cefc0248b8992a68658d59
patterns-samples/Photos.PhotoDetailNarrowSample.js
patterns-samples/Photos.PhotoDetailNarrowSample.js
enyo.kind({ name: "moon.sample.photos.PhotoDetailNarrowSample", kind : "moon.Panel", classes: "photo-detail", fit: true, title : "PHOTO NAME", titleAbove : "03", titleBelow : "2013-04-08", headerComponents : [ { kind : "moon.IconButton", style : "border:none;", src : "assets/icon-favorite.png"}, { kind : "moon.IconButton", style : "border:none;", src : "assets/icon-download.png"}, { kind : "moon.IconButton", style : "border:none;", src : "assets/icon-next.png"}, ], components: [ {kind : "enyo.Spotlight"}, { kind : "enyo.Image", src : "./assets/default-movie.png", style : "width:600px;height:400px;" } ] });
enyo.kind({ name: "moon.sample.photos.PhotoDetailNarrowSample", kind: "moon.Panel", classes: "photo-detail", fit: true, title: "PHOTO NAME", titleAbove: "03", titleBelow: "2013-04-08", headerComponents : [ {kind: "moon.IconButton", style: "border:none;", src: "assets/icon-favorite.png"}, {kind: "moon.IconButton", style: "border:none;", src: "assets/icon-download.png"}, {kind: "moon.IconButton", style: "border:none;", src: "assets/icon-next.png"}, ], components: [ { //bindFrom: "src" name: "photoDetail", kind: "enyo.Image", src: "", //ontap: "changImage", style: "width:600px;height:400px;" } ], bindings: [ {from: ".controller.src", to: "$.photoDetail.src"} ] }); // Sample model enyo.ready(function(){ var sampleModel = new enyo.Model({ src: "./assets/default-movie.png" }); // Application to render sample new enyo.Application({ view: { classes: "enyo-unselectable moon", components: [ {kind: "enyo.Spotlight"}, { kind: "moon.sample.photos.PhotoDetailNarrowSample", controller: ".app.controllers.photoController", classes: "enyo-fit" } ] }, controllers: [ { name: "photoController", kind: "enyo.ModelController", model: sampleModel, changImage: function(inSender, inEvent) { enyo.log("Item: " + inEvent.originator.parent.controller.model.get("menuItem")); } } ] }); });
Apply MVC to older one
GF-4661: Apply MVC to older one Enyo-DCO-1.1-Signed-off-by: David Um <david.um@lge.com>
JavaScript
apache-2.0
mcanthony/moonstone,mcanthony/moonstone,mcanthony/moonstone,enyojs/moonstone
ed91eac72f4af9dc76e52d85fee204a65d604249
node-red-contrib-alasql.js
node-red-contrib-alasql.js
module.exports = function (RED) { var alasql = require('alasql'); function AlasqlNodeIn(config) { RED.nodes.createNode(this, config); var node = this; node.query = config.query; node.on("input", function (msg) { var sql = this.query || 'SELECT * FROM ?'; var bind = Array.isArray(msg.payload) ? msg.payload : [msg.payload]; alasql.promise(sql, [bind]) .then(function (res) { msg.payload = res; node.status({fill: "green", shape: "dot", text: ' Records: ' + msg.payload.length}); node.send(msg); }).catch((err) => { node.error(err, msg); }); }); } RED.nodes.registerType("alasql", AlasqlNodeIn); }
module.exports = function (RED) { var alasql = require('alasql'); function AlasqlNodeIn(config) { RED.nodes.createNode(this, config); var node = this; node.query = config.query; node.on("input", function (msg) { var sql = this.query || 'SELECT * FROM ?'; var bind = Array.isArray(msg.payload) ? msg.payload : [msg.payload]; alasql.promise(sql, [bind]) .then(function (res) { msg.payload = res; node.status({fill: "green", shape: "dot", text: ' Records: ' + msg.payload.length}); node.send(msg); }).catch((err) => { node.error(err, msg); }); }); this.on('close', () => { node.status({}); }); } RED.nodes.registerType("alasql", AlasqlNodeIn); };
Add on.('close') to clear node status on Deploy
Add on.('close') to clear node status on Deploy
JavaScript
mit
AlaSQL/node-red-contrib-alasql,AlaSQL/node-red-contrib-alasql
cd32c55741feb1bdbf5695b11ed2b0e4bdb11cf1
src/constants/index.js
src/constants/index.js
export const SOCKET_URL = 'wss://ws.onfido.com:9876' export const XHR_URL = 'https://api.onfido.com' export const DOCUMENT_CAPTURE = 'DOCUMENT_CAPTURE' export const FACE_CAPTURE = 'FACE_CAPTURE' export const SET_TOKEN = 'SET_TOKEN' export const SET_AUTHENTICATED = 'SET_AUTHENTICATED' export const SET_WEBSOCKET_SUPPORT = 'SET_WEBSOCKET_SUPPORT' export const SET_GUM_SUPPORT = 'SET_GUM_SUPPORT' export const SET_DOCUMENT_CAPTURED = 'SET_DOCUMENT_CAPTURED' export const SET_FACE_CAPTURED = 'SET_FACE_CAPTURED' export const SET_DOCUMENT_TYPE = 'SET_DOCUMENT_TYPE'
export const SOCKET_URL = 'wss://ws.onfido.com:9876' export const SOCKET_URL_DEV = 'wss://document-check-staging.onfido.co.uk:9876' export const XHR_URL = 'https://api.onfido.com' export const DOCUMENT_CAPTURE = 'DOCUMENT_CAPTURE' export const FACE_CAPTURE = 'FACE_CAPTURE' export const SET_TOKEN = 'SET_TOKEN' export const SET_AUTHENTICATED = 'SET_AUTHENTICATED' export const SET_WEBSOCKET_SUPPORT = 'SET_WEBSOCKET_SUPPORT' export const SET_GUM_SUPPORT = 'SET_GUM_SUPPORT' export const SET_DOCUMENT_CAPTURED = 'SET_DOCUMENT_CAPTURED' export const SET_FACE_CAPTURED = 'SET_FACE_CAPTURED' export const SET_DOCUMENT_TYPE = 'SET_DOCUMENT_TYPE' export const CAPTURE_IS_VALID = 'CAPTURE_IS_VALID'
Add constants for capture valid
Add constants for capture valid
JavaScript
mit
onfido/onfido-sdk-core
649b7be4c27fc54464e3d1a0560f76e8f3505eb8
examples/webpack/config.js
examples/webpack/config.js
const CopyPlugin = require('copy-webpack-plugin'); const ExampleBuilder = require('./example-builder'); const fs = require('fs'); const path = require('path'); const src = path.join(__dirname, '..'); const examples = fs.readdirSync(src) .filter(name => /^(?!index).*\.html$/.test(name)) .map(name => name.replace(/\.html$/, '')); const entry = {}; examples.forEach(example => { entry[example] = `./${example}.js`; }); module.exports = { context: src, target: 'web', entry: entry, optimization: { splitChunks: { name: 'common', // TODO: figure out why this isn't working minChunks: 2 } }, plugins: [ new ExampleBuilder({ templates: path.join(__dirname, '..', 'templates'), common: 'common' }), new CopyPlugin([ {from: '../css', to: 'css'}, {from: 'data', to: 'data'}, {from: 'resources', to: 'resources'}, {from: 'Jugl.js', to: 'Jugl.js'}, {from: 'index.html', to: 'index.html'} ]) ], // TODO: figure out why this hangs // devtool: 'source-map', output: { filename: '[name].js', path: path.join(__dirname, '..', '..', 'build', 'examples') } };
const CopyPlugin = require('copy-webpack-plugin'); const ExampleBuilder = require('./example-builder'); const fs = require('fs'); const path = require('path'); const src = path.join(__dirname, '..'); const examples = fs.readdirSync(src) .filter(name => /^(?!index).*\.html$/.test(name)) .map(name => name.replace(/\.html$/, '')); const entry = {}; examples.forEach(example => { entry[example] = `./${example}.js`; }); module.exports = { context: src, target: 'web', entry: entry, optimization: { runtimeChunk: { name: 'common' }, splitChunks: { name: 'common', chunks: 'initial', minChunks: 2 } }, plugins: [ new ExampleBuilder({ templates: path.join(__dirname, '..', 'templates'), common: 'common' }), new CopyPlugin([ {from: '../css', to: 'css'}, {from: 'data', to: 'data'}, {from: 'resources', to: 'resources'}, {from: 'Jugl.js', to: 'Jugl.js'}, {from: 'index.html', to: 'index.html'} ]) ], devtool: 'source-map', output: { filename: '[name].js', path: path.join(__dirname, '..', '..', 'build', 'examples') } };
Make common chunk (and sourcemap) work
Make common chunk (and sourcemap) work
JavaScript
bsd-2-clause
fredj/ol3,ahocevar/ol3,stweil/ol3,mzur/ol3,stweil/ol3,ahocevar/ol3,stweil/ol3,fredj/ol3,mzur/ol3,adube/ol3,ahocevar/openlayers,geekdenz/ol3,ahocevar/openlayers,bjornharrtell/ol3,adube/ol3,stweil/openlayers,tschaub/ol3,bjornharrtell/ol3,adube/ol3,tschaub/ol3,tschaub/ol3,tschaub/ol3,geekdenz/openlayers,geekdenz/ol3,bjornharrtell/ol3,geekdenz/openlayers,oterral/ol3,ahocevar/ol3,ahocevar/ol3,openlayers/openlayers,openlayers/openlayers,fredj/ol3,stweil/openlayers,stweil/openlayers,stweil/ol3,mzur/ol3,geekdenz/openlayers,ahocevar/openlayers,geekdenz/ol3,geekdenz/ol3,openlayers/openlayers,fredj/ol3,oterral/ol3,oterral/ol3,mzur/ol3
04fd62bb2301d95fce136b3776e65c7fa9a7189b
src/chrome/lib/install.js
src/chrome/lib/install.js
(function () { 'use strict'; var browserExtension = new h.HypothesisChromeExtension({ chromeTabs: chrome.tabs, chromeBrowserAction: chrome.browserAction, extensionURL: function (path) { return chrome.extension.getURL(path); }, isAllowedFileSchemeAccess: function (fn) { return chrome.extension.isAllowedFileSchemeAccess(fn); }, }); browserExtension.listen(window); chrome.runtime.onInstalled.addListener(onInstalled); chrome.runtime.onUpdateAvailable.addListener(onUpdateAvailable); function onInstalled(installDetails) { if (installDetails.reason === 'install') { browserExtension.firstRun(); } // We need this so that 3rd party cookie blocking does not kill us. // See https://github.com/hypothesis/h/issues/634 for more info. // This is intended to be a temporary fix only. var details = { primaryPattern: 'https://hypothes.is/*', setting: 'allow' }; chrome.contentSettings.cookies.set(details); chrome.contentSettings.images.set(details); chrome.contentSettings.javascript.set(details); browserExtension.install(); } function onUpdateAvailable() { // TODO: Implement a "reload" notification that tears down the current // tabs and calls chrome.runtime.reload(). } })();
(function () { 'use strict'; var browserExtension = new h.HypothesisChromeExtension({ chromeTabs: chrome.tabs, chromeBrowserAction: chrome.browserAction, extensionURL: function (path) { return chrome.extension.getURL(path); }, isAllowedFileSchemeAccess: function (fn) { return chrome.extension.isAllowedFileSchemeAccess(fn); }, }); browserExtension.listen(window); chrome.runtime.onInstalled.addListener(onInstalled); chrome.runtime.requestUpdateCheck(function (status) { chrome.runtime.onUpdateAvailable.addListener(onUpdateAvailable); }); function onInstalled(installDetails) { if (installDetails.reason === 'install') { browserExtension.firstRun(); } // We need this so that 3rd party cookie blocking does not kill us. // See https://github.com/hypothesis/h/issues/634 for more info. // This is intended to be a temporary fix only. var details = { primaryPattern: 'https://hypothes.is/*', setting: 'allow' }; chrome.contentSettings.cookies.set(details); chrome.contentSettings.images.set(details); chrome.contentSettings.javascript.set(details); browserExtension.install(); } function onUpdateAvailable() { chrome.runtime.reload(); } })();
Update the Chrome extension more aggressively
Update the Chrome extension more aggressively Request a chrome update when the extension starts and reload the extension when it's installed.
JavaScript
bsd-2-clause
hypothesis/browser-extension,hypothesis/browser-extension,hypothesis/browser-extension,project-star/browser-extension,hypothesis/browser-extension,project-star/browser-extension,project-star/browser-extension
96f0fe140e5cbe77d5c31feb60f40c4c562be059
src/ui/Video.js
src/ui/Video.js
"use strict"; import React from 'react'; let { PropTypes } = React; let Video = React.createClass({ propTypes: { src: PropTypes.string.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, currentTimeChanged: PropTypes.func, durationChanged: PropTypes.func, }, componentDidMount() { let video = React.findDOMNode(this.refs.video); video.addEventListener('timeupdate', this.props.currentTimeChanged); video.addEventListener('durationchange', this.props.durationChanged); video.addEventListener('progress', this.props.onProgress); video.addEventListener('ended', this.props.onEnd); }, componentWillUnmount() { let video = React.findDOMNode(this.refs.video); video.removeEventListener('timeupdate', this.props.currentTimeChanged); video.removeEventListener('durationchange', this.props.durationChanged); video.removeEventListener('progress', this.props.onProgress); video.removeEventListener('ended', this.props.onEnd); }, render() { let { src, width, height, currentTimeChanged, durationChanged, ...restProps} = this.props; return (<video ref="video" {...restProps} width={width} height={height} timeupdate={currentTimeChanged} durationchange={durationChanged} > <source src={src} /> </video>); }, }); module.exports = Video;
"use strict"; import React from 'react'; let { PropTypes } = React; module.exports = React.createClass({ displayName: 'Video', propTypes: { src: PropTypes.string.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, currentTimeChanged: PropTypes.func, durationChanged: PropTypes.func, }, componentDidMount() { let video = React.findDOMNode(this.refs.video); video.addEventListener('timeupdate', this.props.currentTimeChanged); video.addEventListener('durationchange', this.props.durationChanged); video.addEventListener('progress', this.props.onProgress); video.addEventListener('ended', this.props.onEnd); }, componentWillUnmount() { let video = React.findDOMNode(this.refs.video); video.removeEventListener('timeupdate', this.props.currentTimeChanged); video.removeEventListener('durationchange', this.props.durationChanged); video.removeEventListener('progress', this.props.onProgress); video.removeEventListener('ended', this.props.onEnd); }, shouldComponentUpdate(nextProps) { if ( this.props.width !== nextProps.width || this.props.height !== nextProps.height || this.props.src !== nextProps.src ) { return true; } return false; }, render() { const videoProps = { autoPlay: this.props.autoPlay, width: this.props.width, height: this.props.height, }; return (<video ref="video" {...videoProps}> <source src={this.props.src} /> </video>); }, });
Implement "shouldComponentUpdate" method to minimise noop render calls.
Implement "shouldComponentUpdate" method to minimise noop render calls.
JavaScript
mit
Andreyco/react-video,Andreyco/react-video
37786b6ca041b387ff9be400a1f13412f0f21db8
src/token.js
src/token.js
var MaapError = require("./utils/MaapError.js"); const EventEmitter = require('events'); const util = require('util'); /** * Set dsl's store and point to access at the any engine defined in MaaS. * Token inherits from EventEmitter. Any engine create own events to * comunicate with the other engines. The only once own event of Token is * "update". The event "update" is emit when the new model to be register * into the token. * * @history * | Name | Action performed | Date | * | --- | --- | --- | * | Andrea Mantovani | Create class | 2016-06-01 | * * @author Andrea Mantovani * @license MIT */ var Token = function () { this.modelRegistry = []; this.status = { model: [] }; EventEmitter.call(this); }; util.inherits(Token, EventEmitter); /** * @description * Extract the models stored in the token. * @return {Model[]} */ Token.prototype.extract = function () { return this.modelRegistry; }; /** * @description * Save into this token the model extracted from the dsl file and * send the notifies for each observer attached at the token. * @param model {Model} * The model to store */ Token.prototype.register = function (model) { this.modelRegistry.push(model); this.status.model = model; this.emit("update"); }; module.exports = Token;
var MaapError = require("./utils/MaapError"); const EventEmitter = require("events"); const util = require("util"); /** * Set dsl's store and point to access at the any engine defined in MaaS. * Token inherits from EventEmitter. Any engine create own events to * comunicate with the other engines. The only once own event of Token is * "update". The event "update" is emit when the new model to be register * into the token. The event send the follow object : * ``` * { * models: Model[] * } * ``` * `status.models` is the array with the last models loaded. * * * @history * | Name | Action performed | Date | * | --- | --- | --- | * | Andrea Mantovani | Create class | 2016-06-01 | * * @author Andrea Mantovani * @license MIT */ var Token = function () { this.status = { models: [] }; EventEmitter.call(this); }; util.inherits(Token, EventEmitter); /** * @description * Send the notifies for each observer attached at the token with the model loaded. * @param model {Model} * The model to store */ Token.prototype.register = function (model) { this.status.model = model; this.emit("update", this.status); }; module.exports = Token;
Remove unused array of model
Remove unused array of model
JavaScript
mit
BugBusterSWE/DSLEngine
5866282cc1d94776dc92ab8eeccf447384860715
test/filters.js
test/filters.js
var requirejs = require('requirejs'); var test = require('tape'); requirejs.config({ baseUrl: 'src', }); test('simple substring can be found', function(t) { t.plan(1); var filters = requirejs('filters'); t.assert(filters.isMatch('world', 'hello world and friends')); }); test('multi-word search criteria can be matched', function(t) { t.plan(1); var filters = requirejs('filters'); t.assert(filters.isMatch('world friends', 'hello world and friends')); }); test('all search words must be in search index to be a match', function(t) { t.plan(1); var filters = requirejs('filters'); t.assert(!filters.isMatch('world friends the', 'hello world and friends')); });
var requirejs = require('requirejs'); var test = require('tape'); requirejs.config({ baseUrl: 'src', }); test('simple substring can be found', function(t) { t.plan(1); var filters = requirejs('filters'); t.ok(filters.isMatch('world', 'hello world and friends')); }); test('multi-word search criteria can be matched', function(t) { t.plan(1); var filters = requirejs('filters'); t.ok(filters.isMatch('world friends', 'hello world and friends')); }); test('all search words must be in search index to be a match', function(t) { t.plan(1); var filters = requirejs('filters'); t.notOk(filters.isMatch('world friends the', 'hello world and friends')); });
Use ok/notOk instead of assert
Use ok/notOk instead of assert notOk(condition) is more apparent than assert(!condition). Use ok/notOk to be obvious and consistent.
JavaScript
mit
lightster/quick-switcher,lightster/quick-switcher,lightster/quick-switcher
0c75269a50e1d140c8b2be6c8ef243ac692ba811
test/index.js
test/index.js
var config = require('./config'); var should = require('should'); var nock = require('nock'); var up = require('../index')(config); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ describe('.moves', function(){ describe('.get()', function(){ it('should return correct url', function(){ up.moves.get({}, function(err, body) { body.should.equal('https://jawbone.com/nudge/api/v.1.1/users/@me/moves?'); }, debug); }); }); describe('.get({ xid: 123 })', function(){ it('should return correct url', function(){ up.moves.get({ xid: 123 }, function(err, body) { body.should.equal('https://jawbone.com/nudge/api/v.1.1/moves/123'); }, debug); }); }); }); });
var config = require('./config'); var should = require('should'); var nock = require('nock'); var up = require('../index')(config); var baseApi = nock('https://jawbone.com:443'); describe('up', function(){ describe('.moves', function(){ describe('.get()', function(){ it('should call correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/users/@me/moves?') .reply(200, 'OK!'); up.moves.get({}, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.isDone().should.be.true; api.pendingMocks().should.be.empty; done(); }); }); }); describe('.get({ xid: 123 })', function(){ it('should return correct url', function(done){ var api = baseApi.matchHeader('Accept', 'application/json') .get('/nudge/api/v.1.1/moves/123') .reply(200, 'OK!'); up.moves.get({ xid: 123 }, function(err, body) { (err === null).should.be.true; body.should.equal('OK!'); api.isDone().should.be.true; api.pendingMocks().should.be.empty; done(); }); }); }); }); });
Update initial unit tests to use Nock
Update initial unit tests to use Nock
JavaScript
mit
ryanseys/node-jawbone-up,banaee/node-jawbone-up
d519b8e5022bc7ba0266182bcb3b6d225461d7e4
test/index.js
test/index.js
'use strict'; var expect = require('chaijs/chai').expect; var entries = require('..'); describe('entries', function() { it('produce a nested array of key-value pairs', function() { var input = { a: 1, b: 2, '3': 'c', '4': 'd' }; var expected = [ ['a', 1], ['b', 2], ['3', 'c'], ['4', 'd'] ]; expect(entries(input)).to.deep.have.members(expected); }); it('should work with nested objects', function() { var input = { a: {} }; expect(entries(input)[0][1]).to.equal(input.a); }); it('should work on an empty object', function() { expect(entries({})).to.deep.have.members([]); }); });
'use strict'; var expect = require('chaijs/chai').expect; var entries = require('..'); describe('entries', function() { it('produce a nested array of key-value pairs', function() { var input = { a: 1, b: 2, '3': 'c', '4': 'd' }; var expected = [ ['a', 1], ['b', 2], ['3', 'c'], ['4', 'd'] ]; expect(entries(input)).to.deep.have.members(expected); }); it('should work with nested objects', function() { var input = { a: {} }; expect(entries(input)[0][1]).to.equal(input.a); }); it('should work on an empty object', function() { expect(entries({})).to.deep.have.members([]); }); if (typeof Object.create === 'function') { describe('IE9+ tests', function() { it('should ignore inherited properties (IE9+)', function() { var parent = { parent: true }; var child = Object.create(parent, { child: { value: true } }); expect(entries(child)).to.deep.equal([['child', true]]); }); it('should ignore non-enumerable properties (IE9+)', function() { var source = Object.create({}, { visible: { value: true, enumerable: true }, invisible: { value: true, enumerable: false } }); expect(entries(source)).to.deep.equal([['visible', true]]); }); }); } });
Add enumerables, inherited props tests
Add enumerables, inherited props tests
JavaScript
mit
ndhoule/entries
85d8dbb12ac354540cd8a1f6d48db57e158c09d2
tests/docs.js
tests/docs.js
'use strict'; var docs = require('../docs/docs'); var expect = require('chai').expect; var sinon = require('sinon'); var stub = sinon.stub; var utils = require('./helpers/utils'); var each = utils.each; var any = utils.any; var getContextStub = require('./helpers/get-context-stub'); var Canvas = require('../lib/index.js'); describe('docs', function () { var element = document.createElement('canvas'); stub(element, 'getContext', getContextStub); var canvas = new Canvas(element); it('is a list of groups', function () { expect(docs.length).to.be.above(1); each(docs, function (value) { expect(value.name).to.exist; expect(value.methods).to.exist; }); }); it('should contain all of the canvasimo methods (or aliases)', function () { each(canvas, function (value, key) { var anyGroupContainsTheMethod = any(docs, function (group) { return any(group.methods, function (method) { return method.name === key || method.alias === key; }); }); expect(anyGroupContainsTheMethod).to.be.true; }); }); it('should have names and descriptions for all methods', function () { each(docs, function (group) { each(group.methods, function (method) { expect(method.name).to.exist; expect(method.description).to.exist; expect(method.name.length).to.be.above(5); expect(method.description.length).to.be.above(5); }); }); }); });
'use strict'; var docs = require('../docs/docs'); var expect = require('chai').expect; var sinon = require('sinon'); var stub = sinon.stub; var utils = require('./helpers/utils'); var each = utils.each; var any = utils.any; var getContextStub = require('./helpers/get-context-stub'); var Canvas = require('../lib/index.js'); describe('docs', function () { var element = document.createElement('canvas'); stub(element, 'getContext', getContextStub); var canvas = new Canvas(element); it('is a list of groups', function () { expect(docs.length).to.be.above(1); each(docs, function (value) { expect(value.name).to.exist; expect(value.methods).to.exist; }); }); it('should contain all of the canvasimo methods (or aliases)', function () { each(canvas, function (value, key) { var anyGroupContainsTheMethod = any(docs, function (group) { return any(group.methods, function (method) { return method.name === key || method.alias === key; }); }); expect(anyGroupContainsTheMethod).to.be.true; }); }); });
Remove test for doc names & descriptions
Remove test for doc names & descriptions
JavaScript
mit
JakeSidSmith/canvasimo,JakeSidSmith/canvasimo,JakeSidSmith/sensible-canvas-interface
ce3a0467d18cbb96fb37614c8a26337bbe1d80ec
website/app/application/core/account/settings/settings.js
website/app/application/core/account/settings/settings.js
(function (module) { module.controller("AccountSettingsController", AccountSettingsController); AccountSettingsController.$inject = ["mcapi", "User", "toastr"]; /* @ngInject */ function AccountSettingsController(mcapi, User, toastr) { var ctrl = this; ctrl.fullname = User.attr().fullname; ctrl.updateName = updateName; /////////////////////////// function updateName() { mcapi('/users/%', ctrl.mcuser.email) .success(function () { User.save(ctrl.mcuser); toastr.success('User name updated', 'Success', { closeButton: true }); }).error(function () { }).put({fullname: ctrl.fullname}); } } }(angular.module('materialscommons')));
(function (module) { module.controller("AccountSettingsController", AccountSettingsController); AccountSettingsController.$inject = ["mcapi", "User", "toastr"]; /* @ngInject */ function AccountSettingsController(mcapi, User, toastr) { var ctrl = this; ctrl.fullname = User.attr().fullname; ctrl.updateName = updateName; /////////////////////////// function updateName() { mcapi('/users/%', ctrl.mcuser.email) .success(function () { User.attr.fullname = ctrl.fullname; User.save(); toastr.success('User name updated', 'Success', { closeButton: true }); }).error(function () { }).put({fullname: ctrl.fullname}); } } }(angular.module('materialscommons')));
Update to User.save api references.
Update to User.save api references.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
27fa2729c44fd95129e81894bc52e8e937df5070
management.js
management.js
/** * Management of a device. Supports quering it for information and changing * the WiFi settings. */ class DeviceManagement { constructor(device) { this.device = device; } /** * Get information about this device. Includes model info, token and * connection information. */ info() { return this.device.call('miIO.info'); } /** * Update the wireless settings of this device. Needs `ssid` and `passwd` * to be set in the options object. * * `uid` can be set to associate the device with a Mi Home user id. */ updateWireless(options) { if(typeof options.ssid !== 'string') { throw new Error('options.ssid must be a string'); } if(typeof options.passwd !== 'string') { throw new Error('options.passwd must be a string'); } return this.device.call('miIO.config_router', options) .then(result => { if(! result !== 0) { throw new Error('Failed updating wireless'); } return true; }); } } module.exports = DeviceManagement;
/** * Management of a device. Supports quering it for information and changing * the WiFi settings. */ class DeviceManagement { constructor(device) { this.device = device; } /** * Get information about this device. Includes model info, token and * connection information. */ info() { return this.device.call('miIO.info'); } /** * Update the wireless settings of this device. Needs `ssid` and `passwd` * to be set in the options object. * * `uid` can be set to associate the device with a Mi Home user id. */ updateWireless(options) { if(typeof options.ssid !== 'string') { throw new Error('options.ssid must be a string'); } if(typeof options.passwd !== 'string') { throw new Error('options.passwd must be a string'); } return this.device.call('miIO.config_router', options) .then(result => { if(! result !== 0) { throw new Error('Failed updating wireless'); } return true; }); } /** * Get the wireless state of this device. Includes if the device is * online and counters for things such as authentication failures and * connection success and failures. */ wirelessState() { return this.device.call('miIO.wifi_assoc_state'); } } module.exports = DeviceManagement;
Add ability to get wireless state of a device
Add ability to get wireless state of a device
JavaScript
mit
aholstenson/miio
7d56f85029af381d27a70d3eec719a3270febe14
src/hooks/verify-token.js
src/hooks/verify-token.js
import jwt from 'jsonwebtoken'; import errors from 'feathers-errors'; /** * Verifies that a JWT token is valid * * @param {Object} options - An options object * @param {String} options.secret - The JWT secret */ export default function(options = {}){ const secret = options.secret; return function(hook) { const token = hook.params.token; if (!token) { return Promise.resolve(hook); } return new Promise(function(resolve, reject){ jwt.verify(token, secret, options, function (error, payload) { if (error) { // Return a 401 if the token has expired or is invalid. return reject(new errors.NotAuthenticated(error)); } // Attach our decoded token payload to the params hook.params.payload = payload; resolve(hook); }); }); }; }
import jwt from 'jsonwebtoken'; import errors from 'feathers-errors'; /** * Verifies that a JWT token is valid * * @param {Object} options - An options object * @param {String} options.secret - The JWT secret */ export default function(options = {}){ const secret = options.secret; if (!secret) { console.log('no secret', options); throw new Error('You need to pass `options.secret` to the verifyToken() hook.'); } return function(hook) { const token = hook.params.token; if (!token) { return Promise.resolve(hook); } return new Promise(function(resolve, reject){ jwt.verify(token, secret, options, function (error, payload) { if (error) { // Return a 401 if the token has expired or is invalid. return reject(new errors.NotAuthenticated(error)); } // Attach our decoded token payload to the params hook.params.payload = payload; resolve(hook); }); }); }; }
Throw an error if you don't pass a secret to verifyToken hook
Throw an error if you don't pass a secret to verifyToken hook
JavaScript
mit
feathersjs/feathers-passport-jwt,feathersjs/feathers-passport-jwt,feathersjs/feathers-authentication,eblin/feathers-authentication,eblin/feathers-authentication,m1ch3lcl/feathers-authentication,m1ch3lcl/feathers-authentication
6b883624c19abad009db96f0d00d1ef84b1defe9
scripts/cd-server.js
scripts/cd-server.js
// Continuous delivery server const { spawn } = require('child_process') const { resolve } = require('path') const { createServer } = require('http') const { parse } = require('qs') const hostname = '127.0.0.1' const port = 80 const server = createServer((req, res) => { const { headers, method, url } = req // When a successful build has happened, kill the process, triggering a restart if (req.method === 'POST' && req.url === '/webhook') { // Send response res.statusCode = 200 res.end() let body = [] req .on('error', err => { console.error(err) }) .on('data', chunk => { body.push(chunk) }) .on('end', () => { body = Buffer.concat(body).toString() const { payload } = parse(body) console.log(payload.result + ' ' + payload.branch) const passed = payload.result == 0 const master = payload.branch == 'master' if (passed && master) { process.exit(0) } }) } res.statusCode = 404 res.end() }).listen(port)
// Continuous delivery server const { spawn } = require('child_process') const { resolve } = require('path') const { createServer } = require('http') const { parse } = require('qs') const hostname = '127.0.0.1' const port = 80 const server = createServer((req, res) => { const { headers, method, url } = req // When a successful build has happened, kill the process, triggering a restart if (req.method === 'POST' && req.url === '/webhook') { // Send response res.statusCode = 200 res.end() let body = [] req .on('error', err => { console.error(err) }) .on('data', chunk => { body.push(chunk) }) .on('end', () => { body = Buffer.concat(body).toString() const { payload } = parse(body) const data = JSON.parse(payload) console.log(data.result + ' ' + data.branch) const passed = data.result == 0 const master = data.branch == 'master' if (passed && master) { process.exit(0) } }) } res.statusCode = 404 res.end() }).listen(port)
Fix parsing bug in CD server.
Fix parsing bug in CD server.
JavaScript
mit
jsonnull/jsonnull.com,jsonnull/jsonnull.com,jsonnull/jsonnull.com
d0be0c668a41dcd07c888a146d09ab57819fe432
server/core/types.js
server/core/types.js
/* @flow */ 'use babel'; export type Post = { title: string, content: string, postCreated : any, postPublished: string, lastUpdated: string, status: string, author: string, tags: Array<string>, generated_keys?: any } export type Author = { name: string, email: string, username: string, password: string, token: string, generated_keys?: any } export type PostCreated = { year: string, month: string, date: string } export type PostDocument = { filename: string, postCreated: PostCreated, compiledContent: string, post: Post }
/* @flow */ 'use babel' export type Post = { title: string, content: string, postCreated : any, postPublished: string, lastUpdated: string, status: string, author: string, tags: Array<string>, generated_keys?: any } export type PostSum = { title: string, status: string, id: string, author: string } export type Author = { name: string, email: string, username: string, password: string, token: string, generated_keys?: any } export type PostCreated = { year: string, month: string, date: string } export type PostDocument = { filename: string, postCreated: PostCreated, compiledContent: string, post: Post }
Add PostSum type. This is post summary for list view
Add PostSum type. This is post summary for list view
JavaScript
mit
junwatu/blogel,junwatu/blogel,junwatu/blogel
b8db7e248edc31bd5231088832feacf35843b73e
app/assets/javascripts/student_profile/main.js
app/assets/javascripts/student_profile/main.js
$(function() { // only run if the correct page if (!($('body').hasClass('students') && $('body').hasClass('show'))) return; // imports var createEl = window.shared.ReactHelpers.createEl; var PageContainer = window.shared.PageContainer; var parseQueryString = window.shared.parseQueryString; // mixpanel analytics MixpanelUtils.registerUser(serializedData.currentEducator); MixpanelUtils.track('PAGE_VISIT', { page_key: 'STUDENT_PROFILE' }); // entry point, reading static bootstrapped data from the page var serializedData = $('#serialized-data').data(); ReactDOM.render(createEl(PageContainer, { nowMomentFn: function() { return moment.utc(); }, serializedData: serializedData, queryParams: parseQueryString(window.location.search) }), document.getElementById('main')); });
$(function() { // only run if the correct page if (!($('body').hasClass('students') && $('body').hasClass('show'))) return; // imports var createEl = window.shared.ReactHelpers.createEl; var PageContainer = window.shared.PageContainer; var parseQueryString = window.shared.parseQueryString; var MixpanelUtils = window.shared.MixpanelUtils; // mixpanel analytics MixpanelUtils.registerUser(serializedData.currentEducator); MixpanelUtils.track('PAGE_VISIT', { page_key: 'STUDENT_PROFILE' }); // entry point, reading static bootstrapped data from the page var serializedData = $('#serialized-data').data(); ReactDOM.render(createEl(PageContainer, { nowMomentFn: function() { return moment.utc(); }, serializedData: serializedData, queryParams: parseQueryString(window.location.search) }), document.getElementById('main')); });
Fix bug in profile page import
Fix bug in profile page import
JavaScript
mit
erose/studentinsights,erose/studentinsights,jhilde/studentinsights,erose/studentinsights,studentinsights/studentinsights,jhilde/studentinsights,studentinsights/studentinsights,studentinsights/studentinsights,jhilde/studentinsights,jhilde/studentinsights,erose/studentinsights,studentinsights/studentinsights
8b6befcd13104e8eb829947d42a843ec648b5296
addon/utils/validators/ember-component.js
addon/utils/validators/ember-component.js
/** * The PropTypes.EmberComponent validator */ import Ember from 'ember' const {typeOf} = Ember import logger from '../logger' export default function (ctx, name, value, def, logErrors, throwErrors) { const isObject = typeOf(value) === 'object' const valid = isObject && Object.keys(value).some((key) => { // NOTE: this is based on internal API and thus could break without warning. return key.indexOf('COMPONENT_CELL') === 0 }) if (!valid && logErrors) { logger.warn(ctx, `Expected property ${name} to be an Ember.Component`, throwErrors) } return valid }
/** * The PropTypes.EmberComponent validator */ import Ember from 'ember' const {typeOf} = Ember import logger from '../logger' export default function (ctx, name, value, def, logErrors, throwErrors) { const isObject = typeOf(value) === 'object' const valid = isObject && Object.keys(value).some((key) => { // NOTE: this is based on internal API and thus could break without warning. return ( key.indexOf('COMPONENT_CELL') === 0 || // Pre Glimmer 2 key.indexOf('COMPONENT DEFINITION') === 0 // Glimmer 2 ) }) if (!valid && logErrors) { logger.warn(ctx, `Expected property ${name} to be an Ember.Component`, throwErrors) } return valid }
Fix EmberComponent prop type for Ember 2.11
Fix EmberComponent prop type for Ember 2.11
JavaScript
mit
ciena-blueplanet/ember-prop-types,sandersky/ember-prop-types,sandersky/ember-prop-types,sandersky/ember-prop-types,ciena-blueplanet/ember-prop-types,ciena-blueplanet/ember-prop-types
0f68aa298d5cc7c2578126456197fe0ce0798db1
build/start.js
build/start.js
require('./doBuild'); require('./server');
var build = require('./build'); build() .catch(function(err) { require('trace'); require('clarify'); console.trace(err); }); require('./server');
Tweak heroku build to put it into production mode
Tweak heroku build to put it into production mode
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
cb755108580ee143b9e74883a2948598473e341d
src/transferring/index.js
src/transferring/index.js
import * as http_data from "./http-data"; import * as urlModule from "url"; const transferrers = {}; function transfer(request) { // url - the resource URI to send a message to // options.method - the method to use for transferring // options.form - the Form API object representing the form data submission // converted to a message body via encoding (see: options.enctype) // options.enctype - the encoding to use to encode form into message body // options.body - an already encoded message body // if both body and form are present, form is ignored if (!request) throw new Error("'request' param is required."); var url = request.url; var options = request.options; if (!url) throw new Error("'request.url' param is required."); var protocol = urlModule.parse(url).protocol; if (!protocol) throw new Error("'request.url' param must have a protocol scheme."); protocol = protocol.replace(":", ""); if (protocol in transferrers === false) throw new Error("No transferrer registered for protocol: " + protocol); var transferrer = transferrers[protocol]; return transferrer(request); } transfer.register = function registerTransferrer(scheme, transferrer) { transferrers[scheme] = transferrer; }; transfer.register("http", http_data.transfer); transfer.register("data", http_data.transfer); export { transfer };
import * as http_data from "./http-data"; import * as urlModule from "url"; function transfer(request) { // url - the resource URI to send a message to // options.method - the method to use for transferring // options.form - the Form API object representing the form data submission // converted to a message body via encoding (see: options.enctype) // options.enctype - the encoding to use to encode form into message body // options.body - an already encoded message body // if both body and form are present, form is ignored if (!request) throw new Error("'request' param is required."); var url = request.url; var options = request.options; if (!url) throw new Error("'request.url' param is required."); var protocol = urlModule.parse(url).protocol; if (!protocol) throw new Error("'request.url' param must have a protocol scheme."); protocol = protocol.replace(":", ""); if (protocol in transfer.registrations === false) throw new Error("No transferrer registered for protocol: " + protocol); var transferrer = transfer.registrations[protocol]; return transferrer(request); } transfer.registrations = {}; transfer.register = function registerTransferrer(protocol, transferrer) { transfer.registrations[protocol] = transferrer; }; transfer.register("http", http_data.transfer); transfer.register("data", http_data.transfer); export { transfer };
Make Transfer Consistent w/ Views
Make Transfer Consistent w/ Views
JavaScript
mit
lynx-json/jsua
5575571bf0dca4f941e87164839605dc6aca0014
js/buttons/delete-button.js
js/buttons/delete-button.js
"use strict"; /*global module, require*/ var modalDialogueFactory = require("./processes/modal-dialogue.js"), commentFactory = require("./accordion-comment.js"), online = { online: true, offline: false }, standalone = { embedded: false, standalone: true }; module.exports = function(store, specifyButton, closeFileMenu) { var modalDialogueProcess = modalDialogueFactory(closeFileMenu); return specifyButton( "Delete", null, function(wasActive, buttonProcess, onProcessEnd) { if (store.getTitle()) { var submit = function() { store.deleteDocument( store.getTitle() ); // ToDo do something with this. // comment.getComment(); dialogue.exit(); }, dialogue = modalDialogueProcess(wasActive, buttonProcess, onProcessEnd, submit), head = dialogue.element.append("h4") .text("Delete '" + store.getTitle() + "'"), comment = commentFactory(dialogue.element), action = dialogue.element.append("div") .classed("dialogue-action", true) .attr("delete-action", true) .on("click", submit) .text("Delete"); return dialogue; } else { return null; } }, { onlineOffline: online, embeddedStandalone: standalone, search: {} } ); };
"use strict"; /*global module, require*/ var modalDialogueFactory = require("./processes/modal-dialogue.js"), commentFactory = require("./accordion-comment.js"), online = { online: true, offline: false }, standalone = { embedded: false, standalone: true }; module.exports = function(store, specifyButton, closeFileMenu) { var modalDialogueProcess = modalDialogueFactory(closeFileMenu); return specifyButton( "Delete", null, function(wasActive, buttonProcess, onProcessEnd) { if (store.getTitle()) { var submit = function() { store.deleteDocument( store.getTitle() ); // ToDo do something with this. // comment.getComment(); dialogue.exit(); }, dialogue = modalDialogueProcess(wasActive, buttonProcess, onProcessEnd, submit), head = dialogue.element.append("h4") .text("Delete '" + store.getTitle() + "'"), comment = commentFactory(dialogue.element), action = dialogue.element.append("div") .classed("dialogue-action", true) .attr("delete-action", true) .on("click", submit) .text("Delete"); return dialogue; } else { return null; } }, { onlineOffline: online, embeddedStandalone: standalone, readWriteSync: { untitled: false, read: false, write: true, sync: true } } ); };
Delete button enabled on the right occasions.
Delete button enabled on the right occasions.
JavaScript
mit
cse-bristol/multiuser-file-menu,cse-bristol/multiuser-file-menu
59db5d86469bf8f474f8a1ab40588d218831c99c
model/lib/data-snapshot/index.js
model/lib/data-snapshot/index.js
// Not to mix with `DataSnapshots` class which is about different thing // (serialized list views updated reactively) // // This one is about snaphots of data made in specific moments of time. // Snaphots are not reactive in any way. They're updated only if given specific moment repeats // for entity it refers to. // e.g. We want to store a state of submitted dataForms at business process at its submission // After it's stored it's not updated (and safe against any external changes like model changes) // Just in case of re-submissions (e.g. return of file from sent back case) the snapshot is // overwritten with regenerated value 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs') , extendBase = require('../../base'); module.exports = memoize(function (db) { extendBase(ensureDb(db)); return db.Object.extend('DataSnapshot', { jsonString: { type: db.String } // 'resolved' property evaluation is configured in ./resolve.js }); }, { normalizer: require('memoizee/normalizers/get-1')() });
// Not to mix with `DataSnapshots` class which is about different thing // (serialized list views updated reactively) // // This one is about snaphots of data made in specific moments of time. // Snaphots are not reactive in any way. They're updated only if given specific moment repeats // for entity it refers to. // e.g. We want to store a state of submitted dataForms at business process at its submission // After it's stored it's not updated (and safe against any external changes like model changes) // Just in case of re-submissions (e.g. return of file from sent back case) the snapshot is // overwritten with regenerated value 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs') , extendBase = require('../../base'); module.exports = memoize(function (db) { extendBase(ensureDb(db)); return db.Object.extend('DataSnapshot', { jsonString: { type: db.String }, // Generates snapshot (if it was not generated already) generate: { type: db.Function, value: function (ignore) { if (!this.jsonString) this.regenerate(); } }, // Generates snapshot (overwrites old snapshot if it exist) regenerate: { type: db.Function, value: function (ignore) { this.jsonString = JSON.stringify(this.owner.toJSON()); } } }); }, { normalizer: require('memoizee/normalizers/get-1')() });
Introduce `generate` and `regenerate` methods
Introduce `generate` and `regenerate` methods
JavaScript
mit
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
425470a41a20f416fb05c575a443ffffb9aac71d
test/load-json-spec.js
test/load-json-spec.js
/* global describe, it */ import assert from 'assert'; import {KATAS_URL, URL_PREFIX} from '../src/config.js'; import GroupedKata from '../src/grouped-kata.js'; describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { const loadRemoteFileStub = (url, onLoaded) => { let validData = JSON.stringify({groups: {}}); onLoaded(null, validData); }; function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(loadRemoteFileStub, KATAS_URL).load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { const loadRemoteFileStub = (url, onLoaded) => { onLoaded(new Error('')); }; function onError(err) { assert.ok(err); done(); } new GroupedKata(loadRemoteFileStub, '').load(onError); }); it('for invalid data', function(done) { const invalidData = JSON.stringify({propertyGroupsMissing:{}}); const loadRemoteFileStub = (url, onLoaded) => { onLoaded(null, invalidData); }; function onError(err) { assert.ok(err); done(); } new GroupedKata(loadRemoteFileStub, '').load(onError); }); }); });
/* global describe, it */ import assert from 'assert'; import GroupedKata from '../src/grouped-kata.js'; function remoteFileLoaderWhichReturnsGivenData(data) { return (url, onLoaded) => { onLoaded(null, data); }; } function remoteFileLoaderWhichReturnsError(error) { return (url, onLoaded) => { onLoaded(error); }; } describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } const validData = JSON.stringify({groups: {}}); const loaderStub = remoteFileLoaderWhichReturnsGivenData(validData); new GroupedKata(loaderStub, 'irrelevant url').load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } const loaderStub = remoteFileLoaderWhichReturnsError(new Error('')); new GroupedKata(loaderStub, 'irrelevant url').load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } const invalidData = JSON.stringify({propertyGroupsMissing:{}}); const loaderStub = remoteFileLoaderWhichReturnsGivenData(invalidData); new GroupedKata(loaderStub, 'irrelevant url').load(onError); }); }); });
Refactor duplication out of tests.
Refactor duplication out of tests.
JavaScript
mit
wolframkriesing/es6-react-workshop,wolframkriesing/es6-react-workshop
a1d6637ecd4f9d8c0745d3ea59ec83742e371c24
src/plugins/appVersion.js
src/plugins/appVersion.js
// install : cordova plugin add https://github.com/whiteoctober/cordova-plugin-app-version.git // link : https://github.com/whiteoctober/cordova-plugin-app-version angular.module('ngCordova.plugins.appVersion', []) .factory('$cordovaAppVersion', ['$q', function ($q) { return { getAppVersion: function () { var q = $q.defer(); cordova.getAppVersion(function (version) { q.resolve(version); }); return q.promise; } }; }]);
// install : cordova plugin add https://github.com/whiteoctober/cordova-plugin-app-version.git // link : https://github.com/whiteoctober/cordova-plugin-app-version angular.module('ngCordova.plugins.appVersion', []) .factory('$cordovaAppVersion', ['$q', function ($q) { return { getVersionNumber: function () { var q = $q.defer(); cordova.getAppVersion.getVersionNumber(function (version) { q.resolve(version); }); return q.promise; }, getVersionCode: function () { var q = $q.defer(); cordova.getAppVersion.getVersionCode(function (code) { q.resolve(code); }); return q.promise; } }; }]);
Update due to the plugin split into two functions getAppVersion.getVersionNumber() and getAppVersion.getVersionCode() to return build number
Update due to the plugin split into two functions getAppVersion.getVersionNumber() and getAppVersion.getVersionCode() to return build number
JavaScript
mit
listrophy/ng-cordova,dangerfarms/ng-cordova,sesubash/ng-cordova,driftyco/ng-cordova,justinwp/ng-cordova,DavidePastore/ng-cordova,cihadhoruzoglu/ng-cordova,5amfung/ng-cordova,candril/ng-cordova,omefire/ng-cordova,alanquigley/ng-cordova,Jewelbots/ng-cordova,beauby/ng-cordova,GreatAnubis/ng-cordova,Freundschaft/ng-cordova,andrew168/ng-cordova,HereSinceres/ng-cordova,nraboy/ng-cordova,omefire/ng-cordova,guaerguagua/ng-cordova,brunogonncalves/ng-cordova,b-cuts/ng-cordova,boboldehampsink/ng-cordova,dangerfarms/ng-cordova,honger05/ng-cordova,GreatAnubis/ng-cordova,fwitzke/ng-cordova,SebastianRolf/ng-cordova,beauby/ng-cordova,ralic/ng-cordova,b-cuts/ng-cordova,edewit/ng-cordova,promactkaran/ng-cordova,sesubash/ng-cordova,gortok/ng-cordova,Jeremy017/ng-cordova,nraboy/ng-cordova,scripterkaran/ng-cordova,fxckdead/ng-cordova,jamalx31/ng-cordova,ralic/ng-cordova,andrew168/ng-cordova,j0k3r/ng-cordova,jskrzypek/ng-cordova,j0k3r/ng-cordova,Sharinglabs/ng-cordova,johnli388/ng-cordova,honger05/ng-cordova,Jewelbots/ng-cordova,5amfung/ng-cordova,selimg/ng-cordova,alanquigley/ng-cordova,boboldehampsink/ng-cordova,brunogonncalves/ng-cordova,jarbitlira/ng-cordova,sesubash/ng-cordova,edewit/ng-cordova,candril/ng-cordova,fxckdead/ng-cordova,kidush/ng-cordova,kublaj/ng-cordova,gortok/ng-cordova,DavidePastore/ng-cordova,omefire/ng-cordova,glustful/ng-cordova,SidneyS/ng-cordova,mattlewis92/ng-cordova,toddhalfpenny/ng-cordova,moez-sadok/ng-cordova,moez-sadok/ng-cordova,matheusrocha89/ng-cordova,SidneyS/ng-cordova,toddhalfpenny/ng-cordova,b-cuts/ng-cordova,scripterkaran/ng-cordova,brunogonncalves/ng-cordova,alanquigley/ng-cordova,athiradandira/ng-cordova,listrophy/ng-cordova,kidush/ng-cordova,andreground/ng-cordova,fxckdead/ng-cordova,saschalink/ng-cordova,scripterkaran/ng-cordova,promactkaran/ng-cordova,Tobiaswk/ng-cordova,toddhalfpenny/ng-cordova,j0k3r/ng-cordova,dangerfarms/ng-cordova,lulee007/ng-cordova,jarbitlira/ng-cordova,Jeremy017/ng-cordova,kidush/ng-cordova,guaerguagua/ng-cordova,lukemartin/ng-cordova,DavidePastore/ng-cordova,boboldehampsink/ng-cordova,5amfung/ng-cordova,kublaj/ng-cordova,fwitzke/ng-cordova,guaerguagua/ng-cordova,kublaj/ng-cordova,Sharinglabs/ng-cordova,jamalx31/ng-cordova,HereSinceres/ng-cordova,justinwp/ng-cordova,jason-engage/ng-cordova,candril/ng-cordova,dlermen12/ng-cordova,saschalink/ng-cordova,moez-sadok/ng-cordova,microlv/ng-cordova,thomasbabuj/ng-cordova,blocktrail/ng-cordova,andrew168/ng-cordova,jason-engage/ng-cordova,jamalx31/ng-cordova,Jewelbots/ng-cordova,1337/ng-cordova,nraboy/ng-cordova,jason-engage/ng-cordova,edewit/ng-cordova,blocktrail/ng-cordova,promactkaran/ng-cordova,johnli388/ng-cordova,microlv/ng-cordova,Sharinglabs/ng-cordova,glustful/ng-cordova,saschalink/ng-cordova,glustful/ng-cordova,SebastianRolf/ng-cordova,athiradandira/ng-cordova,lulee007/ng-cordova,matheusrocha89/ng-cordova,honger05/ng-cordova,selimg/ng-cordova,driftyco/ng-cordova,lulee007/ng-cordova,jarbitlira/ng-cordova,gortok/ng-cordova,athiradandira/ng-cordova,Freundschaft/ng-cordova,lukemartin/ng-cordova,GreatAnubis/ng-cordova,microlv/ng-cordova,jskrzypek/ng-cordova,1337/ng-cordova,blocktrail/ng-cordova,thomasbabuj/ng-cordova,johnli388/ng-cordova,SebastianRolf/ng-cordova,jskrzypek/ng-cordova,matheusrocha89/ng-cordova,dlermen12/ng-cordova,dlermen12/ng-cordova,cihadhoruzoglu/ng-cordova,fwitzke/ng-cordova,lukemartin/ng-cordova,mattlewis92/ng-cordova,andreground/ng-cordova,1337/ng-cordova,Freundschaft/ng-cordova,driftyco/ng-cordova,Jeremy017/ng-cordova,mattlewis92/ng-cordova,SidneyS/ng-cordova,listrophy/ng-cordova,beauby/ng-cordova,thomasbabuj/ng-cordova,selimg/ng-cordova,ralic/ng-cordova,justinwp/ng-cordova,Tobiaswk/ng-cordova,Tobiaswk/ng-cordova,andreground/ng-cordova,cihadhoruzoglu/ng-cordova,HereSinceres/ng-cordova
bea6c3a94e10aafefba91fd791dece9a26a1fe13
src/mist/io/static/js/app/views/image_list_item.js
src/mist/io/static/js/app/views/image_list_item.js
define('app/views/image_list_item', [ 'text!app/templates/image_list_item.html','ember'], /** * * Image List Item View * * @returns Class */ function(image_list_item_html) { return Ember.View.extend({ tagName:'li', starImage: function() { var payload = { 'action': 'star' }; var backend_id = this.image.backend.id var image_id = this.image.id; $.ajax({ url: '/backends/' + backend_id + '/images/' + image_id, type: "POST", data: JSON.stringify(payload), contentType: "application/json", headers: { "cache-control": "no-cache" }, dataType: "json" }); }, didInsertElement: function(){ $('#images-list').listview('refresh'); try{ $('#images-list .ember-checkbox').checkboxradio(); } catch(e){} }, launchImage: function(){ var AddView = Mist.MachineAddView.create(); AddView.selectProvider(this.image.backend); AddView.selectImage(this.image); $('#images .dialog-add').panel('open'); }, template: Ember.Handlebars.compile(image_list_item_html), }); } );
define('app/views/image_list_item', [ 'text!app/templates/image_list_item.html','ember'], /** * * Image List Item View * * @returns Class */ function(image_list_item_html) { return Ember.View.extend({ tagName:'li', starImage: function() { var payload = { 'action': 'star' }; var backend_id = this.image.backend.id var image_id = this.image.id; var that = this; $.ajax({ url: '/backends/' + backend_id + '/images/' + image_id, type: "POST", data: JSON.stringify(payload), contentType: "application/json", headers: { "cache-control": "no-cache" }, dataType: "json", success: function (){ var backend = Mist.backendsController.getBackendById(backend_id); if (backend.images.content.indexOf(that.image) == -1) { if (image.star == false) { backend.images.content.unshiftObject(that.image); } } } }); }, didInsertElement: function(){ $('#images-list').listview('refresh'); try{ $('#images-list .ember-checkbox').checkboxradio(); } catch(e){} }, launchImage: function(){ var AddView = Mist.MachineAddView.create(); AddView.selectProvider(this.image.backend); AddView.selectImage(this.image); $('#images .dialog-add').panel('open'); }, template: Ember.Handlebars.compile(image_list_item_html), }); } );
Fix star image from advanced search in javascript
Fix star image from advanced search in javascript
JavaScript
agpl-3.0
afivos/mist.io,munkiat/mist.io,afivos/mist.io,munkiat/mist.io,afivos/mist.io,munkiat/mist.io,zBMNForks/mist.io,Lao-liu/mist.io,munkiat/mist.io,Lao-liu/mist.io,kelonye/mist.io,zBMNForks/mist.io,DimensionDataCBUSydney/mist.io,johnnyWalnut/mist.io,kelonye/mist.io,zBMNForks/mist.io,johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io,kelonye/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io
e7da62df0ace6f30593df7d18ae983cb7e44c778
test/test-creation.js
test/test-creation.js
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('browserify generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('browserify:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig' ]; helpers.mockPrompt(this.app, { 'framework': 'foundation', 'modernizr': true, 'jade': true }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('browserify generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('browserify:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig' ]; helpers.mockPrompt(this.app, { 'framework': ['foundation'], 'compiler': ['libsass'], 'foundation': true, 'modernizr': true, 'jade': true, 'libsass': true }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
Update tests to reflect addition of list prompts and compiler list in generator.
Update tests to reflect addition of list prompts and compiler list in generator.
JavaScript
mit
dlmoody/generator-browserify,vincentmac/generator-browserify,dlmoody/generator-browserify
0bb4c1bd060627ddeb098f107fc7ec5d8cddbb0d
core/client/assets/lib/touch-editor.js
core/client/assets/lib/touch-editor.js
var createTouchEditor = function createTouchEditor() { var noop = function () {}, TouchEditor; TouchEditor = function (el, options) { /*jshint unused:false*/ this.textarea = el; this.win = { document : this.textarea }; this.ready = true; this.wrapping = document.createElement('div'); var textareaParent = this.textarea.parentNode; this.wrapping.appendChild(this.textarea); textareaParent.appendChild(this.wrapping); this.textarea.style.opacity = 1; }; TouchEditor.prototype = { setOption: function (type, handler) { if (type === 'onChange') { $(this.textarea).change(handler); } }, eachLine: function () { return []; }, getValue: function () { return this.textarea.value; }, setValue: function (code) { this.textarea.value = code; }, focus: noop, getCursor: function () { return { line: 0, ch: 0 }; }, setCursor: noop, currentLine: function () { return 0; }, cursorPosition: function () { return { character: 0 }; }, addMarkdown: noop, nthLine: noop, refresh: noop, selectLines: noop, on: noop }; return TouchEditor; }; export default createTouchEditor;
var createTouchEditor = function createTouchEditor() { var noop = function () {}, TouchEditor; TouchEditor = function (el, options) { /*jshint unused:false*/ this.textarea = el; this.win = { document : this.textarea }; this.ready = true; this.wrapping = document.createElement('div'); var textareaParent = this.textarea.parentNode; this.wrapping.appendChild(this.textarea); textareaParent.appendChild(this.wrapping); this.textarea.style.opacity = 1; }; TouchEditor.prototype = { setOption: function (type, handler) { if (type === 'onChange') { $(this.textarea).change(handler); } }, eachLine: function () { return []; }, getValue: function () { return this.textarea.value; }, setValue: function (code) { this.textarea.value = code; }, focus: noop, getCursor: function () { return { line: 0, ch: 0 }; }, setCursor: noop, currentLine: function () { return 0; }, cursorPosition: function () { return { character: 0 }; }, addMarkdown: noop, nthLine: noop, refresh: noop, selectLines: noop, on: noop, off: noop }; return TouchEditor; }; export default createTouchEditor;
Add off as a noop function to touch editor.
Add off as a noop function to touch editor. Closes #3107
JavaScript
mit
tandrewnichols/ghost,katiefenn/Ghost,situkangsayur/Ghost,anijap/PhotoGhost,tmp-reg/Ghost,ericbenson/GhostAzureSetup,rollokb/Ghost,Rovak/Ghost,aschmoe/jesse-ghost-app,JonSmith/Ghost,blankmaker/Ghost,jparyani/GhostSS,dai-shi/Ghost,dymx101/Ghost,ErisDS/Ghost,Smile42RU/Ghost,gabfssilva/Ghost,virtuallyearthed/Ghost,Feitianyuan/Ghost,jgladch/taskworksource,dYale/blog,lethalbrains/Ghost,tadityar/Ghost,davidenq/Ghost-Blog,carlosmtx/Ghost,cqricky/Ghost,jiachenning/Ghost,omaracrystal/Ghost,epicmiller/pages,sceltoas/Ghost,chevex/undoctrinate,madole/diverse-learners,sajmoon/Ghost,vainglori0us/urban-fortnight,Shauky/Ghost,skleung/blog,vloom/blog,sifatsultan/js-ghost,kmeurer/Ghost,mhhf/ghost-latex,djensen47/Ghost,tidyui/Ghost,manishchhabra/Ghost,dbalders/Ghost,load11/ghost,neynah/GhostSS,dylanchernick/ghostblog,krahman/Ghost,shrimpy/Ghost,mlabieniec/ghost-env,letsjustfixit/Ghost,ErisDS/Ghost,nakamuraapp/new-ghost,sebgie/Ghost,devleague/uber-hackathon,Kikobeats/Ghost,ThorstenHans/Ghost,ghostchina/Ghost.zh,singular78/Ghost,wangjun/Ghost,mnitchie/Ghost,YY030913/Ghost,letsjustfixit/Ghost,optikalefx/Ghost,load11/ghost,Brunation11/Ghost,manishchhabra/Ghost,duyetdev/islab,sifatsultan/js-ghost,AlexKVal/Ghost,kortemy/Ghost,johnnymitch/Ghost,Alxandr/Blog,JonSmith/Ghost,yangli1990/Ghost,thehogfather/Ghost,smaty1/Ghost,phillipalexander/Ghost,NovaDevelopGroup/Academy,ckousik/Ghost,bosung90/Ghost,ryanbrunner/crafters,rouanw/Ghost,panezhang/Ghost,benstoltz/Ghost,singular78/Ghost,FredericBernardo/Ghost,uploadcare/uploadcare-ghost-demo,rollokb/Ghost,zackslash/Ghost,NovaDevelopGroup/Academy,davidenq/Ghost-Blog,mlabieniec/ghost-env,ineitzke/Ghost,jaswilli/Ghost,lethalbrains/Ghost,Loyalsoldier/Ghost,bsansouci/Ghost,cncodog/Ghost-zh-codog,diancloud/Ghost,carlyledavis/Ghost,akveo/akveo-blog,kortemy/Ghost,SkynetInc/steam,axross/ghost,ManRueda/Ghost,beautyOfProgram/Ghost,daihuaye/Ghost,kaiqigong/Ghost,klinker-apps/ghost,Jai-Chaudhary/Ghost,pathayes/FoodBlog,pollbox/ghostblog,diogogmt/Ghost,v3rt1go/Ghost,Netazoic/bad-gateway,kwangkim/Ghost,schematical/Ghost,leonli/ghost,ManRueda/Ghost,wallmarkets/Ghost,dbalders/Ghost,javimolla/Ghost,mohanambati/Ghost,AlexKVal/Ghost,BlueHatbRit/Ghost,hilerchyn/Ghost,Alxandr/Blog,ivantedja/ghost,ASwitlyk/Ghost,netputer/Ghost,tyrikio/Ghost,scopevale/wethepeopleweb.org,lf2941270/Ghost,liftup/ghost,r14r/fork_nodejs_ghost,trunk-studio/Ghost,allspiritseve/mindlikewater,ITJesse/Ghost-zh,duyetdev/islab,e10/Ghost,francisco-filho/Ghost,devleague/uber-hackathon,JohnONolan/Ghost,Japh/shortcoffee,praveenscience/Ghost,nneko/Ghost,bitjson/Ghost,camilodelvasto/herokughost,bisoe/Ghost,kmeurer/Ghost,dgem/Ghost,rchrd2/Ghost,jiachenning/Ghost,beautyOfProgram/Ghost,praveenscience/Ghost,edsadr/Ghost,diancloud/Ghost,tidyui/Ghost,jomofrodo/ccb-ghost,kaychaks/kaushikc.org,flomotlik/Ghost,novaugust/Ghost,darvelo/Ghost,UnbounDev/Ghost,Alxandr/Blog,dbalders/Ghost,cysys/ghost-openshift,lowkeyfred/Ghost,mdbw/ghost,jaswilli/Ghost,qdk0901/Ghost,bosung90/Ghost,lukekhamilton/Ghost,dqj/Ghost,MadeOnMars/Ghost,sankumsek/Ghost-ashram,jeonghwan-kim/Ghost,stridespace/Ghost,chris-yoon90/Ghost,lukw00/Ghost,kaychaks/kaushikc.org,sergeylukin/Ghost,telco2011/Ghost,sergeylukin/Ghost,bastianbin/Ghost,SachaG/bjjbot-blog,ineitzke/Ghost,cqricky/Ghost,olsio/Ghost,jparyani/GhostSS,IbrahimAmin/Ghost,NamedGod/Ghost,thehogfather/Ghost,rito/Ghost,UnbounDev/Ghost,madole/diverse-learners,gcamana/Ghost,pbevin/Ghost,cobbspur/Ghost,ddeveloperr/Ghost,greenboxindonesia/Ghost,Gargol/Ghost,wangjun/Ghost,kevinansfield/Ghost,zackslash/Ghost,disordinary/Ghost,Kaenn/Ghost,wemakeweb/Ghost,handcode7/Ghost,jorgegilmoreira/ghost,barbastan/Ghost,katrotz/blog.katrotz.space,dymx101/Ghost,e10/Ghost,panezhang/Ghost,thomasalrin/Ghost,ManRueda/manrueda-blog,GroupxDev/javaPress,zhiyishou/Ghost,jgillich/Ghost,sfpgmr/Ghost,tmp-reg/Ghost,cwonrails/Ghost,bastianbin/Ghost,leonli/ghost,theonlypat/Ghost,PDXIII/Ghost-FormMailer,makapen/Ghost,yanntech/Ghost,rameshponnada/Ghost,bitjson/Ghost,jgillich/Ghost,denzelwamburu/denzel.xyz,johnnymitch/Ghost,psychobunny/Ghost,makapen/Ghost,dgem/Ghost,achimos/ghost_as,Jai-Chaudhary/Ghost,Yarov/yarov,flpms/ghost-ad,jacostag/Ghost,TryGhost/Ghost,Azzurrio/Ghost,dqj/Ghost,zhiyishou/Ghost,Yarov/yarov,woodyrew/Ghost,Bunk/Ghost,ivanoats/ivanstorck.com,rizkyario/Ghost,bsansouci/Ghost,cysys/ghost-openshift,GroupxDev/javaPress,axross/ghost,ThorstenHans/Ghost,andrewconnell/Ghost,wemakeweb/Ghost,jacostag/Ghost,javorszky/Ghost,ghostchina/Ghost-zh,Dnlyc/Ghost,sebgie/Ghost,situkangsayur/Ghost,bbmepic/Ghost,diogogmt/Ghost,metadevfoundation/Ghost,atandon/Ghost,mattchupp/blog,eduardojmatos/eduardomatos.me,skleung/blog,Polyrhythm/dolce,NikolaiIvanov/Ghost,k2byew/Ghost,yangli1990/Ghost,disordinary/Ghost,acburdine/Ghost,Kikobeats/Ghost,skmezanul/Ghost,tadityar/Ghost,lukekhamilton/Ghost,sangcu/Ghost,pathayes/FoodBlog,notno/Ghost,olsio/Ghost,Netazoic/bad-gateway,sebgie/Ghost,ManRueda/manrueda-blog,melissaroman/ghost-blog,ITJesse/Ghost-zh,no1lov3sme/Ghost,UsmanJ/Ghost,NodeJSBarenko/Ghost,SachaG/bjjbot-blog,JohnONolan/Ghost,davidenq/Ghost-Blog,Romdeau/Ghost,johngeorgewright/blog.j-g-w.info,Brunation11/Ghost,IbrahimAmin/Ghost,zeropaper/Ghost,claudiordgz/Ghost,DesenTao/Ghost,vainglori0us/urban-fortnight,theonlypat/Ghost,karmakaze/Ghost,PaulBGD/Ghost-Plus,JohnONolan/Ghost,NovaDevelopGroup/Academy,lukaszklis/Ghost,mlabieniec/ghost-env,lanffy/Ghost,k2byew/Ghost,camilodelvasto/herokughost,icowan/Ghost,v3rt1go/Ghost,imjerrybao/Ghost,uniqname/everydaydelicious,pensierinmusica/Ghost,adam-paterson/blog,tksander/Ghost,codeincarnate/Ghost,PeterCxy/Ghost,ngosinafrica/SiteForNGOs,kolorahl/Ghost,DesenTao/Ghost,Rovak/Ghost,javorszky/Ghost,jomahoney/Ghost,syaiful6/Ghost,mdbw/ghost,carlosmtx/Ghost,kortemy/Ghost,cwonrails/Ghost,kaiqigong/Ghost,bigertech/Ghost,rafaelstz/Ghost,gleneivey/Ghost,pensierinmusica/Ghost,etdev/blog,rito/Ghost,tanbo800/Ghost,weareleka/blog,wallmarkets/Ghost,augbog/Ghost,syaiful6/Ghost,morficus/Ghost,no1lov3sme/Ghost,epicmiller/pages,sceltoas/Ghost,schneidmaster/theventriloquist.us,Trendy/Ghost,RoopaS/demo-intern,ballPointPenguin/Ghost,llv22/Ghost,RufusMbugua/TheoryOfACoder,vishnuharidas/Ghost,laispace/laiblog,petersucks/blog,pedroha/Ghost,daimaqiao/Ghost-Bridge,tksander/Ghost,Kaenn/Ghost,allanjsx/Ghost,kolorahl/Ghost,KnowLoading/Ghost,hnq90/Ghost,etanxing/Ghost,cicorias/Ghost,dggr/Ghost-sr,achimos/ghost_as,hoxoa/Ghost,ashishapy/ghostpy,ananthhh/Ghost,icowan/Ghost,Azzurrio/Ghost,laispace/laiblog,Elektro1776/javaPress,jiangjian-zh/Ghost,atandon/Ghost,julianromera/Ghost,JonathanZWhite/Ghost,telco2011/Ghost,TryGhost/Ghost,aroneiermann/GhostJade,arvidsvensson/Ghost,anijap/PhotoGhost,ghostchina/Ghost.zh,ClarkGH/Ghost,jorgegilmoreira/ghost,etdev/blog,riyadhalnur/Ghost,lanffy/Ghost,Japh/Ghost,ckousik/Ghost,hilerchyn/Ghost,djensen47/Ghost,omaracrystal/Ghost,Xibao-Lv/Ghost,Feitianyuan/Ghost,STANAPO/Ghost,etanxing/Ghost,devleague/uber-hackathon,javimolla/Ghost,mattchupp/blog,ryanbrunner/crafters,wspandihai/Ghost,leninhasda/Ghost,mnitchie/Ghost,allanjsx/Ghost,telco2011/Ghost,KnowLoading/Ghost,gabfssilva/Ghost,delgermurun/Ghost,jin/Ghost,camilodelvasto/localghost,lf2941270/Ghost,notno/Ghost,InnoD-WebTier/hardboiled_ghost,cicorias/Ghost,cncodog/Ghost-zh-codog,jamesslock/Ghost,exsodus3249/Ghost,vloom/blog,mohanambati/Ghost,skmezanul/Ghost,bisoe/Ghost,ASwitlyk/Ghost,MadeOnMars/Ghost,hoxoa/Ghost,PDXIII/Ghost-FormMailer,riyadhalnur/Ghost,codeincarnate/Ghost,ladislas/ghost,TryGhost/Ghost,Klaudit/Ghost,Coding-House/Ghost,nmukh/Ghost,rizkyario/Ghost,schematical/Ghost,novaugust/Ghost,BayPhillips/Ghost,Kaenn/Ghost,veyo-care/Ghost,benstoltz/Ghost,morficus/Ghost,alecho/Ghost,GarrethDottin/Habits-Design,Netazoic/bad-gateway,ghostchina/Ghost-zh,klinker-apps/ghost,julianromera/Ghost,sfpgmr/Ghost,thinq4yourself/Unmistakable-Blog,rchrd2/Ghost,obsoleted/Ghost,kevinansfield/Ghost,BayPhillips/Ghost,psychobunny/Ghost,aschmoe/jesse-ghost-app,ericbenson/GhostAzureSetup,smedrano/Ghost,akveo/akveo-blog,andrewconnell/Ghost,phillipalexander/Ghost,yundt/seisenpenji,jiangjian-zh/Ghost,acburdine/Ghost,JulienBrks/Ghost,pedroha/Ghost,cysys/ghost-openshift,rameshponnada/Ghost,augbog/Ghost,arvidsvensson/Ghost,YY030913/Ghost,smedrano/Ghost,stridespace/Ghost,zeropaper/Ghost,hnarayanan/narayanan.co,alexandrachifor/Ghost,llv22/Ghost,VillainyStudios/Ghost,VillainyStudios/Ghost,prosenjit-itobuz/Ghost,Aaron1992/Ghost,PaulBGD/Ghost-Plus,netputer/Ghost,obsoleted/Ghost,Japh/shortcoffee,edurangel/Ghost,pbevin/Ghost,rafaelstz/Ghost,GroupxDev/javaPress,FredericBernardo/Ghost,rmoorman/Ghost,pollbox/ghostblog,ballPointPenguin/Ghost,sunh3/Ghost,RufusMbugua/TheoryOfACoder,dai-shi/Ghost,r1N0Xmk2/Ghost,mttschltz/ghostblog,ryansukale/ux.ryansukale.com,jeonghwan-kim/Ghost,exsodus3249/Ghost,lcamacho/Ghost,flomotlik/Ghost,Bunk/Ghost,r14r/fork_nodejs_ghost,yanntech/Ghost,dggr/Ghost-sr,neynah/GhostSS,vainglori0us/urban-fortnight,hyokosdeveloper/Ghost,janvt/Ghost,jaguerra/Ghost,camilodelvasto/localghost,flpms/ghost-ad,GarrethDottin/Habits-Design,PepijnSenders/whatsontheotherside,fredeerock/atlabghost,melissaroman/ghost-blog,jparyani/GhostSS,veyo-care/Ghost,edurangel/Ghost,thinq4yourself/Unmistakable-Blog,mtvillwock/Ghost,jomahoney/Ghost,ManRueda/Ghost,jomofrodo/ccb-ghost,lukaszklis/Ghost,NikolaiIvanov/Ghost,Trendy/Ghost,ManRueda/manrueda-blog,Romdeau/Ghost,barbastan/Ghost,mikecastro26/ghost-custom,smaty1/Ghost,novaugust/Ghost,imjerrybao/Ghost,AnthonyCorrado/Ghost,mohanambati/Ghost,hnarayanan/narayanan.co,ignasbernotas/nullifer,dYale/blog,petersucks/blog,ananthhh/Ghost,mayconxhh/Ghost,Elektro1776/javaPress,ClarkGH/Ghost,singular78/Ghost,mttschltz/ghostblog,influitive/crafters,cwonrails/Ghost,katrotz/blog.katrotz.space,nmukh/Ghost,jin/Ghost,rizkyario/Ghost,Japh/Ghost,hnq90/Ghost,denzelwamburu/denzel.xyz,zumobi/Ghost,rmoorman/Ghost,rouanw/Ghost,PepijnSenders/whatsontheotherside,InnoD-WebTier/hardboiled_ghost,wspandihai/Ghost,daimaqiao/Ghost-Bridge,claudiordgz/Ghost,ignasbernotas/nullifer,qdk0901/Ghost,PeterCxy/Ghost,dggr/Ghost-sr,AileenCGN/Ghost,ErisDS/Ghost,Remchi/Ghost,daimaqiao/Ghost-Bridge,greyhwndz/Ghost,delgermurun/Ghost,memezilla/Ghost,tanbo800/Ghost,dylanchernick/ghostblog,uploadcare/uploadcare-ghost-demo,tuan/Ghost,xiongjungit/Ghost,InnoD-WebTier/hardboiled_ghost,cncodog/Ghost-zh-codog,trunk-studio/Ghost,alecho/Ghost,lowkeyfred/Ghost,ashishapy/ghostpy,karmakaze/Ghost,jaguerra/Ghost,ryansukale/ux.ryansukale.com,influitive/crafters,bbmepic/Ghost,handcode7/Ghost,mayconxhh/Ghost,allanjsx/Ghost,gleneivey/Ghost,davidmenger/nodejsfan,Smile42RU/Ghost,memezilla/Ghost,letsjustfixit/Ghost,NamedGod/Ghost,Elektro1776/javaPress,kwangkim/Ghost,Sebastian1011/Ghost,ddeveloperr/Ghost,ygbhf/Ghost,leninhasda/Ghost,laispace/laiblog,gcamana/Ghost,tyrikio/Ghost,xiongjungit/Ghost,SkynetInc/steam,adam-paterson/blog,chris-yoon90/Ghost,MrMaksimize/sdg1,ygbhf/Ghost,francisco-filho/Ghost,leonli/ghost,blankmaker/Ghost,Sebastian1011/Ghost,Xibao-Lv/Ghost,ljhsai/Ghost,JulienBrks/Ghost,sunh3/Ghost,Remchi/Ghost,velimir0xff/Ghost,yundt/seisenpenji,developer-prosenjit/Ghost,neynah/GhostSS,lukw00/Ghost,weareleka/blog,carlyledavis/Ghost,developer-prosenjit/Ghost,woodyrew/Ghost,patterncoder/patterncoder,fredeerock/atlabghost,kevinansfield/Ghost,floofydoug/Ghost,virtuallyearthed/Ghost,jomofrodo/ccb-ghost,darvelo/Ghost,floofydoug/Ghost,tchapi/igneet-blog,Netazoic/bad-gateway,sajmoon/Ghost,sangcu/Ghost,kmeurer/GhostAzureSetup,Kikobeats/Ghost,UsmanJ/Ghost,thomasalrin/Ghost,velimir0xff/Ghost,aroneiermann/GhostJade,jorgegilmoreira/ghost,Klaudit/Ghost,TribeMedia/Ghost,metadevfoundation/Ghost,ivanoats/ivanstorck.com,mhhf/ghost-latex,greenboxindonesia/Ghost,johngeorgewright/blog.j-g-w.info,TribeMedia/Ghost,allspiritseve/mindlikewater,liftup/ghost,jamesslock/Ghost,aexmachina/blog-old,tandrewnichols/ghost,mtvillwock/Ghost,prosenjit-itobuz/Ghost,patterncoder/patterncoder,r1N0Xmk2/Ghost,LeandroNascimento/Ghost,AnthonyCorrado/Ghost,ljhsai/Ghost,trepafi/ghost-base,Gargol/Ghost,stridespace/Ghost,Dnlyc/Ghost,BlueHatbRit/Ghost,shannonshsu/Ghost,zumobi/Ghost,ladislas/ghost,LeandroNascimento/Ghost,acburdine/Ghost,Loyalsoldier/Ghost,janvt/Ghost,patrickdbakke/ghost-spa,JonathanZWhite/Ghost,schneidmaster/theventriloquist.us,optikalefx/Ghost,hyokosdeveloper/Ghost,ngosinafrica/SiteForNGOs,nneko/Ghost,edsadr/Ghost,ghostchina/website,Coding-House/Ghost,greyhwndz/Ghost,shrimpy/Ghost,freele/ghost,STANAPO/Ghost,shannonshsu/Ghost,daihuaye/Ghost,davidmenger/nodejsfan
39db65de05c816848c07bfbc9b3562d590a34521
scripts/assign-env-vars.js
scripts/assign-env-vars.js
// Used to assign stage-specific env vars in our CI setup // to the env var names used in app code. // All env vars we want to pick up from the CI environment. const envVars = [ 'NODE_ENV', 'AWS_REGION', // AWS Cognito 'COGNITO_REGION', 'COGNITO_IDENTITYPOOLID', 'COGNITO_USERPOOLID', 'COGNITO_CLIENTID', // Web app 'PUBLIC_PATH', 'WEB_HOST', 'WEB_PORT', // GraphQL 'TABLE_NAME_APPENDIX', 'GRAPHQL_PORT', // Endpoints 'GRAPHQL_ENDPOINT', 'DYNAMODB_ENDPOINT', 'S3_ENDPOINT' // Secrets ] // Expect one argument, the stage name. const assignEnvVars = function (stageName) { // Using the name of the stage, assign the stage-specific // value to the environment value name. const stageNameUppercase = stageName ? stageName.toUpperCase() : '' const stagePrefix = stageNameUppercase ? `${stageNameUppercase}_` : '' envVars.forEach((envVar) => { let stageEnvVar = `${stagePrefix}${envVar}` process.env[envVar] = process.env[stageEnvVar] }) } module.exports = assignEnvVars
// Used to assign stage-specific env vars in our CI setup // to the env var names used in app code. // All env vars we want to pick up from the CI environment. const envVars = [ 'NODE_ENV', 'AWS_REGION', // AWS Cognito 'COGNITO_REGION', 'COGNITO_IDENTITYPOOLID', 'COGNITO_USERPOOLID', 'COGNITO_CLIENTID', // Web app 'PUBLIC_PATH', 'WEB_HOST', 'WEB_PORT', // GraphQL 'TABLE_NAME_APPENDIX', 'GRAPHQL_PORT', // Endpoints 'GRAPHQL_ENDPOINT', 'DYNAMODB_ENDPOINT', 'S3_ENDPOINT' // Secrets ] // Expect one argument, the stage name. const assignEnvVars = function (stageName, allEnvVarsRequired = true) { // Using the name of the stage, assign the stage-specific // value to the environment value name. const stageNameUppercase = stageName ? stageName.toUpperCase() : '' const stagePrefix = stageNameUppercase ? `${stageNameUppercase}_` : '' envVars.forEach((envVar) => { let stageEnvVarName = `${stagePrefix}${envVar}` let stageEnvVar = process.env[stageEnvVarName] // Optionally throw an error if an env variable is not set. if ( (typeof stageEnvVar === 'undefined' || stageEnvVar === null) && allEnvVarsRequired ) { throw new Error(`Environment variable ${stageEnvVarName} must be set.`) } process.env[envVar] = stageEnvVar }) } module.exports = assignEnvVars
Throw error if an expected env var is not set.
Throw error if an expected env var is not set.
JavaScript
mpl-2.0
gladly-team/tab,gladly-team/tab,gladly-team/tab
e3d04be3e031feabc28d5b13deaa4b445f885a05
static/js/views/dbView.js
static/js/views/dbView.js
_r(function (app) { if ( ! window.app.views.hasOwnProperty('db')) { app.views.db = {}; } /** * Database selection box */ app.views.db.box = app.base.formView.extend({ model: app.models.Db, module: 'db', action: 'box', auto_render: true, $el: $('<div id="db_box"></div>').appendTo('body > div.container'), events: { 'click .show_form': 'showForm', 'click .hide_form': 'hideForm' }, afterRender: function () { if (app.user_self.get('name')) { this.$el.show(); } app.base.formView.prototype.afterRender.apply(this, Array.prototype.slice.call(arguments)); }, load: function (callback) { this.model.fetch(function (db) { callback(null, db); }); }, showForm: function () { this.$el.addClass('with_form'); }, hideForm: function () { this.$el.removeClass('with_form'); this.render(); }, saved: function () { this.render(); this.model.once('saved', this.saved); } }); });
_r(function (app) { if ( ! window.app.views.hasOwnProperty('db')) { app.views.db = {}; } /** * Database selection box */ app.views.db.box = app.base.formView.extend({ model: app.models.Db, module: 'db', action: 'box', auto_render: true, $el: $('<div id="db_box"></div>').appendTo('body > div.container'), events: { 'click .show_form': 'showForm', 'click .hide_form': 'hideForm' }, afterRender: function () { if (app.user_self.get('name')) { this.$el.show(); } app.base.formView.prototype.afterRender.apply(this, Array.prototype.slice.call(arguments)); }, load: function (callback) { this.model.fetch(function (db) { callback(null, db); }); }, showForm: function () { this.$el.addClass('with_form'); }, hideForm: function () { this.$el.removeClass('with_form'); this.render(); }, saved: function () { this.hideForm(); this.model.once('saved', this.saved); app.reload(); } }); });
Fix db box to hide itself on successful change
Fix db box to hide itself on successful change
JavaScript
mit
maritz/nohm-admin,maritz/nohm-admin
85f32436c920101c8877462d11445ca44bc32832
lib/plugins/body_parser.js
lib/plugins/body_parser.js
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.method !== 'POST' && req.method !== 'PUT' && req.method !== 'PATCH') return next(); if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else if (options.rejectUnknown !== false) { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.method !== 'POST' && req.method !== 'PUT' && req.method !== 'PATCH') return next(); if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else if (options && options.rejectUnknown !== false) { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
Check that options is not empty
Check that options is not empty
JavaScript
mit
TheDeveloper/node-restify,prasmussen/node-restify,adunkman/node-restify,chaordic/node-restify,kevinykchan/node-restify,uWhisp/node-restify,jclulow/node-restify,ferhatsb/node-restify
623796045a00bb3cd67dd88ece4c89cae01e9f09
karma.conf.js
karma.conf.js
module.exports = function(config) { const files = [ { pattern: 'browser/everything.html', included: false, served: true, }, { pattern: 'browser/everything.js', included: true, served: true, }, { pattern: 'spec/fixtures/*.json', included: false, served: true, }, { pattern: 'browser/vendor/requirejs/*.js', included: false, served: true, }, { pattern: 'browser/vendor/react/*.js', included: false, served: true, }, { pattern: 'browser/manifest.appcache', included: false, served: true, }, 'spec/*.js', ]; const configuration = { basePath: '', frameworks: ['mocha', 'chai'], files, exclude: [], preprocessors: {}, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome', 'ChromeHeadless', 'ChromeHeadlessNoSandbox'], customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'], }, }, singleRun: true, concurrency: Infinity }; config.set(configuration); }
module.exports = function(config) { const files = [ { pattern: 'browser/everything.html', included: false, served: true, }, { pattern: 'browser/everything.js', included: true, served: true, }, { pattern: 'spec/fixtures/*.json', included: false, served: true, }, { pattern: 'browser/vendor/requirejs/*.js', included: false, served: true, }, { pattern: 'browser/vendor/react/*.js', included: false, served: true, }, { pattern: 'browser/manifest.appcache', included: false, served: true, }, 'spec/*.js', ]; const configuration = { basePath: '', frameworks: ['mocha', 'chai'], files, exclude: [], preprocessors: {}, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['ChromeHeadless'], customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'], }, }, singleRun: true, concurrency: Infinity }; if (process.env.TRAVIS) { configuration.browsers = ['ChromeHeadlessNoSandbox']; } config.set(configuration); }
Switch browser list when running in Travis
Switch browser list when running in Travis
JavaScript
mit
noflo/noflo-browser,noflo/noflo-browser
245ddf33d7d4fecbf000a6cd42f3c54cbc476238
karma.conf.js
karma.conf.js
/* global module:false */ module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'chai'], reporters: ['dots', 'progress'], browsers: ['ChromeIncognito', 'Firefox', 'Safari'], singleRun: true, customLaunchers: { ChromeIncognito: { base: 'Chrome', flags: ['--incognito'] } }, files: [ 'idbstore.min.js', 'test/**/*spec.js' ] }); };
/* global module:false */ module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'chai'], reporters: ['dots', 'progress'], browsers: ['ChromeIncognito', 'Firefox'], singleRun: true, customLaunchers: { ChromeIncognito: { base: 'Chrome', flags: ['--incognito'] } }, files: [ 'idbstore.min.js', 'test/**/*spec.js' ] }); };
Remove Safari from automated tests
Remove Safari from automated tests
JavaScript
mit
jensarps/IDBWrapper,jayfunk/IDBWrapper,jayfunk/IDBWrapper,jensarps/IDBWrapper
ee97033aab6492b08c23f7eb52e93c9f4f58b9bf
jest.config.js
jest.config.js
module.exports = { "modulePaths": [ "<rootDir>/app", "<rootDir>/node_modules" ], "moduleFileExtensions": [ "js", "json" ], "testRegex": "/test/*/.*-test.js$", "testEnvironment": "node", "testTimeout": 10000, "collectCoverage": true, "reporters": [ "default", [ "jest-junit", { "outputDirectory": "test/junit", "outputName": "TESTS.xml" } ] ], "collectCoverageFrom": [ "app/**/*.js", "!**/node_modules/**", "!**/test/**" ], "coverageDirectory": "<rootDir>/coverage", "coverageReporters": [ "json", "lcov", "html" ] }
module.exports = { "modulePaths": [ "<rootDir>/app", "<rootDir>/node_modules" ], "moduleFileExtensions": [ "js", "json" ], "testRegex": "/test/*/.*-test.js$", "testEnvironment": "node", "testTimeout": 10000, "collectCoverage": true, "reporters": [ "default", [ "jest-junit", { "outputDirectory": "test/junit", "outputName": "TESTS.xml" } ] ], "collectCoverageFrom": [ "app/**/*.js", "!**/node_modules/**", "!**/test/**" ], "coverageDirectory": "<rootDir>/coverage", "coverageReporters": [ "json", "lcov", "html", "cobertura" ] }
Add Cobertura Test coverage output
Add Cobertura Test coverage output
JavaScript
apache-2.0
stamp-web/stamp-webservices
13b19fd044152ac6bf1213aa4d22fa0cb1623da6
js/redirect.js
js/redirect.js
/*global chrome,document,window */ (function init(angular) { "use strict"; try { chrome.storage.local.get(["url", "tab.selected", "always-tab-update"], function (items) { var url = items.url; if (url) { url = (0 !== url.indexOf("about:") && -1 === url.indexOf("://")) ? ("http://" + url) : url; if (/^http[s]?:/i.test(url) && items["always-tab-update"] !== true) { document.location.href = url; } else { chrome.tabs.getCurrent(function (tab) { // a keen user may open the extension's background page and set: // chrome.storage.local.set({'tab.selected': false}); var selected = items["tab.selected"] === undefined ? true : (items["tab.selected"] == "true"); chrome.tabs.update(tab.id, { "url": url, "highlighted": selected }); }); } } else { angular.resumeBootstrap(); } }); } catch(e){ // If anything goes wrong with the redirection logic, fail to custom apps page. console.error(e); angular.resumeBootstrap(); } })(angular);
/*global chrome,document,window */ (function init(angular) { "use strict"; try { chrome.storage.local.get(["url", "tab.selected", "always-tab-update"], function (items) { var url = items.url; if (url) { url = (0 !== url.indexOf("about:") && 0 !== url.indexOf("data:") && -1 === url.indexOf("://")) ? ("http://" + url) : url; if (/^http[s]?:/i.test(url) && items["always-tab-update"] !== true) { document.location.href = url; } else { chrome.tabs.getCurrent(function (tab) { // a keen user may open the extension's background page and set: // chrome.storage.local.set({'tab.selected': false}); var selected = items["tab.selected"] === undefined ? true : (items["tab.selected"] == "true"); chrome.tabs.update(tab.id, { "url": url, "highlighted": selected }); }); } } else { angular.resumeBootstrap(); } }); } catch(e){ // If anything goes wrong with the redirection logic, fail to custom apps page. console.error(e); angular.resumeBootstrap(); } })(angular);
Allow data URIs to be set as the new tab page
Allow data URIs to be set as the new tab page
JavaScript
mit
jimschubert/NewTab-Redirect,jimschubert/NewTab-Redirect
1696f212f0ff83997f2aadb6b14a9cd4d716a172
src/commands/post.js
src/commands/post.js
const Command = require('../structures/Command'); const snekfetch = require('snekfetch'); const { inspect } = require('util'); class PostCommand extends Command { constructor() { super({ name: 'post', description: 'Update the guild count on <https://bots.discord.pw>', ownersOnly: true }); } async run(message, args) { const { config: { useDiscordBots, discordBotsAPI }, user, guilds, logger } = message.client; if (!useDiscordBots) return; snekfetch.post(`https://bots.discord.pw/api/bots/${user.id}/stats`) .set('Authorization', `${discordBotsAPI}`) .set('Content-type', 'application/json; charset=utf-8') .send(`{"server_count": ${guilds.size}}`) .then(res => message.reply('POST request sent successfully!')) .catch(err => { const errorDetails = `${err.host ? err.host : ''} ${err.text ? err.text : ''}`.trim(); message.reply(`an error occurred updating the guild count: \`\`${err.status}: ${errorDetails}\`\``); logger.error(inspect(err)); }); } } module.exports = PostCommand;
const Command = require('../structures/Command'); const snekfetch = require('snekfetch'); const { inspect } = require('util'); class PostCommand extends Command { constructor() { super({ name: 'post', description: 'Update the guild count on <https://bots.discord.pw>', ownersOnly: true }); } async run(message, args) { const { config: { useDiscordBots, discordBotsAPI }, user, guilds, logger } = message.client; if (!useDiscordBots) return; snekfetch.post(`https://bots.discord.pw/api/bots/${user.id}/stats`) .set('Authorization', `${discordBotsAPI}`) .set('Content-type', 'application/json; charset=utf-8') .send(`{"server_count": ${guilds.size}}`) .then(res => message.reply('POST request sent successfully!')) .catch(err => { message.reply(`an error occurred updating the guild count: \`\`${err.statusCode}: ${err.statusText}\`\``); logger.error(`Error updating to DiscordBots: ${err.statusCode} - ${err.statusText}`); }); } } module.exports = PostCommand;
Fix this logging n stuff
Fix this logging n stuff
JavaScript
mit
robflop/robbot
914e94f9e5531465fdf6028734fb99402fae3411
templates/html5/output.js
templates/html5/output.js
::if embeddedLibraries::::foreach (embeddedLibraries):: ::__current__::::end::::end:: // lime.embed namespace wrapper (function ($hx_exports, $global) { "use strict"; $hx_exports.lime = $hx_exports.lime || {}; $hx_exports.lime.$scripts = $hx_exports.lime.$scripts || {}; $hx_exports.lime.$scripts["::APP_FILE::"] = (function(exports, global) { ::SOURCE_FILE:: }); // End namespace wrapper $hx_exports.lime.embed = function(projectName) { var exports = {}; $hx_exports.lime.$scripts[projectName](exports, $global); for (var key in exports) $hx_exports[key] = $hx_exports[key] || exports[key]; exports.lime.embed.apply(exports.lime, arguments); return exports; }; })(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this, typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : this);
var $hx_script = (function(exports, global) { ::SOURCE_FILE::}); (function ($hx_exports, $global) { "use strict"; $hx_exports.lime = $hx_exports.lime || {}; $hx_exports.lime.$scripts = $hx_exports.lime.$scripts || {}; $hx_exports.lime.$scripts["::APP_FILE::"] = $hx_script; $hx_exports.lime.embed = function(projectName) { var exports = {}; $hx_exports.lime.$scripts[projectName](exports, $global); for (var key in exports) $hx_exports[key] = $hx_exports[key] || exports[key]; exports.lime.embed.apply(exports.lime, arguments); return exports; }; })(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this, typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : this); ::if embeddedLibraries::::foreach (embeddedLibraries)::::__current__:: ::end::::end::
Fix line numbers for HTML5 source maps
Fix line numbers for HTML5 source maps
JavaScript
mit
madrazo/lime-1,player-03/lime,madrazo/lime-1,MinoGames/lime,openfl/lime,player-03/lime,openfl/lime,madrazo/lime-1,madrazo/lime-1,MinoGames/lime,openfl/lime,openfl/lime,madrazo/lime-1,player-03/lime,MinoGames/lime,openfl/lime,player-03/lime,player-03/lime,MinoGames/lime,MinoGames/lime,MinoGames/lime,player-03/lime,madrazo/lime-1,player-03/lime,MinoGames/lime,openfl/lime,madrazo/lime-1,openfl/lime
d64c1914a95e150b32ec750171187b8354059cd8
lib/errors.js
lib/errors.js
/* * Grasspiler / errors.js * copyright (c) 2016 Susisu */ "use strict"; function endModule() { module.exports = Object.freeze({ ParseError, CompileError }); } class ParseError extends Error { constructor(message) { super(message); this.name = this.constructor.name; } } class CompileError extends Error { constructor(trace, message) { super(message); this.trace = trace; } addTrace(trace) { return new CompileError(trace.concat(this.trace), this.message); } toString() { const traceStr = this.trace.map(t => t.toString() + ":\n").join(""); return traceStr + this.message; } } endModule();
/* * Grasspiler / errors.js * copyright (c) 2016 Susisu */ "use strict"; function endModule() { module.exports = Object.freeze({ ParseError, CompileError }); } class ParseError extends Error { constructor(message) { super(message); this.name = this.constructor.name; } } class CompileError extends Error { constructor(trace, message) { super(message); this.name = this.constructor.name; this.trace = trace; } addTrace(trace) { return new CompileError(trace.concat(this.trace), this.message); } toString() { const traceStr = this.trace.map(t => t.toString() + ":\n").join(""); return this.name + ": " + traceStr + this.message; } } endModule();
Add name property to compile error
Add name property to compile error
JavaScript
mit
susisu/Grasspiler
df3766e78ec0c5af757135192e5a1ff6b051199f
lib/errors.js
lib/errors.js
/** * Copyright 2013 Rackspace * * 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. * */ var util = require('util'); /** * * @constructor * * @param {String} message The error message. */ function ClientTimeoutError(message) { Error.call(this, error); this.message = message; this.name = 'ClientTimeoutException'; } util.inherits(ClientTimeoutError, Error); exports.ClientTimeoutError = ClientTimeoutError;
/** * Copyright 2014 Rackspace * * 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. * */ var util = require('util'); /** * Error for when the client times out a query. * @constructor * * @param {String} message The error message. */ function ClientTimeoutError(message) { Error.call(this, error); this.message = message; this.name = 'ClientTimeoutException'; } util.inherits(ClientTimeoutError, Error); exports.ClientTimeoutError = ClientTimeoutError;
Add missing comment and fix copyright date.
Add missing comment and fix copyright date.
JavaScript
apache-2.0
racker/node-cassandra-client,racker/node-cassandra-client
a0f8a7bcc765f8fb07a2760a09307faf39404aca
lib/adapter.js
lib/adapter.js
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://cksource.com/ckfinder/license */ ( function( window, bender ) { 'use strict'; var unlock = bender.defer(), originalRequire = window.require; // TODO what if require is never called? bender.require = function( deps, callback ) { originalRequire( deps, function() { callback.apply( null, arguments ); unlock(); } ); }; } )( this, bender );
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://cksource.com/ckfinder/license */ ( function( window, bender ) { 'use strict'; bender.require = function( deps, callback ) { var unlock = bender.defer(); window.require( deps, function() { callback.apply( null, arguments ); unlock(); } ); }; } )( this, bender );
Move bender.defer() inside the require call.
Move bender.defer() inside the require call.
JavaScript
mit
benderjs/benderjs-amd
1057855e5c60e281e8c2450d4ac5560c385da771
package.js
package.js
Package.describe({ name: 'verody:groupaccount', version: '0.1.0', summary: 'Account management package providing qualified access to a single Meteor server account from one or more sets of credentials.', git: 'https://github.com/ekobi/meteor-groupaccount.git', documentation: 'README.md' }); Package.onUse(function(api) { api.use('npm-bcrypt@=0.7.8_2'); api.use([ 'accounts-base', 'ecmascript', 'sha', 'ejson', 'ddp', 'check', 'underscore' ], ['client', 'server']); api.versionsFrom('1.2.1'); api.imply ('accounts-base'); api.addFiles(['groupaccount.js']); api.export('GroupAccounts'); }); Package.onTest(function(api) { api.use(['tinytest', 'random']); api.use(['accounts-base', 'verody:groupaccount', 'sha']); api.addFiles('groupaccount-tests.js'); });
Package.describe({ name: 'verody:groupaccount', version: '0.1.0', summary: 'Provides qualified access to a single Meteor user account from one or more sets of credentials.', git: 'https://github.com/ekobi/meteor-groupaccount.git', documentation: 'README.md' }); Package.onUse(function(api) { api.use('npm-bcrypt@=0.7.8_2'); api.use([ 'accounts-base', 'ecmascript', 'sha', 'ejson', 'ddp', 'check', 'underscore' ], ['client', 'server']); api.versionsFrom('1.2.1'); api.imply ('accounts-base'); api.addFiles(['groupaccount.js']); api.export('GroupAccounts'); }); Package.onTest(function(api) { api.use(['tinytest', 'random']); api.use(['accounts-base', 'verody:groupaccount', 'sha']); api.addFiles('groupaccount-tests.js'); });
Trim summary to fit 100 character limit.
Trim summary to fit 100 character limit.
JavaScript
mit
ekobi/meteor-groupaccount,ekobi/meteor-groupaccount,ekobi/meteor-groupaccount
3e968acae5397d7b33d409fc0c26da610c1ba9b0
Resources/js/InjectCSS.js
Resources/js/InjectCSS.js
document.documentElement.style.webkitTouchCallout='none'; var root = document.getElementsByTagName( 'html' )[0] root.setAttribute( 'class', 'hybrid' ); var styleElement = document.createElement('style'); root.appendChild(styleElement); styleElement.textContent = '${CSS}';
document.documentElement.style.webkitTouchCallout='none'; var root = document.getElementsByTagName( 'html' )[0] root.setAttribute( 'class', 'neeman-hybrid-app' ); var styleElement = document.createElement('style'); root.appendChild(styleElement); styleElement.textContent = '${CSS}';
Switch HTML tag to one less likely to be used by another library.
Switch HTML tag to one less likely to be used by another library.
JavaScript
mit
intellum/neeman,intellum/neeman,intellum/neeman,intellum/neeman
cfe506bf86d27cf1c1c9677adf7902e3c003dfe7
lib/webhook.js
lib/webhook.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() }, issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}` } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
Move additional field "issuer" out of the "solution" object
Move additional field "issuer" out of the "solution" object
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
54b35d592d3d2c7e9c4357acc2c3cdc3a3c5478f
src/client/blog/posts/posts-service.js
src/client/blog/posts/posts-service.js
BlogPostsFactory.$inject = ['$resource']; function BlogPostsFactory($resource){ return $resource('/api/v1/posts/:postId'); } angular.module('blog.posts.service', [ 'ngResource' ]).factory('Posts', BlogPostsFactory);
BlogPostsFactory.$inject = ['$resource']; function BlogPostsFactory($resource){ return $resource('/api/v1/posts/:postId', {postId: '@id'}); } angular.module('blog.posts.service', [ 'ngResource' ]).factory('Posts', BlogPostsFactory);
Allow saving with the posts.
Allow saving with the posts.
JavaScript
isc
RupertJS/rupert-example-blog,RupertJS/rupert-example-blog
ff4ac1f418508c005d5afa713027af33dcf29ff1
test/helper.js
test/helper.js
var nock = require('nock') , io = require('../index'); var helper = exports; // // Define the default options // var default_options = helper.default_options = { endpoint: 'https://api.orchestrate.io', api: 'v0' }; // // Create a new fake server // helper.fakeIo = require('./support/fake-io').createServer(default_options); helper.io = io;
/* * helper.js * */ var io = require('../index'); var helper = exports; var default_options = helper.default_options = { endpoint: 'https://api.orchestrate.io', api: 'v0' }; // // Create a new fake server // helper.fakeIo = require('./support/fake-io').createServer(default_options); helper.io = io;
Stop to require a useless module
Stop to require a useless module
JavaScript
mit
giraffi/node-orchestrate.io
3d0972cc6f42359bc3a94254c808a1a6e34517a9
src/custom/cappasity-users-activate.js
src/custom/cappasity-users-activate.js
const ld = require('lodash'); const moment = require('moment'); const setMetadata = require('../utils/updateMetadata.js'); /** * Adds metadata from billing into usermix * @param {String} username * @return {Promise} */ module.exports = function mixPlan(username, audience) { const { amqp, config } = this; const { payments } = config; const route = [payments.prefix, payments.routes.planGet].join('.'); const id = 'free'; return amqp .publishAndWait(route, id, { timeout: 5000 }) .bind(this) .then(function mix(plan) { const subscription = ld.findWhere(plan.subs, { name: id }); const nextCycle = moment().add(1, 'month').format(); const update = { username, audience, metadata: { '$set': { plan: id, nextCycle, models: subscription.models, modelPrice: subscription.price, }, }, }; return setMetadata.call(this, update); }); };
const Promise = require('bluebird'); const ld = require('lodash'); const moment = require('moment'); const setMetadata = require('../utils/updateMetadata.js'); /** * Adds metadata from billing into usermix * @param {String} username * @return {Promise} */ module.exports = function mixPlan(username, audience) { const { amqp, config } = this; const { payments } = config; const route = [payments.prefix, payments.routes.planGet].join('.'); const id = 'free'; // make sure that ms-payments is launched before return Promise .delay(10000) .then(() => { return amqp .publishAndWait(route, id, { timeout: 5000 }) .bind(this) .then(function mix(plan) { const subscription = ld.findWhere(plan.subs, { name: id }); const nextCycle = moment().add(1, 'month').format(); const update = { username, audience, metadata: { '$set': { plan: id, nextCycle, models: subscription.models, modelPrice: subscription.price, }, }, }; return setMetadata.call(this, update); }); }); };
Add sleep in custom action
Add sleep in custom action
JavaScript
mit
makeomatic/ms-users,makeomatic/ms-users
58239dac2cc98052570cd13e87905c9fb3b11de5
src/scenes/home/opCodeCon/opCodeCon.js
src/scenes/home/opCodeCon/opCodeCon.js
import React from 'react'; import commonUrl from 'shared/constants/commonLinks'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './opCodeCon.css'; const OpCodeCon = () => ( <div className={styles.hero}> <div className={styles.heading}> <h1>OpCodeCon</h1> <h3>Join us for our inaugural Operation Code Convention!</h3> <p>September 19th-20th, 2018</p> <p>Raleigh Convention Center, Raleigh, NC</p> <p> <a href="mailto:eilish@operationcode.org" className={styles.textLink}> Contact us </a>{' '} for sponsorship information. </p> <LinkButton role="button" text="Donate" theme="red" link={commonUrl.donateLink} isExternal /> {/* <p>Check back for more information.</p> */} </div> </div> ); export default OpCodeCon;
import React from 'react'; import commonUrl from 'shared/constants/commonLinks'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './opCodeCon.css'; const OpCodeCon = () => ( <div className={styles.hero}> <div className={styles.heading}> <h1>OpCodeCon</h1> <h3>Join us for our inaugural Operation Code Convention!</h3> <p>September 19th-20th, 2018</p> <p>Raleigh Convention Center, Raleigh, NC</p> <p> <a href="mailto:eilish@operationcode.org" className={styles.textLink}> Contact us </a>{' '} for sponsorship information. </p> <LinkButton role="button" text="Donate" theme="red" link={commonUrl.donateLink} isExternal /> {/* <p>Check back for more information.</p> */} </div> </div> ); export default OpCodeCon;
Fix ESLint error causing Travis build to fail
Fix ESLint error causing Travis build to fail 'jsx-max-props-per-line' rule
JavaScript
mit
sethbergman/operationcode_frontend,OperationCode/operationcode_frontend,sethbergman/operationcode_frontend,sethbergman/operationcode_frontend,hollomancer/operationcode_frontend,OperationCode/operationcode_frontend,hollomancer/operationcode_frontend,OperationCode/operationcode_frontend,hollomancer/operationcode_frontend
c4e00daab05ac6cc0b9965fd5a07539b3281bd2e
app/routes.js
app/routes.js
module.exports = { bind : function (app) { app.get('/', function (req, res) { console.log("Clearing the session.") delete req.session res.render('index'); }); app.get('/examples/template-data', function (req, res) { res.render('examples/template-data', { 'name' : 'Foo' }); }); app.post('/start-flow', function(req, res) { res.redirect('/service-before'); }); // add your routes here } };
function clear_session(req) { console.log("Clearing the session.") delete req.session } module.exports = { bind : function (app) { app.get('/', function (req, res) { clear_session(req); res.render('index'); }); app.get('/index', function (req, res) { clear_session(req); res.render('index'); }); app.get('/examples/template-data', function (req, res) { res.render('examples/template-data', { 'name' : 'Foo' }); }); app.post('/start-flow', function(req, res) { res.redirect('/service-before'); }); // add your routes here } };
Clear the session on accessing the index page too.
Clear the session on accessing the index page too.
JavaScript
mit
stephenjoe1/pay-staff-tool,stephenjoe1/pay-staff-tool,stephenjoe1/pay-staff-tool
8ebb4b1d798c02dd62d7b0e584f567374c4a930c
NoteWrangler/public/js/routes.js
NoteWrangler/public/js/routes.js
// js/routes (function() { "use strict"; angular.module("NoteWrangler") .config(config); function config($routeProvider) { $routeProvider .when("/notes", { templateUrl: "../templates/pages/notes/index.html", controller: "NotesIndexController", controllerAs: "notesIndexCtrl" }) .when("/users", { templateUrl: "../templates/pages/users/index.html" }) .when("/notes/new", { templateUrl: "templates/pages/notes/new.html", controller: "NotesCreateController", controllerAs: "notesCreateCtrl" }) .when("/notes/:id", { templateUrl: "templates/pages/notes/show.html", controller: "NotesShowController", controllerAs: "notesShowCtrl" }) .otherwise({ redirectTo: "/" }); } })();
// js/routes (function() { "use strict"; angular.module("NoteWrangler") .config(config); function config($routeProvider) { $routeProvider .when("/notes", { templateUrl: "../templates/pages/notes/index.html", controller: "NotesIndexController", controllerAs: "notesIndexCtrl" }) .when("/users", { templateUrl: "../templates/pages/users/index.html" }) .when("/notes/new", { templateUrl: "templates/pages/notes/new.html", controller: "NotesCreateController", controllerAs: "notesCreateCtrl" }) .when("/notes/:id", { templateUrl: "templates/pages/notes/show.html", controller: "NotesShowController", controllerAs: "notesShowCtrl" }) .otherwise({ redirectTo: "/", templateUrl: "templates/pages/index/index.html" }); } })();
Add templateUrl for default route
Add templateUrl for default route
JavaScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
b33eafc06f6f89166cecd8cde664c470cc249b31
lib/app.js
lib/app.js
var app = require("express")(); app.get('/', function (req, res) { res.send('c\'est ne une jsbin'); }); app.listen(3000);
var express = require('express'), path = require('path'), app = express(); app.root = path.join(__dirname, '..', 'public'); app.use(express.logger()); app.use(express.static(app.root)); app.get('/', function (req, res) { res.send('c\'est ne une jsbin'); }); module.exports = app; // Run a local development server if this file is called directly. if (require.main === module) { app.listen(3000); }
Add support for serving static files and logging
Add support for serving static files and logging
JavaScript
mit
thsunmy/jsbin,jsbin/jsbin,filamentgroup/jsbin,mingzeke/jsbin,jwdallas/jsbin,kentcdodds/jsbin,jsbin/jsbin,knpwrs/jsbin,IvanSanchez/jsbin,martinvd/jsbin,blesh/jsbin,saikota/jsbin,pandoraui/jsbin,carolineartz/jsbin,dhval/jsbin,svacha/jsbin,mlucool/jsbin,dennishu001/jsbin,eggheadio/jsbin,Freeformers/jsbin,mcanthony/jsbin,ctide/jsbin,johnmichel/jsbin,eggheadio/jsbin,ctide/jsbin,arcseldon/jsbin,ilyes14/jsbin,y3sh/jsbin-fork,mingzeke/jsbin,francoisp/jsbin,AverageMarcus/jsbin,KenPowers/jsbin,Freeformers/jsbin,KenPowers/jsbin,IveWong/jsbin,late-warrior/jsbin,dedalik/jsbin,jasonsanjose/jsbin-app,yize/jsbin,nitaku/jervis,HeroicEric/jsbin,mlucool/jsbin,fend-classroom/jsbin,Hamcha/jsbin,saikota/jsbin,Hamcha/jsbin,simonThiele/jsbin,KenPowers/jsbin,mcanthony/jsbin,simonThiele/jsbin,jamez14/jsbin,yohanboniface/jsbin,dennishu001/jsbin,jamez14/jsbin,dedalik/jsbin,knpwrs/jsbin,pandoraui/jsbin,minwe/jsbin,knpwrs/jsbin,dhval/jsbin,francoisp/jsbin,yize/jsbin,carolineartz/jsbin,juliankrispel/jsbin,mdo/jsbin,peterblazejewicz/jsbin,IveWong/jsbin,fgrillo21/NPA-Exam,jasonsanjose/jsbin-app,ilyes14/jsbin,minwe/jsbin,fgrillo21/NPA-Exam,digideskio/jsbin,y3sh/jsbin-fork,AverageMarcus/jsbin,IvanSanchez/jsbin,johnmichel/jsbin,fend-classroom/jsbin,remotty/jsbin,vipulnsward/jsbin,HeroicEric/jsbin,vipulnsward/jsbin,thsunmy/jsbin,digideskio/jsbin,martinvd/jsbin,jwdallas/jsbin,arcseldon/jsbin,late-warrior/jsbin,svacha/jsbin,kirjs/jsbin,roman01la/jsbin,juliankrispel/jsbin,yohanboniface/jsbin,kirjs/jsbin,roman01la/jsbin,peterblazejewicz/jsbin,kentcdodds/jsbin,filamentgroup/jsbin
4390638b4674024c7abd266450916fbe4f78ea5a
prompts.js
prompts.js
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'nginx', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } } ]; module.exports = prompts;
'use strict'; var _ = require('lodash'); var prompts = [ { type: 'input', name: 'projectName', message: 'Machine-name of your project?', // Name of the parent directory. default: _.last(process.cwd().split('/')), validate: function (input) { return (input.search(' ') === -1) ? true : 'No spaces allowed.'; } }, { type: 'list', name: 'webserver', message: 'Choose your webserver:', choices: [ 'apache', 'nginx', 'custom' ], default: 'apache' }, { name: 'webImage', message: 'Specify your webserver Docker image:', default: 'phase2/apache24php55', when: function(answers) { return answers.webserver == 'custom'; }, validate: function(input) { if (_.isString(input)) { return true; } return 'A validate docker image identifier is required.'; } }, { type: 'list', name: 'cacheInternal', message: 'Choose a cache backend:', default: 'memcache', choices: [ 'memcache', 'database' ] } ]; module.exports = prompts;
Add support for memcache with Drupal config via override.settings.php.
Add support for memcache with Drupal config via override.settings.php.
JavaScript
mit
phase2/generator-outrigger-drupal,phase2/generator-outrigger-drupal,phase2/generator-outrigger-drupal
9c69add5dbeb82687180f0f225defbe8cc2f0553
shows/paste.js
shows/paste.js
function(doc, req) { start({ "headers" : { "Content-type": "text/html" } }); var Mustache = require("vendor/mustache"); var x = Mustache.to_html(this.templates.paste, doc); return x; }
function(doc, req) { start({ "Content-type": "text/html; charset='utf-8'" }); var Mustache = require("vendor/mustache"); Mustache.to_html(this.templates.paste, doc, null, send); }
Use CouchDB send function when displaying the template
Use CouchDB send function when displaying the template Also correct the start function which was wrong before.
JavaScript
mit
gdamjan/paste-couchapp