commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
deb97101edcb6b5b97304c1d88ea6f2860e8d2ab
Fix for Firefox ignoring the autofocus attribute.
js/system.js
js/system.js
/* * Copyright (c) Codiad & Kent Safranski (codiad.com), distributed * as-is and without warranty under the MIT License. See * [root]/license.txt for more. This information must remain intact. */ ////////////////////////////////////////////////////////////////////// // loadScript instead of getScript (checks and balances and shit...) ////////////////////////////////////////////////////////////////////// jQuery.loadScript = function (url, arg1, arg2) { var cache = true, callback = null; //arg1 and arg2 can be interchangable if ($.isFunction(arg1)){ callback = arg1; cache = arg2 || cache; } else { cache = arg1 || cache; callback = arg2 || callback; } var load = true; //check all existing script tags in the page for the url jQuery('script[type="text/javascript"]') .each(function () { return load = (url != $(this).attr('src')); }); if (load){ //didn't find it in the page, so load it jQuery.ajax({ type: 'GET', url: url, success: callback, dataType: 'script', cache: cache }); } else { //already loaded so just call the callback if (jQuery.isFunction(callback)) { callback.call(this); }; }; }; ////////////////////////////////////////////////////////////////////// // Init ////////////////////////////////////////////////////////////////////// $(function(){ // Sliding sidebars sidebars.init(); var handleWidth = 10; $(window).on('load resize',function(){ if($("#sb-left").css('left')!==0 && !sidebars.user_lock){ margin_l = handleWidth; reduction = 2*handleWidth; }else{ margin_l = $("#sb-left").width(); reduction = margin_l + handleWidth; } $('#editor-region').css({ 'margin-left':margin_l+'px', 'width':($('body').outerWidth()-reduction)+'px', 'height':($('body').outerHeight()-25)+'px' }); }); }); ////////////////////////////////////////////////////////////////////// // Parse JSEND Formatted Returns ////////////////////////////////////////////////////////////////////// var jsend = { parse : function(d){ // (Data) var obj = $.parseJSON(d); if(obj.status=='error'){ message.error(obj.message); return 'error'; }else{ return obj.data; } } }; ////////////////////////////////////////////////////////////////////// // Modal ////////////////////////////////////////////////////////////////////// var modal = { load : function(w,u){ // (Width, URL) $('#modal').css({'top':'15%','left':'50%','width':w+'px','margin-left':'-'+Math.ceil(w/2)+'px'}).draggable({ handle: '#drag-handle' }); $('#modal-content').html('<div id="modal-loading"></div>'); $('#modal-content').load(u); $('#modal, #modal-overlay').fadeIn(200); sidebars.modal_lock = true; }, hide_overlay : function(){ $('#modal-overlay').hide(); }, unload : function(){ $('#modal-content form').die('submit'); // Prevent form bubbling $('#modal, #modal-overlay').fadeOut(200); $('#modal-content').html(''); sidebars.modal_lock = false; if(!sidebars.user_lock){ // Slide sidebar back $('#sb-left').animate({'left':'-290px'},300,'easeOutQuart'); $('#editor-region').animate({'margin-left':'10px','width':($('body').outerWidth()-20)+'px'},300,'easeOutQuart'); } } }; ////////////////////////////////////////////////////////////////////// // User Alerts / Messages ////////////////////////////////////////////////////////////////////// autoclose = null; var message = { success : function(m){ // (Message) $('#message').removeClass('error').addClass('success').html(m); this.show(); }, error : function(m){ // (Message) $('#message').removeClass('success').addClass('error').html(m); this.show(); }, show : function(){ clearTimeout(autoclose); $('#message').fadeIn(300); autoclose = setTimeout(function(){ message.hide(); },2000); }, hide : function(){ $('#message').fadeOut(300); } }; ////////////////////////////////////////////////////////////////////// // Workspace Resize ////////////////////////////////////////////////////////////////////// var sidebars = { user_lock : true, modal_lock : false, init : function(){ $('#lock-left-sidebar').on('click',function(){ if(sidebars.user_lock){ sidebars.user_lock = false; $('#lock-left-sidebar').html('V'); }else{ sidebars.user_lock = true; $('#lock-left-sidebar').html('U'); } }); // Left Column Slider $("#sb-left").hover(function() { var timeout_r = $(this).data("timeout_r"); if(timeout_r){ clearTimeout(timeout_r); } var sbarWidth = $("#sb-left").width(); $('#editor-region').animate({ 'margin-left': sbarWidth+'px', 'width':($('body').outerWidth()- sbarWidth - 10)+'px' },300,'easeOutQuart'); $(this).animate({'left':'0px'},300,'easeOutQuart'); },function() { var sbarWidth = $("#sb-left").width(); $(this).data("timeout_r", setTimeout($.proxy(function() { if(!sidebars.user_lock && !sidebars.modal_lock){ // Check locks $(this).animate({ 'left':(-sbarWidth + 10)+"px" },300,'easeOutQuart'); $('#editor-region').animate({'margin-left':'10px','width':($('body').outerWidth()-20)+'px'},300,'easeOutQuart'); } },this), 500)); }); // Right Column Slider $("#sb-right").hover(function() { var timeout_r = $(this).data("timeout_r"); if(timeout_r){ clearTimeout(timeout_r); } $('#editor-region').animate({'margin-right':'200px'},300,'easeOutQuart'); $(this).animate({'right':'0px'},300,'easeOutQuart'); },function() { $(this).data("timeout_r", setTimeout($.proxy(function() { $(this).animate({'right':'-190px'},300,'easeOutQuart'); $('#editor-region').animate({'margin-right':'10px'},300,'easeOutQuart'); },this), 500)); }); $(".sidebar-handle").draggable({ axis: 'x', drag: function(event, ui) { newWidth = ui.position.left; $("#sb-left").width(newWidth + 10); }, stop: function() { $(window).resize(); } }); } };
JavaScript
0
@@ -2813,16 +2813,144 @@ ).load(u +,function()%7B%0A // Fix for Firefox autofocus goofiness%0A $('input%5Bautofocus=%22autofocus%22%5D').focus();%0A %7D );%0A
c9354954b120817827d32b1aa870ddd28321d992
Update upvote.js
js/upvote.js
js/upvote.js
var Upvote = (function (window, document) { that = this; // endEvent = hasTouch ? 'touchend' : 'mouseup', Upvote = function (opts) { that = this; this.current_category = 'us'; // --------------------------------------------------------- // Muench launch // --------------------------------------------------------- // Options from user for (i in opts) this.options[i] = opts[i]; // --------------------------------------------------------- // Skimmin launch // --------------------------------------------------------- $('.upvote-container').on('click', this.fn_tap_upvote.bind(this)); $('.category-container').on('click', this.fn_change_category.bind(this)); window.addEventListener('load', function() { FastClick.attach(document.body); }, false); }; Upvote.prototype = { // ------------------------------------------------------ // Skimmin Core Functions // ------------------------------------------------------ fn_change_category: function(e) { space_index = e.target.className.lastIndexOf(" "); category_class = e.target.className.substr(space_index); if ($('.upvote-container').hasClass('upvoted') == true) { $('.upvote-container').removeClass(this.current_category); $('.upvote-text').removeClass(this.current_category); $('.upvote-icon').removeClass(this.current_category); $('.upvote-container').addClass(category_class); $('.upvote-text').addClass(category_class); $('.upvote-icon').addClass(category_class); } this.current_category = category_class; }, fn_tap_upvote: function() { if ($('.upvote-container').hasClass('upvoted') == true) { $('.upvote-container').removeClass('upvoted'); setTimeout(function() { $('.upvote-container').removeClass('tapped us world sports business technology entertainment'); $('.upvote-text').removeClass('us world sports business technology entertainment'); $('.upvote-text').html(30); $('.upvote-icon').removeClass('us world sports business technology entertainment'); }, 300); } else { $('.upvote-container').addClass('upvoted'); setTimeout(function() { $('.upvote-container').addClass('tapped ' + that.current_category); $('.upvote-text').addClass(that.current_category); $('.upvote-text').html(31); $('.upvote-icon').addClass(that.current_category); }, 300); } }, }; return Upvote; })(window, document);
JavaScript
0.000002
@@ -2200,18 +2200,18 @@ ').html( -30 +14 );%0A @@ -2603,10 +2603,10 @@ tml( -3 1 +5 );%0A
42ffeca6756bf1f51e9c49abbf10982399fb637d
Add tech level to planet generation tests
src/utils/__tests__/sector-generator.spec.js
src/utils/__tests__/sector-generator.spec.js
import Chance from 'chance'; import { every } from 'lodash'; import sectorGenerator, { generatePlanet } from '../sector-generator'; import { worldTagKeys } from '../../constants/world-tags'; import Atmosphere from '../../constants/atmosphere'; import Temperature from '../../constants/temperature'; import Biosphere from '../../constants/biosphere'; import Population from '../../constants/population'; describe('SectorGenerator', () => { let config; beforeEach(() => { config = { columns: 8, rows: 10, isBuilder: false, }; }); it('should have a randomly generated name', () => { const { name } = sectorGenerator(config); expect(name).toBeDefined(); }); it('should pass the key, rows, and columns through to the result', () => { const testKey = 'lkjhgfdsa'; const testName = 'The Outer Worlds'; const { key, name, rows, columns } = sectorGenerator({ ...config, key: testKey, name: testName, }); expect(key).toEqual(testKey); expect(name).toEqual(testName); expect(rows).toEqual(10); expect(columns).toEqual(8); }); it('should generate a sector with no systems if it is initialized in builder mode', () => { const { systems } = sectorGenerator({ ...config, isBuilder: true }); expect(systems).toEqual({}); }); it('should have a minimum system count of at least row * columns / 4', () => { const { systems } = sectorGenerator(config); expect( Object.keys(systems).length >= config.rows * config.columns / 4, ).toBeTruthy(); }); it('should generate between one and three planets per system', () => { const { systems } = sectorGenerator(config); Object.values(systems).forEach(system => { const numPlanets = Object.keys(system.planets).length; expect(numPlanets >= 1).toBeTruthy(); expect(numPlanets <= 3).toBeTruthy(); }); }); describe('generatePlanet', () => { it('should include a random name', () => { const { name } = generatePlanet(new Chance())(); expect(name).toBeDefined(); expect(name.split(' ')).toHaveLength(1); }); it('should include an encoded key', () => { const testName = 'VJLAE FLIAE%='; const { key } = generatePlanet(new Chance(), testName)(); expect(key).toEqual(encodeURIComponent(testName.toLowerCase())); }); it('should include world tags from list', () => { const { tags } = generatePlanet(new Chance())(); expect( every(tags, tag => Object.keys(worldTagKeys).includes(tag)), ).toBeTruthy(); }); it('should include atmosphere from list', () => { const { atmosphere } = generatePlanet(new Chance())(); expect(Object.keys(Atmosphere).includes(atmosphere)).toBeTruthy(); }); it('should include temperature from list', () => { const { temperature } = generatePlanet(new Chance())(); expect(Object.keys(Temperature).includes(temperature)).toBeTruthy(); }); it('should include biosphere from list', () => { const { biosphere } = generatePlanet(new Chance())(); expect(Object.keys(Biosphere).includes(biosphere)).toBeTruthy(); }); it('should include population from list', () => { const { population } = generatePlanet(new Chance())(); expect(Object.keys(Population).includes(population)).toBeTruthy(); }); }); });
JavaScript
0.000001
@@ -185,16 +185,68 @@ -tags';%0A +import TechLevel from '../../constants/tech-level';%0A import A @@ -2619,32 +2619,226 @@ thy();%0A %7D);%0A%0A + it('should include tech level from list', () =%3E %7B%0A const %7B techLevel %7D = generatePlanet(new Chance())();%0A expect(Object.keys(TechLevel).includes(techLevel)).toBeTruthy();%0A %7D);%0A%0A it('should i
c87d0bfb741134867b4d0af6393e978719f175fc
fix delayed sorting
src/mui/field/ReferenceManyField.js
src/mui/field/ReferenceManyField.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import LinearProgress from 'material-ui/LinearProgress'; import { crudGetManyReference as crudGetManyReferenceAction } from '../../actions/dataActions'; import { getIds, getReferences, nameRelatedTo } from '../../reducer/references/oneToMany'; import { SORT_ASC, SORT_DESC } from '../../reducer/resource/list/queryReducer'; /** * Render related records to the current one. * * You must define the fields to be passed to the iterator component as children. * * @example Display all the comments of the current post as a datagrid * <ReferenceManyField reference="comments" target="post_id"> * <Datagrid> * <TextField source="id" /> * <TextField source="body" /> * <DateField source="created_at" /> * <EditButton /> * </Datagrid> * </ReferenceManyField> * * @example Display all the books by the current author, only the title * <ReferenceManyField reference="books" target="author_id"> * <SingleFieldList> * <ChipField source="title" /> * </SingleFieldList> * </ReferenceManyField> * * By default, restricts the possible values to 25. You can extend this limit * by setting the `perPage` prop. * * @example * <ReferenceManyField perPage={10} reference="comments" target="post_id"> * ... * </ReferenceManyField> * * By default, orders the possible values by id desc. You can change this order * by setting the `sort` prop (an object with `field` and `order` properties). * * @example * <ReferenceManyField sort={{ field: 'created_at', order: 'DESC' }} reference="comments" target="post_id"> * ... * </ReferenceManyField> * * Also, you can filter the query used to populate the possible values. Use the * `filter` prop for that. * * @example * <ReferenceManyField filter={{ is_published: true }} reference="comments" target="post_id"> * ... * </ReferenceManyField> */ export class ReferenceManyField extends Component { constructor(props) { super(props); this.state = { sort: props.sort }; } componentDidMount() { this.fetchReferences(); } componentWillReceiveProps(nextProps) { if (this.props.record.id !== nextProps.record.id) { this.fetchReferences(nextProps); } } setSort = (field) => { const order = this.state.sort.field === field && this.state.sort.order === SORT_ASC ? SORT_DESC : SORT_ASC; this.setState({ sort: { field, order } }); this.fetchReferences(); } fetchReferences({ reference, record, resource, target, perPage, filter } = this.props) { const { crudGetManyReference } = this.props; const pagination = { page: 1, perPage }; const relatedTo = nameRelatedTo(reference, record.id, resource, target); crudGetManyReference(reference, target, record.id, relatedTo, pagination, this.state.sort, filter); } render() { const { resource, reference, data, ids, children, basePath, isLoading } = this.props; if (React.Children.count(children) !== 1) { throw new Error('<ReferenceManyField> only accepts a single child (like <Datagrid>)'); } if (typeof ids === 'undefined') { return <LinearProgress style={{ marginTop: '1em' }} />; } const referenceBasePath = basePath.replace(resource, reference); // FIXME obviously very weak return React.cloneElement(children, { resource: reference, ids, data, isLoading, basePath: referenceBasePath, currentSort: this.state.sort, setSort: this.setSort, }); } } ReferenceManyField.propTypes = { addLabel: PropTypes.bool, basePath: PropTypes.string.isRequired, children: PropTypes.element.isRequired, crudGetManyReference: PropTypes.func.isRequired, filter: PropTypes.object, ids: PropTypes.array, label: PropTypes.string, perPage: PropTypes.number, record: PropTypes.object, reference: PropTypes.string.isRequired, data: PropTypes.object, resource: PropTypes.string.isRequired, sort: PropTypes.shape({ field: PropTypes.string, order: PropTypes.oneOf(['ASC', 'DESC']), }), source: PropTypes.string.isRequired, target: PropTypes.string.isRequired, isLoading: PropTypes.bool, }; ReferenceManyField.defaultProps = { filter: {}, perPage: 25, sort: { field: 'id', order: 'DESC' }, source: '', }; function mapStateToProps(state, props) { const relatedTo = nameRelatedTo(props.reference, props.record.id, props.resource, props.target); return { data: getReferences(state, props.reference, relatedTo), ids: getIds(state, relatedTo), isLoading: state.admin.loading > 0, }; } const ConnectedReferenceManyField = connect(mapStateToProps, { crudGetManyReference: crudGetManyReferenceAction, })(ReferenceManyField); ConnectedReferenceManyField.defaultProps = { addLabel: true, source: '', }; export default ConnectedReferenceManyField;
JavaScript
0.000001
@@ -2529,16 +2529,29 @@ etState( +%0A %7B sort: @@ -2568,18 +2568,17 @@ rder %7D %7D -); +, %0A @@ -2570,32 +2570,36 @@ er %7D %7D,%0A + this.fetchRefere @@ -2594,33 +2594,42 @@ .fetchReferences -( +,%0A );%0A %7D%0A%0A fe
25847db2dedb3b98078ee3da970da52b80790402
Handle null value in CheckboxGroupInput
src/mui/input/CheckboxGroupInput.js
src/mui/input/CheckboxGroupInput.js
import React, { Component, PropTypes } from 'react'; import Checkbox from 'material-ui/Checkbox'; import Labeled from './Labeled'; /** * An Input component for a checkbox group, using an array of objects for the options * * Pass possible options as an array of objects in the 'choices' attribute. * * The expected input must be an array of identifiers (e.g. [12, 31]) which correspond to * the 'optionValue' of 'choices' attribute objects. * * By default, the options are built from: * - the 'id' property as the option value, * - the 'name' property an the option text * @example * const choices = [ * { id: 12, name: 'Ray Hakt' }, * { id: 31, name: 'Ann Gullar' }, * { id: 42, name: 'Sean Phonee' }, * ]; * <CheckboxGroupInput source="recipients" choices={choices} /> * * You can also customize the properties to use for the option name and value, * thanks to the 'optionText' and 'optionValue' attributes. * @example * const choices = [ * { _id: 123, full_name: 'Leo Tolstoi' }, * { _id: 456, full_name: 'Jane Austen' }, * ]; * <CheckboxGroupInput source="recipients" choices={choices} optionText="full_name" optionValue="_id" /> * * `optionText` also accepts a function, so you can shape the option text at will: * @example * const choices = [ * { id: 123, first_name: 'Leo', last_name: 'Tolstoi' }, * { id: 456, first_name: 'Jane', last_name: 'Austen' }, * ]; * const optionRenderer = choice => `${choice.first_name} ${choice.last_name}`; * <CheckboxGroupInput source="recipients" choices={choices} optionText={optionRenderer} /> * * `optionText` also accepts a React Element, that will be cloned and receive * the related choice as the `record` prop. You can use Field components there. * @example * const choices = [ * { id: 123, first_name: 'Leo', last_name: 'Tolstoi' }, * { id: 456, first_name: 'Jane', last_name: 'Austen' }, * ]; * const FullNameField = ({ record }) => <span>{record.first_name} {record.last_name}</span>; * <CheckboxGroupInput source="recipients" choices={choices} optionText={<FullNameField />}/> */ export class CheckboxGroupInput extends Component { handleCheck = (event, isChecked) => { const { input: { value, onChange } } = this.props; if (isChecked) { onChange([...value, ...[event.target.value]]); } else { onChange(value.filter(v => (v != event.target.value))); } }; render() { const { choices, optionValue, optionText, label, resource, source, options, input: { value }, } = this.props; const option = React.isValidElement(optionText) ? // eslint-disable-line no-nested-ternary choice => React.cloneElement(optionText, { record: choice }) : (typeof optionText === 'function' ? optionText : choice => choice[optionText] ); return ( <Labeled label={label} source={source} resource={resource}> <div> {choices.map(choice => <Checkbox key={choice[optionValue]} checked={value.find(v => (v == choice[optionValue])) !== undefined} onCheck={this.handleCheck} value={choice[optionValue]} label={option(choice)} {...options} />, )} </div> </Labeled> ); } } CheckboxGroupInput.propTypes = { addField: PropTypes.bool.isRequired, choices: PropTypes.arrayOf(PropTypes.object), label: PropTypes.string, source: PropTypes.string, options: PropTypes.object, input: PropTypes.shape({ onChange: PropTypes.func.isRequired, }), optionText: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.element, ]).isRequired, optionValue: PropTypes.string.isRequired, resource: PropTypes.string, }; CheckboxGroupInput.defaultProps = { addField: true, choices: [], options: {}, optionText: 'name', optionValue: 'id', }; export default CheckboxGroupInput;
JavaScript
0
@@ -3277,16 +3277,24 @@ d=%7Bvalue + ? value .find(v @@ -3337,16 +3337,24 @@ ndefined + : false %7D%0A
3babcc0fc3a9b25ec5c04b02524275de643f5ee7
Update calculate.js
lib/calculate.js
lib/calculate.js
exports = module.exports = function Calculate(command) { command.prototype._aspectIsEqual = function(ar1, ar2) { var p1 = this.toAspectRatio(ar1); var p2 = this.toAspectRatio(ar2); if (p1 === undefined || p2 === undefined) { return false; } else { return (p1.x === p2.x && p1.y === p2.y); } }; command.prototype._calculatePadding = function(data) { if (data.video.aspect) { var newaspect, padAmount; // check if the aspect ratio has changed if (this.options.video.aspect && !this.options.video.size) { newaspect = this.options.video.aspect; } else if (!this.options.video.aspect) { // check aspect ratio change by calculating new aspect ratio from size (using greatest common divider, GCD) var ratio = this.gcd(this.options.video.width, this.options.video.height); newaspect = this.options.video.width / ratio + ':' + this.options.video.height / ratio; } else { // we have both aspect ratio and size set, all calculations are fine newaspect = this.options.video.aspect; } // if there are still no sizes for our output video, assume input size if (!this.options.video.width && !this.options.video.height) { this.options.video.width = data.video.resolution.w; this.options.video.height = data.video.resolution.h; } if (!this._aspectIsEqual(data.video.aspectString, newaspect)) { var ardata = this.toAspectRatio(newaspect); if (newaspect === '16:9') { // assume conversion from 4:3 to 16:9, pad output video stream left- / right-sided var newWidth = parseInt(this.options.video.width / (4 / 3), 10); newWidth += (newWidth % 2); var wdiff = this.options.video.width - newWidth; padAmount = parseInt(wdiff / 2, 10); padAmount += (padAmount % 2); // set pad filter options this.options.video.pad = { x: padAmount, y: 0, w: this.options.video.width, h: this.options.video.height }; this.options.video.size = newWidth + 'x' + this.options.video.height; } else if (newaspect === '4:3') { // assume conversion from 16:9 to 4:3, add padding to top and bottom var newHeight = parseInt(this.options.video.height / (4 / 3), 10); newHeight -= (newHeight % 2); var hdiff = this.options.video.height - newHeight; padAmount = parseInt(hdiff / 2, 10); padAmount += (padAmount % 2); // set pad filter options this.options.video.pad = { x: 0, y: padAmount, w: this.options.video.width, h: this.options.video.height }; this.options.video.size = this.options.video.pad.w + 'x' + newHeight; } } } else { // aspect ratio could not be read from source file return; } }; command.prototype._calculateDimensions = function(data) { // load metadata and prepare size calculations var fixedWidth = /([0-9]+)x\?/.exec(this.options.video.size); var fixedHeight = /\?x([0-9]+)/.exec(this.options.video.size); var percentRatio = /\b([0-9]{1,2})%/.exec(this.options.video.size); var resolution = this.options.keepPixelAspect ? data.video.resolution : data.video.resolutionSquare; var w, h; if (!resolution) { return new Error('could not determine video resolution, check your ffmpeg setup'); } var ratio, ardata; if (fixedWidth && fixedWidth.length > 0) { // calculate height of output if (!resolution.w) { return new Error('could not determine width of source video, aborting execution'); } ratio = resolution.w / parseInt(fixedWidth[1], 10); // if we have an aspect ratio target set, calculate new size using AR if (this.options.video.aspect !== undefined) { ardata = this.toAspectRatio(this.options.video.aspect); if (ardata) { w = parseInt(fixedWidth[1], 10); h = Math.round((w / ardata.x) * ardata.y); } else { // aspect ratio could not be parsed, return error return new Error('could not parse aspect ratio set using withAspect(), aborting execution'); } } else { w = parseInt(fixedWidth[1], 10); h = Math.round(resolution.h / ratio); } } else if (fixedHeight && fixedHeight.length > 0) { // calculate width of output if (!resolution.h) { return new Error('could not determine height of source video, aborting execution'); } ratio = resolution.h / parseInt(fixedHeight[1], 10); // if we have an aspect ratio target set, calculate new size using AR if (this.options.video.aspect !== undefined) { ardata = this.toAspectRatio(this.options.video.aspect); if (ardata) { h = parseInt(fixedHeight[1], 10); w = Math.round((h / ardata.y) * ardata.x); } else { // aspect ratio could not be parsed, return error return new Error('could not parse aspect ratio set using withAspect(), aborting execution'); } } else { w = Math.round(resolution.w / ratio); h = parseInt(fixedHeight[1], 10); } } else if (percentRatio && percentRatio.length > 0) { // calculate both height and width of output if (!resolution.w || !resolution.h) { return new Error('could not determine resolution of source video, aborting execution'); } ratio = parseInt(percentRatio[1], 10) / 100; w = Math.round(resolution.w * ratio); h = Math.round(resolution.h * ratio); } else { return new Error('could not determine type of size string, aborting execution'); } // for video resizing, width and height have to be a multiple of 2 if (w % 2 === 1) { w -= 1; } if (h % 2 === 1) { h -= 1; } this.options.video.size = w + 'x' + h; this.options.video.width = w; this.options.video.height = h; }; command.prototype.calculateDimensions = command.prototype._calculateDimensions; };
JavaScript
0.000001
@@ -1,9 +1,8 @@ -%0A exports @@ -3245,17 +3245,17 @@ %5B0-9%5D%7B1, -2 +3 %7D)%25/.exe
5651c58bf5ea363ff3201fad8ed2ae72e151e894
fix cleverbot
lib/cleverbot.js
lib/cleverbot.js
var story = require('storyboard').mainStory; var config = require('../config'); var cleverbot = null; try { var Cleverbot = require('cleverbot-node'); cleverbot = new Cleverbot; cleverbot.prepare(); story.info('cleverbot', 'Cleverbot loaded and ready.'); } catch (e) { cleverbot = undefined; story.info('cleverbot', 'Unable to load cleverbot-integration.'); story.debug('cleverbot', 'Unable to load cleverbot-integration.', {attach: e}); } module.exports = function (data) { if (cleverbot !== null && config.cleverbot.enabled) { cleverbot.write(data.message.replace('@' + plugged.getSelf().username, '').trim(), function (resp) { story.debug('cleverbot', resp.message); plugged.sendChat(utils.replace(langfile.cleverbot.format, { username: data.username, message: resp.message })); }); } };
JavaScript
0.000786
@@ -301,17 +301,12 @@ t = -undefined +null ;%0A @@ -524,16 +524,43 @@ null && + cleverbot !== undefined && config.
9478c93dcf2968263ae33e23738ea2cab2f56a2a
Use classes by their new names.
lib/container.js
lib/container.js
// Load modules. var path = require('canonical-path') , Factory = require('./patterns/factory') , Constructor = require('./patterns/constructor') , Literal = require('./patterns/literal') , debug = require('debug')('electrolyte'); /** * Manages objects within an application. * * A container creates and manages the set of objects within an application. * Using inversion of control principles, a container automatically instantiates * and assembles these objects. * * Objects are created from a specification. A specification defines the * requirements needed in order to create an object. Such requirements include * the objects required by the object being created. When an object requires * other objects, the required objects will be created prior to the requiring * object, and so on, transitively assembling the complete graph of objects as * necessary. * * @constructor * @api public */ function Container() { this._o = {}; this._sources = {}; this._order = []; this._expose = undefined; this._resolvers = []; this.resolver(require('./resolvers/id')()); } /** * Create an object. * * Creates an object from the specifications registered with the container. * When the object being created requires other objects, tthe required will * automatically be created and injected into the requiring object. In this * way, complex graphs of objects can be created in a single single line of * code, eliminating extraneous boilerplate. * * A specification can declare an object to be a singleton. In such cases, only * one instance of the object will be created. Subsequent calls to create the * object will return the singleton instance. * * Examples: * * var foo = IoC.create('foo'); * * var boop = IoC.create('beep/boop'); * * @param {string} id - The id of the object to create. * @param {Spec} [parent] - (private) The parent specification requiring the object. * @returns {object} * @public */ Container.prototype.create = function(id, parent) { if (parent && id[0] == '.') { // resolve relative component ID id = path.join(path.dirname(parent.id), id); } // special modules switch (id) { case '$container': return this; } id = this.resolve(id, parent && parent.id); var comp = this._o[id]; if (!comp) { // No component is registered with the given ID. Attempt to register the // component by loading its corresponding module. this._loadModule(id); } comp = this._o[id]; if (!comp) { // After attemting auto-loading, the component ID is still unregistered, // which is a terminal condition. throw new Error("Unable to create component '" + id + "'"); } return comp.create(this); } Container.prototype.resolve = function(id, pid) { var resolvers = this._resolvers , fn, rid, i, len; for (i = 0, len = resolvers.length; i < len; ++i) { fn = resolvers[i]; rid = fn(id, pid); if (rid) { return rid; } } // TODO: Give more debugging information here. What was the requiring file? throw new Error("Unable to resolve interface \"" + id + "\""); } Container.prototype.factory = function(id, dependencies, fn, sid) { if (typeof dependencies == 'function') { fn = dependencies; dependencies = []; } debug('register factory %s %s', id, dependencies); // TODO: rename to ReturnedComponent this.register(new Factory(id, dependencies, fn), sid); } Container.prototype.constructor = function(id, dependencies, ctor, sid) { if (typeof dependencies == 'function') { ctor = dependencies; dependencies = []; } debug('register constructor %s %s', id, dependencies); // TODO: rename to ConstructedComponent this.register(new Constructor(id, dependencies, ctor), sid); } Container.prototype.literal = function(id, obj, sid) { debug('register literal %s', id); // TODO: rename to LiteralComponent this.register(new Literal(id, [], obj), sid); } Container.prototype.register = function(comp, sid) { // TODO: Pass sid to constructor (??) comp._sid = sid; this._o[comp.id] = comp; } /** * Utilize a source of components within the container. * * The container creates a components from component sources. Sources are * typically a directory on the file system or a package of components that are * specifically designed to function together. */ Container.prototype.loader = Container.prototype.use = function(prefix, fn, options) { if (typeof prefix == 'function') { options = fn; fn = prefix; prefix = ''; } if (typeof fn != 'function') { throw new Error("Container#use requires a function, was passed a '" + (typeof fn) + "'"); } if (prefix.length && prefix[prefix.length - 1] != '/') { prefix += '/'; } var id = this._order.length; this._sources[id] = { mod: fn, prefix: prefix, options: options }; this._order.unshift(id); } Container.prototype.resolver = function(fn) { this._resolvers.push(fn); } Container.prototype.expose = function(cb) { this._expose = cb; } Container.prototype._loadModule = function(id) { debug('autoload %s', id); var order = this._order , source, prefix, rid, mod; for (var i = 0, len = order.length; i < len; ++i) { source = this._sources[order[i]]; prefix = source.prefix; if (id.indexOf(prefix) !== 0) { continue; } rid = id.slice(prefix.length); mod = source.mod(rid); if (mod) { this._registerModule(id, mod, source.id); break; } } } Container.prototype.iterateOverSources = function(fn) { var order = this._order , sources = this._sources , source, i, len, done; for (i = 0, len = order.length; i < len; ++i) { source = sources[order[i]]; cont = fn(source.mod, source.prefix); if (done === true) { break; } } } Container.prototype._registerModule = function(id, mod, sid) { var dependencies = mod['@require'] || [] , pattern = 'literal' , singleton = mod['@singleton']; if (typeof mod == 'function' && mod['@literal'] !== true) { var name = mod.name || 'anonymous'; if (name[0] == name[0].toUpperCase()) { pattern = 'constructor'; } else { pattern = 'factory'; } } switch (pattern) { case 'factory': this.factory(id, dependencies, mod, sid); break; case 'constructor': this.constructor(id, dependencies, mod, sid); break; case 'literal': this.literal(id, mod, sid); break; } } module.exports = Container;
JavaScript
0
@@ -58,16 +58,20 @@ Factory +Spec = requi @@ -110,16 +110,20 @@ structor +Spec = requi @@ -162,16 +162,20 @@ Literal +Spec = requi @@ -3355,47 +3355,8 @@ s);%0A - // TODO: rename to ReturnedComponent%0A th @@ -3374,24 +3374,28 @@ (new Factory +Spec (id, depende @@ -3645,50 +3645,8 @@ s);%0A - // TODO: rename to ConstructedComponent%0A th @@ -3664,32 +3664,36 @@ (new Constructor +Spec (id, dependencie @@ -3806,46 +3806,8 @@ d);%0A - // TODO: rename to LiteralComponent%0A th @@ -3825,24 +3825,28 @@ (new Literal +Spec (id, %5B%5D, obj
936a7698692037e919442a1cbd693ea63acc7ce2
Fix typo in ShiftDragZoom (caught by @ahocevar)
src/ol/interaction/shiftdragzoom.js
src/ol/interaction/shiftdragzoom.js
// FIXME draw drag box goog.provide('ol.interaction.ShiftDragZoom'); goog.require('ol.Extent'); goog.require('ol.MapBrowserEvent'); goog.require('ol.control.DragBox'); goog.require('ol.interaction.Drag'); /** * @define {number} Hysterisis pixels. */ ol.SHIFT_DRAG_ZOOM_HYSTERESIS_PIXELS = 8; /** * @const {number} */ ol.SHIFT_DRAG_ZOOM_HYSTERESIS_PIXELS_SQUARED = ol.SHIFT_DRAG_ZOOM_HYSTERESIS_PIXELS * ol.SHIFT_DRAG_ZOOM_HYSTERESIS_PIXELS; /** * @constructor * @extends {ol.interaction.Drag} */ ol.interaction.ShiftDragZoom = function() { goog.base(this); /** * @type {ol.control.DragBox} * @private */ this.dragBox_ = null; }; goog.inherits(ol.interaction.ShiftDragZoom, ol.interaction.Drag); /** * @inheritDoc */ ol.interaction.ShiftDragZoom.prototype.handleDragEnd = function(mapBrowserEvent) { this.dragBox_.setMap(null); this.dragBox = null; if (this.deltaX * this.deltaX + this.deltaY * this.deltaY >= ol.SHIFT_DRAG_ZOOM_HYSTERESIS_PIXELS_SQUARED) { var map = mapBrowserEvent.map; var extent = ol.Extent.boundingExtent( this.startCoordinate, mapBrowserEvent.getCoordinate()); map.fitExtent(extent); } }; /** * @inheritDoc */ ol.interaction.ShiftDragZoom.prototype.handleDragStart = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; if (browserEvent.isMouseActionButton() && browserEvent.shiftKey) { this.dragBox_ = new ol.control.DragBox({ map: mapBrowserEvent.map, startCoordinate: this.startCoordinate }); return true; } else { return false; } };
JavaScript
0
@@ -887,16 +887,17 @@ .dragBox +_ = null;
c2a0a9b39e0177e0cd3abcb2aa53abe6220c5f6d
Fix raw:outgoing event for </stream>
lib/websocket.js
lib/websocket.js
var WildEmitter = require('wildemitter'), _ = require('lodash'), async = require('async'), stanza = require('./stanza/stanza'), Stream = require('./stanza/stream').Stream, Message = require('./stanza/message').Message, Presence = require('./stanza/presence').Presence, Iq = require('./stanza/iq').Iq, StreamManagement = require('./sm').StreamManagement, uuid = require('node-uuid'); function WSConnection() { var self = this; WildEmitter.call(this); self.sm = new StreamManagement(self); self.sendQueue = async.queue(function (data, cb) { if (self.conn) { self.emit('raw:outgoing', data); self.sm.track(data); if (typeof data !== 'string') { data = data.toString(); } self.conn.send(data); } cb(); }, 1); function wrap(data) { var result = [self.streamStart, data, self.streamEnd].join(''); return result; } function parse(data) { return (self.parser.parseFromString(data, 'application/xml')).childNodes[0]; } self.on('connected', function () { self.send([ '<stream:stream', 'xmlns:stream="http://etherx.jabber.org/streams"', 'xmlns="jabber:client"', 'version="' + (self.config.version || '1.0') + '"', 'xml:lang="' + (self.config.lang || 'en') + '"', 'to="' + self.config.server + '">' ].join(' ')); }); self.on('raw:incoming', function (data) { var streamData, ended; data = data.trim(); data = data.replace(/^(\s*<\?.*\?>\s*)*/, ''); if (data.match(self.streamEnd)) { return self.disconnect(); } else if (self.hasStream) { try { streamData = new Stream({}, parse(wrap(data))); } catch (e) { return self.disconnect(); } } else { // Inspect start of stream element to get NS prefix name var parts = data.match(/^<(\S+:)?(\S+) /); self.streamStart = data; self.streamEnd = '</' + (parts[1] || '') + parts[2] + '>'; ended = false; try { streamData = new Stream({}, parse(data + self.streamEnd)); } catch (e) { try { streamData = new Stream({}, parse(data)); ended = true; } catch (e2) { return self.disconnect(); } } self.hasStream = true; self.stream = streamData; self.emit('stream:start', streamData); } _.each(streamData._extensions, function (stanzaObj) { if (!stanzaObj.lang) { stanzaObj.lang = self.stream.lang; } if (stanzaObj._name === 'message' || stanzaObj._name === 'presence' || stanzaObj._name === 'iq') { self.sm.handle(stanzaObj); self.emit('stanza', stanzaObj); } self.emit(stanzaObj._eventname || stanzaObj._name, stanzaObj); self.emit('stream:data', stanzaObj); if (stanzaObj.id) { self.emit('id:' + stanzaObj.id, stanzaObj); } }); if (ended) { self.emit('stream:end'); } }); } WSConnection.prototype = Object.create(WildEmitter.prototype, { constructor: { value: WSConnection } }); WSConnection.prototype.connect = function (opts) { var self = this; self.config = opts; self.hasStream = false; self.streamStart = '<stream:stream xmlns:stream="http://etherx.jabber.org/streams">'; self.streamEnd = '</stream:stream>'; self.parser = new DOMParser(); self.serializer = new XMLSerializer(); self.conn = new WebSocket(opts.wsURL, 'xmpp'); self.conn.onopen = function () { self.emit('connected', self); }; self.conn.onclose = function () { self.emit('disconnected', self); }; self.conn.onmessage = function (wsMsg) { self.emit('raw:incoming', wsMsg.data); }; }; WSConnection.prototype.disconnect = function () { if (this.conn) { if (this.hasStream) { this.conn.send('</stream:stream>') this.emit('stream:end'); } this.hasStream = false; this.conn.close(); this.stream = undefined; this.conn = undefined; } }; WSConnection.prototype.restart = function () { var self = this; self.hasStream = false; self.send([ '<stream:stream', 'xmlns:stream="http://etherx.jabber.org/streams"', 'xmlns="jabber:client"', 'version="' + (self.config.version || '1.0') + '"', 'xml:lang="' + (self.config.lang || 'en') + '"', 'to="' + self.config.server + '">' ].join(' ')); }; WSConnection.prototype.send = function (data) { this.sendQueue.push(data); }; exports.WSConnection = WSConnection;
JavaScript
0.000002
@@ -4359,16 +4359,76 @@ tream%3E') +;%0A this.emit('raw:outgoing', '%3C/stream:stream%3E'); %0A
392b532f2eb18a6c1b4725147d87b9b791577393
Allow daemonize to pass arbitrary arguments to child.
lib/daemonize.js
lib/daemonize.js
// Copyright (c) 2012 Kuba Niegowski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. "use strict"; var fs = require("fs"), path = require("path"), util = require("util"), args = require("./args"), constants = require("./constants"), spawn = require("child_process").spawn, EventEmitter = require("events").EventEmitter; exports.setup = function(options) { return new Daemon(options); }; var Daemon = function(options) { EventEmitter.call(this); if (!options.main) throw new Error("Expected 'main' option for daemonize"); var dir = path.dirname(module.parent.filename), main = path.resolve(dir, options.main), name = options.name || path.basename(main, ".js"); if (!this._isFile(main)) throw new Error("Can't find daemon main module: '" + main + "'"); // normalize options this._options = {}; this._options.main = main; this._options.name = name; this._options.pidfile = options.pidfile ? path.resolve(dir, options.pidfile) : path.join("/var/run", name + ".pid"); this._options.user = options.user || ""; this._options.group = options.group || ""; this._stopTimeout = options.stopTimeout || 2000; this._childExitHandler = null; this._childStdoutCloseHandler = null; this._childStdoutCloseTimer = null; if (!options.silent) this._bindConsole(); }; util.inherits(Daemon, EventEmitter); Daemon.prototype.start = function() { // make sure daemon is not running var pid = this._sendSignal(this._getpid()); if (pid) { this.emit("running", pid); return this; } this.emit("starting"); // check whether we have right to write to pid file var err = this._savepid(""); if (err) { this.emit("error", new Error("Failed to write pidfile (" + err + ")")); return this; } // spawn child process var child = spawn(process.execPath, [ __dirname + "/wrapper.js" ].concat(args.make(this._options)) ); pid = child.pid; // save pid this._savepid(pid); // redirect child's stdout/stderr child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); // wrapper.js will exit with special exit codes child.once("exit", this._childExitHandler = function(code, signal) { child.stdout.removeListener("close", this._childStdoutCloseHandler); clearTimeout(this._childStdoutCloseTimer); this.emit("error", new Error( code > 1 ? constants.findExitCode(code) : "Module '" + this._options.main + "' stopped unexpected" )); }.bind(this)); // check if it is still running when child's stdout closes child.stdout.once("close", this._childStdoutCloseHandler = function() { // check it in 100ms in case this is child's exit this._childStdoutCloseTimer = setTimeout(function() { child.removeListener("exit", this._childExitHandler); if (this._sendSignal(pid)) { this.emit("started", pid); } else { this.emit("error", new Error("Daemon failed to start")); } }.bind(this), 100); }.bind(this)); return this; }; Daemon.prototype.stop = function() { return this._kill(["SIGTERM"]); }; Daemon.prototype.kill = function() { return this._kill(["SIGTERM", "SIGKILL"]); }; Daemon.prototype.status = function() { return this._sendSignal(this._getpid()); }; Daemon.prototype.sendSignal = function(signal) { return this._sendSignal(this._getpid(), signal); }; Daemon.prototype._getpid = function() { try { return parseInt(fs.readFileSync(this._options.pidfile)); } catch (err) { } return 0; }; Daemon.prototype._savepid = function(pid) { try { fs.writeFileSync(this._options.pidfile, pid + "\n"); } catch (ex) { return ex.code; } return ""; }; Daemon.prototype._sendSignal = function(pid, signal) { if (!pid) return 0; try { process.kill(pid, signal || 0); return pid; } catch (err) { } return 0; }; Daemon.prototype._kill = function(signals) { var pid = this._sendSignal(this._getpid()); if (!pid) { this.emit("notrunning"); return this; } this.emit("stopping"); this._tryKill(pid, signals, function(pid) { // try to remove pid file try { fs.unlinkSync(this._options.pidfile); } catch (ex) {} this.emit("stopped", pid); }.bind(this)); return this; }; Daemon.prototype._tryKill = function(pid, signals, callback) { if (!this._sendSignal(pid, signals.length > 1 ? signals.shift() : signals[0])) { if (callback) callback(pid); return true; } setTimeout(this._tryKill.bind(this, pid, signals, callback), this._stopTimeout); return false; }; Daemon.prototype._isFile = function(path) { try { var stat = fs.statSync(path); if (stat && !stat.isDirectory()) return true; } catch (err) { } return false; }; Daemon.prototype._bindConsole = function() { this .on("starting", function() { console.log("Starting daemon..."); }) .on("started", function(pid) { console.log("Daemon started. PID: " + pid); }) .on("stopping", function() { console.log("Stopping daemon..."); }) .on("stopped", function(pid) { console.log("Daemon stopped."); }) .on("running", function(pid) { console.log("Daemon already running. PID: " + pid); }) .on("notrunning", function() { console.log("Daemon is not running"); }) .on("error", function(err) { console.log("Daemon failed to start: " + err.message); }); };
JavaScript
0
@@ -1920,16 +1920,195 @@ s = %7B%7D;%0A + %0A // pass all basic type arguments to child%0A for (var arg in options)%0A if (!(options%5Barg%5D instanceof Object))%0A this._options%5Barg%5D = options%5Barg%5D;%0A %0A this
5b479ad198bb089ef45ea3156988c4f8b3149ba1
fix selected projects url
app/controllers/home.js
app/controllers/home.js
/*! * Module dependencies. */ var mongoose = require('mongoose'), Feature = mongoose.model('Feature'); /** * Home */ exports.index = function (req, res) { if(req.isAuthenticated()) { res.render('layouts/default', { title: 'Mapas Coletivos', user: req.user ? JSON.stringify(req.user) : 'null' }) } else { res.render('home/landing', { selectedProjects: [ { title: 'Rio dos Jogos', img: 'http://alpha.mapascoletivos.com.br/uploads/images/376_1_1371165797.jpg', url: 'http://alpha.mapascoletivos.com.br/maps/5318c652cb160eaf6d30103a/', description: 'Jornalismo Colaborativo: cuide do Rio!' }, { title: 'São Paulo sem frescura', img: 'http://alpha.mapascoletivos.com.br/uploads/images/139_1_1328364227.jpg', url: 'http://alpha.mapascoletivos.com.br/maps/5318c652cb160eaf6d300f60/', description: 'Casas, padarias, botecos, barbearias, lojinhas, qualquer tipo de estabelecimento com um charme de antigamente, que mantiveram suas peculiaridades, sem entrar na onda da "modernização".' }, { title: 'Trianon Acessível', img: 'http://alpha.mapascoletivos.com.br/uploads/images/396_1_1384554991.jpg', url: 'http://alpha.mapascoletivos.com.br/maps/5318c652cb160eaf6d30104e/', description: 'Observar a situação das calçadas e também em estabelecimentos comerciais no entorno, o excesso de postes nas esquinas, rampas de acesso e vagas para deficientes.' }, { title: 'Cantos BA', img: 'http://farm3.staticflickr.com/2620/3977617811_ced60d34e9_o.jpg', url: 'http://alpha.mapascoletivos.com.br/maps/5318c652cb160eaf6d301043/', description: '' }, { title: 'Vídeos Ambientais', img: '/img/selected-projects/53235a26cc24363c3b52cbcc.png', url: 'http://alpha.mapascoletivos.com.br/layers/53235a26cc24363c3b52cbcc/', description: '' }, { title: 'Centros de adoção de animais', img: 'http://alpha.mapascoletivos.com.br/uploads/images/300_1_1350313222.jpg', url: 'http://alpha.mapascoletivos.com.br/maps/5318c652cb160eaf6d300ff4/', description: 'Onde adotar um bichinho de estimação (não se esqueça, não compre, adote, tem muitos cães e gatos esperando um dono que os ame)' } ] }) } } exports.about = function(req, res) { res.render('home/about'); } exports.tutorial = function(req, res) { res.render('home/tutorial'); } exports.terms = function(req, res) { res.render('home/terms'); } exports.app = function(req, res) { res.render('layouts/default', { title: 'Mapas Coletivos' }); } /** * Explore */ exports.explore = function (req, res) { var page = (req.param('page') > 0 ? req.param('page') : 1) - 1 var perPage = 30 var options = { perPage: perPage, page: page } Feature.list(options, function(err, features) { if (err) return res.render('500') Feature.count().exec(function (err, count) { res.render('home/explore', { title: 'Features', features: features, page: page + 1, pages: Math.ceil(count / perPage) }) }) }) }
JavaScript
0.000001
@@ -419,37 +419,35 @@ %09%09%09img: 'http:// -alpha +www .mapascoletivos. @@ -501,37 +501,35 @@ %09%09%09url: 'http:// -alpha +www .mapascoletivos. @@ -688,37 +688,35 @@ %09%09%09img: 'http:// -alpha +www .mapascoletivos. @@ -770,37 +770,35 @@ %09%09%09url: 'http:// -alpha +www .mapascoletivos. @@ -1098,37 +1098,35 @@ %09%09%09img: 'http:// -alpha +www .mapascoletivos. @@ -1180,37 +1180,35 @@ %09%09%09url: 'http:// -alpha +www .mapascoletivos. @@ -1553,37 +1553,35 @@ %09%09%09url: 'http:// -alpha +www .mapascoletivos. @@ -1762,37 +1762,35 @@ %09%09%09url: 'http:// -alpha +www .mapascoletivos. @@ -1919,37 +1919,35 @@ %09%09%09img: 'http:// -alpha +www .mapascoletivos. @@ -2013,13 +2013,11 @@ p:// -alpha +www .map
a5e8aed842c30c349da640c8fd48f14a1399033b
increase compatibility with BB.sync: use options.type for method type if available, fall back to GET (fixes gh-41)
lib/dom-utils.js
lib/dom-utils.js
// Usage: // utils.matchesSelector(div, '.something'); utils.matchesSelector = (function() { if (typeof document === 'undefined') return; // Suffix. var sfx = 'MatchesSelector'; var tag = document.createElement('div'); var name; ['matches', 'webkit' + sfx, 'moz' + sfx, 'ms' + sfx].some(function(item) { var valid = (item in tag); name = item; return valid; }); if (!name) { throw new Error('Element#matches is not supported'); } return function(element, selector) { return element[name](selector); }; })(); // Make AJAX request to the server. // Usage: // var callback = function(error, data) {console.log('Done.', error, data);}; // ajax({url: 'url', method: 'PATCH', data: 'data'}, callback); utils.ajax = (function() { var xmlRe = /^(?:application|text)\/xml/; var jsonRe = /^application\/json/; var getData = function(accepts, xhr) { if (accepts == null) accepts = xhr.getResponseHeader('content-type'); if (xmlRe.test(accepts)) { return xhr.responseXML; } else if (jsonRe.test(accepts)) { return JSON.parse(xhr.responseText); } else { return xhr.responseText; } }; var isValid = function(xhr) { return (xhr.status >= 200 && xhr.status < 300) || (xhr.status === 304) || (xhr.status === 0 && window.location.protocol === 'file:') }; var end = function(xhr, options, deferred) { return function() { if (xhr.readyState !== 4) return; var status = xhr.status; var data = getData(options.headers && options.headers.Accept, xhr); // Check for validity. if (isValid(xhr)) { if (options.success) options.success(data); if (deferred) deferred.resolve(data); } else { var error = new Error('Server responded with a status of ' + status); if (options.error) options.error(xhr, status, error); if (deferred) deferred.reject(xhr); } } }; return function(options) { if (options == null) throw new Error('You must provide options'); if (options.method == null) options.method = 'GET'; var xhr = new XMLHttpRequest(); var deferred = Backbone.Deferred && Backbone.Deferred(); if (options.credentials) options.withCredentials = true; xhr.addEventListener('readystatechange', end(xhr, options, deferred)); xhr.open(options.method, options.url, true); if (options.headers) for (var key in options.headers) { xhr.setRequestHeader(key, options.headers[key]); } xhr.send(options.data); return deferred ? deferred.promise : undefined; }; })();
JavaScript
0
@@ -2085,16 +2085,32 @@ method = + options.type %7C%7C 'GET';%0A
9ff28d84c903e04db9b33b232769e353969c6a9c
Fix gulpExeca
gulp/run.js
gulp/run.js
'use strict' const { promisify } = require('util') const Nodemon = require('nodemon') // eslint-disable-next-line import/no-internal-modules const execa = require('gulp-shared-tasks/dist/exec') const EXAMPLE_PATH = `${__dirname}/../examples/index.js` const DIST_PATH = `${__dirname}/../dist` // We use this instead of requiring the application to test the CLI const runProd = () => execa('node', ['../bin/autoserver.js'], { cwd: 'examples' }) // eslint-disable-next-line fp/no-mutation runProd.description = 'Run an example production server' const runDev = () => startNodemon(NODEMON_CONFIG) // eslint-disable-next-line fp/no-mutation runDev.description = 'Start an example dev server' const runDebug = () => startNodemon(DEBUG_NODEMON_CONFIG) // eslint-disable-next-line fp/no-mutation runDebug.description = 'Start an example dev server in debug mode' const startNodemon = async function(config) { const nodemon = new Nodemon(config) // Otherwise Nodemon's log does not appear // eslint-disable-next-line no-restricted-globals nodemon.on('log', ({ colour }) => global.console.log(colour)) await promisify(nodemon.on.bind(nodemon))('start') } const NODEMON_CONFIG = { script: EXAMPLE_PATH, nodeArgs: ['--inspect', '--stack-trace-limit=20'], env: { NODE_ENV: 'dev' }, watch: DIST_PATH, delay: 100, quiet: true, } const DEBUG_NODEMON_CONFIG = { ...NODEMON_CONFIG, nodeArgs: ['--inspect-brk', '--stack-trace-limit=20'], } module.exports = { runProd, runDev, runDebug, }
JavaScript
0.000003
@@ -141,22 +141,25 @@ es%0Aconst + %7B exec -a + %7D = requi @@ -388,17 +388,16 @@ %3E%0A exec -a ('node',
9bf3aa02fe28f7d6a3d61c55abdf5ed966ec7a44
Add watcher
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var concat = require('gulp-concat'); gulp.task('concat', function() { return gulp.src('src/**/*.js') .pipe(concat('img-src-ondemand.js')) .pipe(gulp.dest('dist')); });
JavaScript
0.000001
@@ -201,8 +201,121 @@ ));%0A%7D);%0A +%0Agulp.task('watch', function() %7B%0A gulp.watch('src/**/*.js', %5B'concat'%5D);%0A%7D);%0A%0Agulp.task('default', %5B'concat'%5D);%0A
a637fb1dbb4d25a747c0318adbb049ea39fa98a7
Update Gulpfile to only minify JavaScript bundle for deployments
gulpfile.js
gulpfile.js
'use strict'; var beep = require( 'beepbeep' ), browserify = require( 'browserify' ), concat = require( 'gulp-concat' ), deploy = require( 'gulp-gh-pages' ), es = require( 'event-stream' ), gulp = require( 'gulp' ), gutil = require( 'gulp-util' ), jshint = require('gulp-jshint'), reactify = require( 'reactify' ), rename = require( 'gulp-rename' ), sass = require( 'gulp-sass' ), source = require( 'vinyl-source-stream' ), streamify = require( 'gulp-streamify' ), uglify = require( 'gulp-uglify' ); var config = { cssPath: './stylesheets/css', sassPath: './stylesheets/scss', jsPath: './js', buildPath: './build' }; gulp.task( 'default', [ 'watch', 'build' ] ); gulp.task( 'build', [ 'js', 'css', 'public' ] ); gulp.task( 'watch', function() { gulp.watch( './index.html', [ 'index' ] ); gulp.watch( config.sassPath + '/*.scss', [ 'css' ] ); gulp.watch( config.jsPath + '/**/*.js', [ 'js' ] ); gulp.watch( config.jsPath + '/**/*.jsx', [ 'js' ] ); } ); // Copy assets from /public into the root of the build directory gulp.task( 'public', function() { gulp.src( './public/*' ) .pipe( gulp.dest('./build' ) ); } ); gulp.task( 'css', function () { var cssFiles = gulp.src( config.cssPath + '/*.css' ), sassFiles = gulp.src( config.sassPath + '/*.scss' ).pipe( sass( { style: 'compressed' } ) ); return es.concat( cssFiles, sassFiles ) .pipe( concat( 'style.css' ) ) .pipe( gulp.dest( './build/stylesheets' ) ); }); gulp.task( 'jshint', function () { // TODO: Figure out how to use jshint to check JSX files as well gulp.src( [ './js/**/*.js', './gulpfile.js' ] ) .pipe( jshint() ) .pipe( jshint.reporter( 'default' ) ); } ); gulp.task( 'js', function() { var mainPath = config.jsPath + '/main.js'; browserify({ entries: mainPath, extensions: [ '.jsx' ] } ) .transform( reactify ) .bundle() .on('error', function( error ) { beep(); gutil.log( error.message ); } ) .pipe( source( mainPath ) ) .pipe( streamify( uglify() ) ) .pipe( rename( 'bundle.js' ) ) .pipe( gulp.dest( config.buildPath + '/js' ) ); } ); gulp.task( 'deploy', [ 'build' ], function () { return gulp.src( './build/**/*' ) .pipe( deploy() ); });
JavaScript
0
@@ -1961,16 +1961,39 @@ %09%09.pipe( + gutil.env.production ? streami @@ -2006,16 +2006,31 @@ lify() ) + : gutil.noop() )%0A%09%09.pi @@ -2117,55 +2117,271 @@ );%0A%0A -gulp.task( 'deploy', %5B 'build' %5D, function () %7B +// Run %60gulp deploy --production%60 to deploy to Github Pages%0Agulp.task( 'deploy', %5B 'build' %5D, function () %7B%0A%09if ( ! gutil.env.production ) %7B%0A%09%09throw new Error( 'gulp deploy must be run with the --production flag to ensure the JavaScript bundle is minified' );%0A%09%7D%0A %0A%09re
70b5335e2c99790a538e92944d6ab0637509b81f
Fix bug EVENT.LOC_CHANGED not defined
gulpfile.js
gulpfile.js
var gulp = require('gulp') , merge = require('event-stream').merge , series = require('stream-series') , map = require('map-stream') , $ = require('gulp-load-plugins')() function pipe(src, transforms, dest) { if (typeof transforms === 'string') { dest = transforms transforms = null } var stream = gulp.src(src) transforms && transforms.forEach(function(transform) { stream = stream.pipe(transform) }) if (dest) stream = stream.pipe(gulp.dest(dest)) return stream } function html2js(template) { return map(escape) function escape(file, cb) { var path = $.util.replaceExtension(file.path, '.js') , content = file.contents.toString() , escaped = content.replace(/\\/g, "\\\\") .replace(/'/g, "\\'") .replace(/\r?\n/g, "\\n' +\n '") , body = template.replace('$$', escaped) file.path = path file.contents = new Buffer(body) cb(null, file) } } function buildJs(additions, ctx) { var src = additions.concat([ './src/adapter.github.js', './src/view.help.js', './src/view.error.js', './src/view.tree.js', './src/view.options.js', './src/util.location.js', './src/util.module.js', './src/util.async.js', './tmp/template.js', './src/constants.js', './src/octotree.js', ]) return pipe(src, [ $.concat('octotree.js'), $.preprocess({ context: ctx }) ], './tmp') } function buildTemplate(ctx) { return pipe('./src/template.html', [ $.preprocess({ context: ctx }), html2js('const TEMPLATE = \'$$\'') ], './tmp') } gulp.task('clean', function() { return pipe('./tmp', [$.clean()]) }) gulp.task('css', function() { return pipe('./src/octotree.less', [$.less(), $.autoprefixer({ cascade: true })], './tmp') }) gulp.task('default', function(cb) { $.runSequence('clean', 'css', 'chrome', 'opera', 'safari', 'firefox', cb) gulp.watch(['./src/**/*'], ['default']) }) // Chrome gulp.task('chrome:template', function() { return buildTemplate({ CHROME: true }) }) gulp.task('chrome:js', ['chrome:template'], function() { return buildJs(['./src/chrome/storage.js'], { CHROME: true }) }) gulp.task('chrome', ['chrome:js'], function() { return merge( pipe('./icons/**/*', './tmp/chrome/icons'), pipe(['./libs/**/*', './tmp/octotree.*', './src/chrome/**/*', '!./src/chrome/storage.js'], './tmp/chrome/') ) }) // Opera gulp.task('opera', ['chrome'], function() { return pipe('./tmp/chrome/**/*', './tmp/opera') }) // Safari gulp.task('safari:template', function() { return buildTemplate({ SAFARI: true }) }) gulp.task('safari:js', ['safari:template'], function() { return buildJs(['./src/safari/storage.js'], { SAFARI: true }) }) gulp.task('safari', ['safari:js'], function() { return merge( pipe('./icons/**/*', './tmp/safari/octotree.safariextension/icons'), pipe(['./libs/**/*', './tmp/octotree.js', './tmp/octotree.css', './src/safari/**/*', '!./src/safari/storage.js'], './tmp/safari/octotree.safariextension/') ) }) // Firefox gulp.task('firefox:template', function() { return buildTemplate({ FIREFOX: true }) }) gulp.task('firefox:js', ['firefox:template'], function() { return buildJs(['./src/firefox/storage.js'], { FIREFOX: true }) }) gulp.task('firefox', ['firefox:js'], function() { return merge( pipe('./icons/**/*', './tmp/firefox/data/icons'), pipe(['./libs/**/*', './tmp/octotree.js', './tmp/octotree.css'], './tmp/firefox/data'), pipe(['./src/firefox/firefox.js'], './tmp/firefox/lib'), pipe('./src/firefox/package.json', './tmp/firefox') ) })
JavaScript
0.000001
@@ -1041,16 +1041,67 @@ oncat(%5B%0A + './tmp/template.js',%0A './src/constants.js',%0A './s @@ -1320,59 +1320,8 @@ s',%0A - './tmp/template.js',%0A './src/constants.js',%0A
93f4f967aecf0ea59e3f8a5637965cd952a0389d
Reformat the gulpfile
gulpfile.js
gulpfile.js
/*jshint node: true, globalstrict: true */ 'use strict'; // Imports // ------------------------------------------------------------------------------------------------- var gulp = require('gulp'); var to5 = require('gulp-6to5'); // Tasks // ================================================================================================= // `gulp build` or `gulp` // ------------------------------------------------------------------------------------------------- gulp.task('default', ['build']); gulp.task('build', ['scripts']); // `gulp scripts` // ------------------------------------------------------------------------------------------------- gulp.task('scripts', ['scripts:es6', 'scripts:es5']); gulp.task('scripts:es6', function () { return gulp.src('source/**/*.js') .pipe(gulp.dest('dist')) ; }); gulp.task('scripts:es5', function () { return gulp.src('source/n.js') .pipe(to5({modules: '6-to-library'})) .pipe(gulp.dest('dist.es5')) ; });
JavaScript
0
@@ -36,13 +36,28 @@ true +, esnext: false */%0A -' +%22 use @@ -62,17 +62,17 @@ e strict -' +%22 ;%0A%0A%0A// I @@ -92,98 +92,8 @@ ---- ------------------------------------------------------------------------------------------- %0A%0Ava @@ -113,14 +113,14 @@ ire( -' +%22 gulp -' +%22 );%0Av @@ -136,17 +136,17 @@ require( -' +%22 gulp-6to @@ -150,232 +150,43 @@ 6to5 -' +%22 );%0A%0A%0A -%0A%0A// Tasks%0A// =================================================================================================%0A%0A%0A// %60gulp build%60 or %60gulp%60%0A// --------------------------------------------------------------------------- +// %60gulp build%60 or %60gulp%60%0A// ---- @@ -219,27 +219,27 @@ ask( -' +%22 default -', %5B' +%22, %5B%22 build -' +%22 %5D);%0A @@ -252,27 +252,27 @@ ask( -' +%22 build -', %5B' +%22, %5B%22 scripts -' +%22 %5D);%0A @@ -312,91 +312,37 @@ ---- ------------------------------------------------------------------------------------ +%0A%0Avar source = %22source/n.js%22; %0A%0Agu @@ -353,21 +353,21 @@ ask( -' +%22 scripts -', %5B' +%22, %5B%22 scri @@ -377,12 +377,12 @@ :es6 -', ' +%22, %22 scri @@ -388,17 +388,17 @@ ipts:es5 -' +%22 %5D);%0A%0Agul @@ -396,33 +396,33 @@ %22%5D);%0A%0Agulp.task( -' +%22 scripts:es6', fu @@ -416,17 +416,17 @@ ipts:es6 -' +%22 , functi @@ -425,34 +425,32 @@ , function () %7B%0A - return gulp.sr @@ -450,35 +450,26 @@ gulp +%0A .src( -' source -/**/*.js')%0A +)%0A @@ -488,27 +488,25 @@ est( -' +%22 dist -' +%22 ))%0A - ;%0A + %7D);%0A @@ -516,17 +516,17 @@ lp.task( -' +%22 scripts: @@ -528,17 +528,17 @@ ipts:es5 -' +%22 , functi @@ -545,18 +545,16 @@ on () %7B%0A - return @@ -562,32 +562,26 @@ gulp +%0A .src( -' source -/n.js')%0A +)%0A @@ -600,17 +600,17 @@ odules: -' +%22 6-to-lib @@ -617,17 +617,13 @@ rary -' +%22 %7D))%0A - @@ -642,17 +642,17 @@ est( -' +%22 dist.es5 '))%0A @@ -651,22 +651,20 @@ .es5 -' +%22 ))%0A - ;%0A + %7D);%0A
80050f80aa5a123356bcbd023076eebc3c7173fd
Fix how benchmark spawns oql.js subprocess
benchmark/node/benchmark.js
benchmark/node/benchmark.js
const randomString = require('random-string'); const _ = require('lodash'); const async = require('async'); const gemfire = require('../..'); gemfire.configure('xml/ExampleClient.xml'); const cache = gemfire.getCache(); const region = cache.getRegion("exampleRegion"); console.log("node version " + process.version); console.log("node-gemfire version " + gemfire.version); console.log("GemFire version " + gemfire.gemfireVersion); function smokeTest(callback) { region.put('smoke', { test: 'value' }, function(error){ if(error) { throw error; } region.get('smoke', function(error, value) { if(error) { throw error; } if(JSON.stringify(value) !== JSON.stringify({ test: 'value' })) { throw "Smoke test failed."; } callback(); }); }); } var keyOptions = { length: 8, numeric: true, letter: true, special: false }; var valueOptions = { length: 15 * 1024, numeric: true, letter: true, special: true }; var randomObject = require('../data/randomObject.json'); var stringValue = randomString(valueOptions); var gemfireKey = randomString(keyOptions); var suffix = 0; function benchmark(numberOfPuts, title, functionToTest, callback) { region.clear(); var start = process.hrtime(); async.series([ function(next) { functionToTest(numberOfPuts, next); }, function(next) { const duration = process.hrtime(start); const nanoseconds = duration[0] * 1e9 + duration[1]; const microseconds = nanoseconds / 1e3; const seconds = (microseconds / 1e6); const putsPerSecond = Math.round(numberOfPuts / seconds); const usecPerPut = Math.round(microseconds / numberOfPuts); console.log( title + " put:" , + usecPerPut + " usec/op " + putsPerSecond + " ops/sec" ); next(); } ], callback); } function putNValues(value) { return function(iterationCount, callback) { async.times(iterationCount, function(n, done) { suffix++; region.put(gemfireKey + suffix, value, function(error) { if(error) { throw error; } done(); }); }, function(error, results) { callback(); }); }; } function benchmarkStrings(numberOfPuts, callback){ return benchmark(numberOfPuts, "String", putNValues(stringValue), callback); } function benchmarkSimpleObjects(numberOfPuts, callback){ return benchmark(numberOfPuts, "Simple object", putNValues({ foo: stringValue }), callback); } function benchmarkComplexObjects(numberOfPuts, callback){ return benchmark(numberOfPuts, "Complex object", putNValues(randomObject), callback); } async.series([ function(next){ smokeTest(next); }, function(next){ benchmarkStrings(10000, next); }, function(next){ benchmarkSimpleObjects(1000, next); }, function(next){ benchmarkComplexObjects(100, next); } ], function(){ require('./oql.js'); });
JavaScript
0.002526
@@ -100,16 +100,106 @@ async'); +%0Aconst exec = require(%22child_process%22).exec;%0Aconst spawn = require(%22child_process%22).spawn; %0A%0Aconst @@ -2948,11 +2948,11 @@ ); %7D -%0A%5D, +,%0A fun @@ -2961,34 +2961,86 @@ ion( -)%7B%0A require('./oql.js');%0A%7D +next)%7B spawn(%22node%22, %5B%22benchmark/node/oql.js%22%5D, %7Bstdio: %22inherit%22%7D, next); %7D%0A%5D );%0A +%0A
7c52422a46c92c85d6ddb482cce389d5fa80e5ba
Call completion callback in test:run
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var tsc = require('gulp-tsc'); var tape = require('gulp-tape'); var tapSpec = require('tap-spec'); var del = require('del'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src(['test/**/*.ts']) .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })); }); gulp.task("test", ["test:build"], function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })); });
JavaScript
0
@@ -627,24 +627,46 @@ ec()%0A %7D)) +%0A .on('end', done); ;%0A%7D);%0A%0Agulp.
df11fc4460fd2dd7bac3081ec21863f6d230b5c0
Call build command rather than rebuild
gulpfile.js
gulpfile.js
const DIST_PATH = "./.dist"; var gulp = require("gulp"); var hb = require("gulp-handlebars"); var deploy = require('gulp-gh-pages'); var clean = require('gulp-clean'); var wrap = require('gulp-wrap'); var declare = require('gulp-declare'); var concat = require('gulp-concat'); var runSequence = require('gulp-run-sequence'); gulp.task("default", ["deploy"]); gulp.task("clean", function() { gulp.src(DIST_PATH, {read:false}) .pipe(clean()); }); gulp.task('pages', function() { gulp.src('index.html') .pipe(gulp.dest('.dist')); }); gulp.task("templates", function() { gulp.src("templates/*.handlebars") .pipe(hb({ handlebars: require('handlebars') })) .pipe(wrap('Handlebars.template(<%= contents %>)')) .pipe(declare({ namespace: 'MyApp.templates', noRedeclare: true, // Avoid duplicate declarations })) .pipe(concat('templates.js')) .pipe(gulp.dest(DIST_PATH+"/templates/")); }); gulp.task("styles", function() { gulp.src("stylesheets/*") .pipe(gulp.dest(DIST_PATH+"/stylesheets/")); }); gulp.task("scripts", function () { gulp.src("js/*.js").pipe(gulp.dest(DIST_PATH+"/js/")); }); gulp.task("media", function() { gulp.src("media/**/*").pipe(gulp.dest(DIST_PATH+"/media/")); }); gulp.task("dependencies", function() { var nodeModules = [ "jquery/dist/jquery.min.js", "firebase/firebase.js", "geofire/dist/geofire.min.js", "handlebars/dist/handlebars.runtime.min.js" ]; for (var i = 0; i < nodeModules.length; i++) { var modPath = "node_modules/"+nodeModules[i]; gulp.src(modPath) .pipe(gulp.dest(DIST_PATH+"/dependencies/")); } }); gulp.task("build", ["pages", "templates", "styles", "scripts", "media", "dependencies"]); /** * Push build to gh-pages */ gulp.task('deploy', ["rebuild"], function () { return gulp.src(DIST_PATH+"/**/*") .pipe(deploy()) });
JavaScript
0.000001
@@ -1796,18 +1796,16 @@ loy', %5B%22 -re build%22%5D, @@ -1875,12 +1875,13 @@ eploy()) +; %0A%7D);
4b79331631ec7ebb4c35940f36f2d6bb5009ba03
Add CSS sourcemap to production task * In production, the init line needs to be after the Postcss job
gulpfile.js
gulpfile.js
'use strict'; // http://www.w3schools.com/js/js_strict.asp // 1. LOAD PLUGINS var gulp = require('gulp'); var postcss = require("gulp-postcss"); var p = require('gulp-load-plugins')({ // This loads all the other plugins. DEBUG: false, pattern: ['gulp-*', 'gulp.*', 'del', 'run-*', 'browser*', 'vinyl-*', 'through2'], rename: { 'vinyl-source-stream': 'source', 'vinyl-buffer': 'buffer', }, }); // 2. CONFIGURATION var src = 'source/', // The Middleman source folder dest = '.tmp/', // The "hot" build folder used by Middleman's external pipeline development = p.environments.development, production = p.environments.production, css = { in: src + 'stylesheets/**/*.{css,scss,sass}', out: dest + 'stylesheets/', }, js = { in: src + 'javascripts/*.{js,coffee}', out: dest + 'javascripts/' }, images = { in: src + 'images/**/*', out: dest + 'images/' }, serverOpts = { proxy: 'localhost:4567', open: false, reloadDelay: 500, files: [dest + '**/*.{js,css}', src + '**/*.{html,erb,markdown}'] }; // 3. WORKER TASKS // CSS Preprocessing gulp.task('css', function() { return gulp.src(css.in) .pipe(development(p.sourcemaps.init())) .pipe(postcss([ require("postcss-import"), require("tailwindcss"), require("autoprefixer") ])) .pipe(production(p.cleanCss())) .pipe(development(p.sourcemaps.write())) .pipe(gulp.dest(css.out)); }); // Javascript Bundling gulp.task('js', function(done) { var b = p.browserify({ entries: src + 'javascripts/all.js', debug: true }); return b.bundle().on('error', handleError) .pipe(p.source('bundle.js')) .pipe(production ? p.buffer() : p.through.obj()) .pipe(production(p.stripDebug())) .pipe(production(p.sourcemaps.init())) .pipe(production(p.terser())) .pipe(production(p.sourcemaps.write())) .pipe(gulp.dest(js.out)) done(); }); // Image Optimization gulp.task('images', function() { return gulp.src(images.in) .pipe(p.changed(images.out)) .pipe(p.imagemin()) .pipe(gulp.dest(images.out)); }); // Clean .tmp/ gulp.task('clean', function(done) { p.del([ dest + '*' ]), done(); }); // Asset Size Report gulp.task('sizereport', function () { return gulp.src(dest + '**/*') .pipe(p.sizereport({ gzip: true })); }); // 4. SUPER TASKS // Development Task gulp.task('development', gulp.series('clean', 'css', 'js', 'images')); // Production Task gulp.task('production', gulp.series('clean', 'css', 'js', 'images', 'sizereport')); // Default Task // This is the task that will be invoked by Middleman's exteranal pipeline when // running 'middleman server' gulp.task('default', gulp.series('development', function browsersync () { p.browserSync.init(serverOpts); gulp.watch(css.in, gulp.series('css')); gulp.watch(js.in, gulp.series('js')); gulp.watch(images.in, gulp.series('images')); })); function handleError(err) { console.log(err.toString()); this.emit('end'); }
JavaScript
0.000001
@@ -1330,40 +1330,123 @@ n(p. -cleanCss()))%0A%09%09.pipe(development +sourcemaps.init()))%0A%09%09.pipe(production(p.cleanCss()))%0A%09%09.pipe(development(p.sourcemaps.write()))%0A%09%09.pipe(production (p.s @@ -1631,16 +1631,59 @@ ug: true + // This provides sourcemaps in development %0A%09%7D);%0A%0A%09
0a7f78136ed4e566dd743ff1e523bbf0dfb350bd
fix paths in embedsvg
gulpfile.js
gulpfile.js
"use strict"; // Load plugins const browsersync = require("browser-sync").create(); const cp = require("child_process"); const cssnano = require("cssnano"); const gulp = require("gulp"); const sourcemaps = require("gulp-sourcemaps"); const del = require("del"); const embedSvg = require('gulp-embed-svg'); const plumber = require("gulp-plumber"); const postcss = require("gulp-postcss"); const rename = require("gulp-rename"); const easyimport = require("postcss-easy-import"); const csslogical = require("postcss-logical"); const cssCustomMedia = require("postcss-custom-media"); const cssCustomSelectors = require("postcss-custom-selectors"); const cssMediaMinMax = require("postcss-media-minmax"); const cssPresentEnv = require("postcss-preset-env"); const cssDeclarationSorter = require('css-declaration-sorter'); // BrowserSync function browserSync(done) { browsersync.init({ server: { baseDir: "./_site/" }, port: 3000 }); done(); } // BrowserSync Reload function browserSyncReload(done) { browsersync.reload(); done(); } // Clean assets function clean() { return del(["./_site/assets/"]); } // SVG function embedSvgs() { return gulp .src('*.html') .pipe(embedSvg()) .pipe(gulp.dest('.')) } // CSS task function css() { var plugins = [ easyimport(), csslogical({ dir: 'ltr' }), cssCustomMedia(), cssCustomSelectors(), cssMediaMinMax(), cssPresentEnv(), cssDeclarationSorter({ order: 'concentric-css' }) ] return gulp .src("./assets/css/_inc/main.css") .pipe(sourcemaps.init()) .pipe(postcss(plugins)) .pipe(sourcemaps.write('.')) .pipe(gulp.dest("./_site/assets/css/")) .pipe(gulp.dest("./assets/css/")) .pipe(browsersync.stream()); } // Jekyll function jekyll() { return cp.spawn("bundle", ["exec", "jekyll", "build", "--config", "_config.yml,_config_dev.yml"], { stdio: "inherit" }); } // Watch files function watchFiles() { gulp.watch("./assets/css/_inc/*", css); gulp.series(css, browserSyncReload) gulp.watch( [ "./_includes/**/*", "./_layouts/**/*", "./_pages/**/*", "./_posts/**/*" ], gulp.series(embedSvgs, jekyll, css, browserSyncReload) ); } // define complex tasks const build = gulp.series(clean, embedSvgs, jekyll, css); const watch = gulp.parallel(watchFiles, browserSync); // export tasks exports.css = css; exports.jekyll = jekyll; exports.clean = clean; exports.embedSvgs = embedSvgs; exports.build = build; exports.watch = watch; exports.default = build;
JavaScript
0.000005
@@ -1182,17 +1182,31 @@ .src(' -* +_includes/hcard .html')%0A @@ -1224,16 +1224,59 @@ mbedSvg( +%7B%0A root: './assets/images/icons'%0A %7D ))%0A . @@ -1291,16 +1291,26 @@ p.dest(' +_includes/ .'))%0A%7D%0A%0A
0de7a4e4fc9d6034f2031d7e0c81224c3d24ead6
Allow changing port via env variable
gulpfile.js
gulpfile.js
var gulp = require("gulp"), gutil = require("gulp-util"), sourcemaps = require('gulp-sourcemaps'), eslint = require('gulp-eslint'); less = require("gulp-less"), concat = require("gulp-concat"), uglify = require("gulp-uglify"), path = require("path"), shell = require("gulp-shell"), rename = require("gulp-rename"), react = require("gulp-react"), jsxcs = require("gulp-jsxcs"), jest = require("gulp-jest"), transform = require("vinyl-transform"), fs = require("fs"), es = require("event-stream"), JSONStream = require("JSONStream"), runSequence = require("run-sequence"), _ = require("underscore"), webpack = require("webpack"), webpackConfig = require("./webpack.config.js"), WebpackDevServer = require("webpack-dev-server"); // Lint Task // Uses jsxcs, then strips Flow types and uses jshint. // Has no output. gulp.task("lint", function() { return gulp.src(['./src/**/*.js']) .pipe(eslint()) .pipe(eslint.format()); }); /** * Compile LESS into CSS puts output in ./build/css */ gulp.task("less", function () { return gulp.src("./style/**/*.less") .pipe(sourcemaps.init()) .pipe(less({ paths: [ path.join(__dirname, "style") ] }).on('error', function(e) { console.log('error running less', e); this.emit('end'); })) .pipe(sourcemaps.write()) .pipe(gulp.dest("./build/css")); }); // The react task should not normally be needed. // This is only present if the errors from webpack and you // want to only try running react. // Puts output in the ./build folder gulp.task("react", function() { return gulp.src(["./src/**/*.js"]) .pipe(react({ harmony: true, // Skip Flow type annotations! stripTypes: true })) .pipe(gulp.dest("./build")); }); // Copy minify.js to the build folder and strip out Flow typechecks gulp.task("copyMinifyScript", function() { return gulp.src(["./src/minify.js"]) .pipe(react({ harmony: true, // Skip Flow type annotations! stripTypes: true })) .pipe(gulp.dest("./build")); }); // Runs ./tools/updateTopicTreeData gulp.task("runTopicTreeScript", function() { return gulp.src("", {read: false}) .pipe(shell([ "./tools/updateTopicTreeData" ])); }); // sequences the above 2 tasks to generate new topic tree files gulp.task("updateTopicTree", function(cb) { runSequence("copyMinifyScript", "runTopicTreeScript", cb); }); // Initiates a webpack operation and puts the bundle in ./build based // on the config in webpack.config.js. gulp.task("webpack", function(callback) { var myConfig = Object.create(webpackConfig); myConfig.debug = true; webpack(myConfig, function(err, stats) { if(err) { throw new gutil.PluginError("webpack", err); } // Log filenames packed: //gutil.log("[webpack]", stats.toString({ // output options //})); callback(); }); }); // Starts a webpack dev-server on port 8008 // localhost:8008 can be used instead for development. // The bundle.js file will not be written out and will be served from memory. gulp.task("server", function(callback) { var myConfig = Object.create(webpackConfig); myConfig.debug = true; myConfig.cache = true; new WebpackDevServer(webpack(myConfig), { publicPath: myConfig.output.publicPath, stats: { colors: true } }).listen(8008, "localhost", function(err) { if (err) { throw new gutil.PluginError("webpack-dev-server", err); } // Server listening gutil.log("[webpack-dev-server]", "http://localhost:8008/webpack-dev-server/index.html"); // keep the server alive or continue? // callback(); }); }); // Runs the ./tools/package script which bundles the app for Firefox OS devices. // Puts the output in ./dist/package gulp.task("package", function () { return gulp.src("", {read: false}) .pipe(shell([ "./tools/package" ])); }); // Runs Jest tests gulp.task("test", function() { return gulp.src("__tests__").pipe(jest({ unmockedModulePathPatterns: [ "node_modules/react" ], testDirectoryName: "js", testPathIgnorePatterns: [ "node_modules" ], moduleFileExtensions: [ "js", "json", "react" ] })); }); // Watch Files For Changes, when there are some will run lint and webpack // Will also watch for .less changes and generate new .css. gulp.task("watch", function() { gulp.watch("src/**/*.js", ["lint", "webpack"]); gulp.watch("style/**/*.less", ["less"]); }); // Default Task // Not including Flow typechecking by default because it takes so painfully long. // Maybe because of my code layout or otheriwse, needto figure it out before enabling by default. gulp.task("default", function(cb) { runSequence(["lint", "less", "webpack"], "package", cb); });
JavaScript
0
@@ -804,16 +804,85 @@ ver%22);%0A%0A +var defaultPort = 8008;%0Avar port = process.env.PORT %7C%7C defaultPort;%0A%0A // Lint @@ -2996,136 +2996,8 @@ %7D%0A - // Log filenames packed:%0A //gutil.log(%22%5Bwebpack%5D%22, stats.toString(%7B%0A // output options%0A //%7D));%0A @@ -3059,21 +3059,8 @@ rver - on port 8008 %0A// @@ -3073,13 +3073,14 @@ ost: -8008 +%3Cport%3E can @@ -3494,20 +3494,20 @@ .listen( -8008 +port , %22local @@ -3714,20 +3714,28 @@ calhost: -8008 +%22 + port + %22 /webpack
712cb3a556caebfaf6d8bfc93db5451dee67b625
remove commented out code
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var requireDir = require('require-dir'); var helpers = require('./gulp/helpers'); var runSequence = require('run-sequence'); requireDir('./gulp/tasks', { recurse: true }); gulp.task('test', ['eslint-build', 'esdoc', 'mocha-server'], function () { console.log('checking for error'); if (helpers.getError()) { throw helpers.getError(); } }); gulp.task('default', function () { return gulp.start('eslint-build', 'esdoc', 'mocha-server'); }); gulp.task('build', (done) => { runSequence('transpile', 'webpack', () => { done(); }); }); // // // 'use strict'; // var gulp = require('gulp'); // var jshint = require('gulp-jshint'); // var istanbul = require('gulp-istanbul'); // var mocha = require('gulp-mocha'); // var coverageEnforcer = require('gulp-istanbul-enforcer'); // var runSequence = require('run-sequence'); // // var globs = { // js: { // lib: ['lib/**/*.js', 'start.js'], // gulpfile: ['Gulpfile.js'], // specs: ['tests/**/*.js', '!tests/fixtures/**/*'] // }, // specs: ['tests/**/*.js', '!tests/fixtures/**/*'] // }; // // function runJshint() { // return gulp.src( // globs.js.lib.concat( // globs.js.gulpfile) // ) // .pipe(jshint()) // .pipe(jshint.reporter('jshint-stylish')) // .pipe(jshint.reporter('jshint-growl-reporter')); // } // // function mochaServer(options) { // // return gulp.src(globs.specs, { // read: false // }) // .pipe(mocha(options || { // reporter: 'nyan', // growl: true // })); // } // // Testing // var coverageOptions = { // dir: './coverage', // reporters: ['html', 'lcov', 'text-summary', 'html', 'json'], // reportOpts: { // dir: './coverage' // } // }; // // gulp.task('jshint-build', function () { // return runJshint().pipe(jshint.reporter('fail')); // }); // gulp.task('jshint', function () { // return runJshint(); // }); // // // // gulp.task('mocha-server-continue', function (cb) { // gulp.src(globs.js.lib) // .pipe(istanbul()) // .on('error', function (err) { // console.log('istanbul error', err); // }) // .on('finish', function () { // mochaServer().on('error', function (err) { // console.trace(err); // this.emit('end'); // cb(); // }).pipe(istanbul.writeReports(coverageOptions)) // .on('end', cb); // }); // }); // gulp.task('enforce-coverage', ['mocha-server'], function () { // var options = { // thresholds: { // statements: 80, // branches: 80, // lines: 80, // functions: 80 // }, // coverageDirectory: 'coverage', // rootDirectory: process.cwd() // }; // return gulp.src(globs.js.lib) // .pipe(coverageEnforcer(options)); // }); // gulp.task('mocha-server', function (cb) { // gulp.src(globs.js.lib) // .pipe(istanbul()) // .on('finish', function () { // mochaServer({ // reporter: 'spec' // }) // .pipe(istanbul.writeReports(coverageOptions)) // .on('end', cb); // }); // }); // // gulp.task('watch', function () { // // var watching = false; // gulp.start( // 'jshint', // 'mocha-server-continue', function () { // // Protect against this function being called twice // if (!watching) { // watching = true; // gulp.watch(globs.js.lib.concat( // globs.js.specs), ['seq-test']); // gulp.watch(globs.js.Gulpfile, ['jshint']); // } // }); // }); // gulp.task('seq-test', function () { // runSequence('jshint', 'mocha-server-continue'); // }); // gulp.task('test', function () { // return gulp.start('jshint-build', // 'mocha-server', // 'enforce-coverage'); // }); // gulp.task('build', function () { // return gulp.start('jshint-build', // 'mocha-server', // 'enforce-coverage'); // }); // gulp.task('default', function () { // return gulp.start('jshint-build', // 'mocha-server', // 'enforce-coverage'); // });
JavaScript
0
@@ -597,3420 +597,4 @@ %7D);%0A -%0A%0A//%0A//%0A// 'use strict';%0A// var gulp = require('gulp');%0A// var jshint = require('gulp-jshint');%0A// var istanbul = require('gulp-istanbul');%0A// var mocha = require('gulp-mocha');%0A// var coverageEnforcer = require('gulp-istanbul-enforcer');%0A// var runSequence = require('run-sequence');%0A//%0A// var globs = %7B%0A// js: %7B%0A// lib: %5B'lib/**/*.js', 'start.js'%5D,%0A// gulpfile: %5B'Gulpfile.js'%5D,%0A// specs: %5B'tests/**/*.js', '!tests/fixtures/**/*'%5D%0A// %7D,%0A// specs: %5B'tests/**/*.js', '!tests/fixtures/**/*'%5D%0A// %7D;%0A//%0A// function runJshint() %7B%0A// return gulp.src(%0A// globs.js.lib.concat(%0A// globs.js.gulpfile)%0A// )%0A// .pipe(jshint())%0A// .pipe(jshint.reporter('jshint-stylish'))%0A// .pipe(jshint.reporter('jshint-growl-reporter'));%0A// %7D%0A//%0A// function mochaServer(options) %7B%0A//%0A// return gulp.src(globs.specs, %7B%0A// read: false%0A// %7D)%0A// .pipe(mocha(options %7C%7C %7B%0A// reporter: 'nyan',%0A// growl: true%0A// %7D));%0A// %7D%0A// // Testing%0A// var coverageOptions = %7B%0A// dir: './coverage',%0A// reporters: %5B'html', 'lcov', 'text-summary', 'html', 'json'%5D,%0A// reportOpts: %7B%0A// dir: './coverage'%0A// %7D%0A// %7D;%0A//%0A// gulp.task('jshint-build', function () %7B%0A// return runJshint().pipe(jshint.reporter('fail'));%0A// %7D);%0A// gulp.task('jshint', function () %7B%0A// return runJshint();%0A// %7D);%0A//%0A//%0A//%0A// gulp.task('mocha-server-continue', function (cb) %7B%0A// gulp.src(globs.js.lib)%0A// .pipe(istanbul())%0A// .on('error', function (err) %7B%0A// console.log('istanbul error', err);%0A// %7D)%0A// .on('finish', function () %7B%0A// mochaServer().on('error', function (err) %7B%0A// console.trace(err);%0A// this.emit('end');%0A// cb();%0A// %7D).pipe(istanbul.writeReports(coverageOptions))%0A// .on('end', cb);%0A// %7D);%0A// %7D);%0A// gulp.task('enforce-coverage', %5B'mocha-server'%5D, function () %7B%0A// var options = %7B%0A// thresholds: %7B%0A// statements: 80,%0A// branches: 80,%0A// lines: 80,%0A// functions: 80%0A// %7D,%0A// coverageDirectory: 'coverage',%0A// rootDirectory: process.cwd()%0A// %7D;%0A// return gulp.src(globs.js.lib)%0A// .pipe(coverageEnforcer(options));%0A// %7D);%0A// gulp.task('mocha-server', function (cb) %7B%0A// gulp.src(globs.js.lib)%0A// .pipe(istanbul())%0A// .on('finish', function () %7B%0A// mochaServer(%7B%0A// reporter: 'spec'%0A// %7D)%0A// .pipe(istanbul.writeReports(coverageOptions))%0A// .on('end', cb);%0A// %7D);%0A// %7D);%0A//%0A// gulp.task('watch', function () %7B%0A//%0A// var watching = false;%0A// gulp.start(%0A// 'jshint',%0A// 'mocha-server-continue', function () %7B%0A// // Protect against this function being called twice%0A// if (!watching) %7B%0A// watching = true;%0A// gulp.watch(globs.js.lib.concat(%0A// globs.js.specs), %5B'seq-test'%5D);%0A// gulp.watch(globs.js.Gulpfile, %5B'jshint'%5D);%0A// %7D%0A// %7D);%0A// %7D);%0A// gulp.task('seq-test', function () %7B%0A// runSequence('jshint', 'mocha-server-continue');%0A// %7D);%0A// gulp.task('test', function () %7B%0A// return gulp.start('jshint-build',%0A// 'mocha-server',%0A// 'enforce-coverage');%0A// %7D);%0A// gulp.task('build', function () %7B%0A// return gulp.start('jshint-build',%0A// 'mocha-server',%0A// 'enforce-coverage');%0A// %7D);%0A// gulp.task('default', function () %7B%0A// return gulp.start('jshint-build',%0A// 'mocha-server',%0A// 'enforce-coverage');%0A// %7D);%0A
ac11f9d72e8159e7e0f3b7934b915db4a95ad1c3
Fix placement of label closing tag
lib/form/html.js
lib/form/html.js
'use strict'; const nunjucks = require('nunjucks'); /* * Add Error Messaging to Rendered Inputs * * @param {string} html - Rendered HTML * @param {InputType} type - Input type being rendered * @param {FormInputValues} - Errors associated with form inputs * @param {Integer} - Index of the instance if repeatable * * @returns {string} - Rendered HTML, with appropriate error messages, and aria labels for invalid inputs */ const addError = (html, input, errors, index) => { let render = html; let result = ''; const inputs = []; if (errors) { if (Array.isArray(input.inputs) && index !== undefined) { Object.keys(input.inputs[index]).map(inp => { inputs.push({ name: `${input.id}--${inp}--${index}`, id: input.inputs[index][inp].id, }); }); } else { Object.keys(input.inputs).map(inp => { inputs.push({ name: `${input.id}--${inp}`, id: input.inputs[inp].id, }); }); } inputs.map(inp => { const find = new RegExp(`name=['"]\\s*${inp.name}\\s*['"]`); const errored = render.replace(find, `name="${inp.name}" aria-invalid="true"`); if (errors.hasOwnProperty(inp.name)) { result += `<p class="form--alert" role="alert" for="${inp.id}">${errors[inp.name]}</p>`; render = errored; } }); } result += render; return result; }; /* * Add Required Rendered Inputs * * @param {string} html - Rendered HTML * @param {InputType} type - Input type being rendered * @param {Integer} - Index of the instance if repeatable * * @returns {string} - Rendered HTML, with required indicators */ const addRequired = (html, input, index) => { let render = html; let result = ''; const inputs = []; if (Array.isArray(input.inputs) && index !== undefined) { Object.keys(input.inputs[index]).map(inp => { inputs.push({ required: input.inputs[index][inp].required, name: `${input.id}--${inp}--${index}`, id: input.inputs[index][inp].id, type: input.inputs[index][inp].type, }); }); } else { Object.keys(input.inputs).map(inp => { inputs.push({ required: input.inputs[inp].required, name: `${input.id}--${inp}`, id: input.inputs[inp].id, type: input.inputs[inp].type, }); }); } inputs.map(inp => { // Skip the required attribute for checkbox and radio on browser if (inp.type === 'checkbox' || inp.type === 'radio') { return; } if (input.required === 'save' || inp.required === 'save' || input.required === 'publish' || inp.required === 'publish') { const required = inp.required || input.required; const level = `required--${required}`; // pre-regex strings const stringFor = `for=["']\\s*${inp.id}\\s*["']`; // regex to get the label for THIS input const regexLabel = new RegExp(`.*(<label[\\w\\W\\s]*${stringFor}[\\w\\W\\s]*?>)`); // THIS input's label const label = render.match(regexLabel); // checks if label is not found if (label === null || !Array.isArray(label) || label.length < 2) { return; } // regex to search for `for` const reFor = new RegExp(`(${stringFor})`); render = render.replace(reFor, `for="${inp.id}"`); // add required to input const reName = new RegExp(`name=['"]\\s*${inp.name}\\s*['"]`); render = render.replace(reName, `name="${inp.name}" aria-required="true" required`); // Add required text to label const reLabel = new RegExp('</label>'); render = render.replace(reLabel, `\u00a0<mark class="${level}">required to ${required}</mark>`); render += '</label>'; } }); result += render; return result; }; /* * Renders the input in to HTML * * @param {InputType} type - Input type being rendered * @param {FormInputValues} - Errors associated with form inputs * * @returns {string} - Rendered HTML form body (not wrapped in <form>) */ const renderer = (type, errors) => { return new Promise((res) => { let rendered = type.attributes.map(input => { let inputs = Object.keys(input.inputs).length; if (Array.isArray(input.inputs) && input.inputs.length > 0) { inputs = Object.keys(input.inputs[0]).length; } const description = input.hasOwnProperty('description') && input.description !== ''; const context = input.inputs; let html = nunjucks.renderString(input.html, context); let render = ''; // Set opening tags based on number of inputs if (inputs > 1) { render += `<fieldset id="${input.id}" class="form--fieldset">`; render += `<legend class="form--legend">${input.name}</legend>`; // Add Description if (description) { render += `<p class="form--description">${input.description}</p>`; } } else { render += `<div id="${input.id}" class="form--field">`; } // Wraps repeatable attributes around div if (Array.isArray(input.inputs) && input.hasOwnProperty('repeatable')) { context.forEach((data, index) => { render += `<div id="sub-${input.id}--${index}" class="form--repeatable">`; html = nunjucks.renderString(input.html, data); // Add error messaging and required render += addRequired(addError(html, input, errors, index), input, index); // Adds delete button if instances are greater than minimum if (input.inputs.length > input.repeatable.min) { render += `<button type="button" class="form--delete" id="${input.id}--delete--${index}">Delete</button>`; } render += '</div>'; }); if (input.inputs.length < input.repeatable.max) { render += `<button type="button" class="form--add" id="${input.id}--add">Add</button>`; } } else { // Add error messaging and required render += addRequired(addError(html, input, errors), input); } // Set closing tags based on number of inputs if (inputs > 1) { render += '</fieldset>'; } else { // Add Description if (description) { render += `<p class="form--description">${input.description}</p>`; } render += '</div>'; } return render; }); rendered = rendered.join('\n\n'); res(rendered); }); }; module.exports = renderer; module.exports.error = addError; module.exports.required = addRequired;
JavaScript
0
@@ -3706,37 +3706,16 @@ ark%3E -%60);%0A render += ' %3C/label%3E ';%0A @@ -3710,17 +3710,18 @@ %3C/label%3E -' +%60) ;%0A %7D%0A
4993dac019eb6eb43b74d5999efebeb5e5c99bdb
Modify files globs to include all files
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var watch = require('gulp-watch'); var harp = require('harp'); var browserSync = require('browser-sync'); var ghPages = require('gulp-gh-pages'); var harpServerOptions = { port: 9000 }; var paths = { projectDir: './', outputDir: './dist', outputFiles: './dist/**/*.*', srcFiles: './public/**/*.*' }; gulp.task('default', ['watch']); gulp.task('deploy', ['build'], function () { return gulp.src(paths.outputFiles) .pipe(ghPages()); }); gulp.task('build', function (done) { harp.compile(paths.projectDir, paths.outputDir, done); }); gulp.task('watch', ['dev-server'], function () { browserSync({ open: false, proxy: 'localhost:' + harpServerOptions.port, notify: false }); gulp.src(paths.srcFiles) .pipe(watch(paths.srcFiles, { verbose: true })) .pipe(browserSync.reload({ stream: true })); }); gulp.task('dev-server', function (done) { harp.server(__dirname, harpServerOptions, done); });
JavaScript
0
@@ -310,18 +310,16 @@ ist/**/* -.* ',%0A src @@ -343,10 +343,8 @@ **/* -.* '%0A%7D;
3d8c522e5ec41df02b9ce21df3729d84f62f1fd2
clean up gulp file
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var sass = require('gulp-sass'); var connect = require('gulp-connect'); var babel = require('gulp-babel'); var minify = require('gulp-minify'); var shell = require('gulp-shell'); // setup the local enviroment gulp.task('connect', function(){ connect.server({ root: 'public', livereload: true }); }); // compile sass and log errors in the terminal gulp.task('sass', function () { return gulp.src('./sass/styles.scss') .pipe(sass({ errLogToConsole: true })) .pipe(gulp.dest('./public/css')); }); // transpile our ES6 javascript into ES5 gulp.task('transpile', function() { return gulp.src('./scripts/*.js') .pipe(babel({ presets: ['env'] })) .pipe(gulp.dest('./public/js')) }); // minify required javascript for dist gulp.task('minify', function() { gulp.src('./public/js/okaynowthis.js') .pipe(minify({ ext:{ min:'.min.js' }, })) .pipe(gulp.dest('./dist/')) }); // setup the live reload of public files gulp.task('livereload', function (){ gulp.src('./public/**/*') .pipe(connect.reload()); }); // watch for changes gulp.task('watch', function () { gulp.watch('./sass/**/*.scss', ['sass']); gulp.watch('./scripts/**/*.js', ['transpile']); gulp.watch('./public/**/*', ['livereload']); }); // update the GitHub pages subtree (by running a basic git command via shell) gulp.task('example', () => { shell.task('git subtree push --prefix public origin gh-pages'); }) // setup the default 'gulp task' gulp.task('default', ['connect', 'watch', 'sass', 'transpile']); // package the dist folder and update the demo on gh-pages gulp.task('package', ['minify', 'updateDemo']);
JavaScript
0.000001
@@ -1416,15 +1416,16 @@ sk(' -example +pushDemo ', ( @@ -1437,19 +1437,67 @@ %7B%0A -shell.task( +return gulp.src('*.js', %7Bread: false%7D)%0A .pipe(shell(%5B%0A 'git @@ -1542,18 +1542,22 @@ h-pages' +%0A %5D) ) -; %0A%7D)%0A%0A// @@ -1643,24 +1643,34 @@ 'transpile' +, 'minify' %5D);%0A// packa @@ -1747,24 +1747,12 @@ , %5B' -minify', 'update +push Demo
8baf0d4540d9fb1ada2133b5ea8a85a039342d21
Update version to 1.5.4
gulpfile.js
gulpfile.js
(function () { 'use strict'; // Set library version var version = '1.5.3'; // Initialize variables var gulp = require('gulp'); var del = require('del'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); // Initialize Panda Libraries var panda = [ // Panda 'src/Panda.js', // Panda Registry 'src/panda/Registry.js', // Base packages 'src/panda/*.js', // Debug package 'src/panda/debug/*.js', // Environment package 'src/panda/env/*.js', // Events package 'src/panda/events/*.js', // Helpers package 'src/panda/helpers/*.js', // Http package 'src/panda/http/*.js', 'src/panda/http/Jar/*.js', // Main files 'src/Init.js' ]; // Set default gulp task gulp.task('default', ['build']); // Compress files task gulp.task('build', ['minify']); // Minify files gulp.task('minify', ['concat', 'concat-with-jq'], function () { return gulp.src(['./dist/*.js']) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('./dist/')); }); // Concat source files gulp.task('concat', function () { // Clean files del('./dist/*'); // build without jQuery return gulp.src(panda) .pipe(concat('panda-' + version + '.js')) .pipe(gulp.dest('./dist/')); }); // Concat source files gulp.task('concat-with-jq', function () { // Clean files del('./dist/*'); // build with jQuery return gulp.src(['src/jquery/*.js'].concat(panda)) .pipe(concat('panda-' + version + '.jq.js')) .pipe(gulp.dest('./dist/')); }); }());
JavaScript
0.000001
@@ -81,9 +81,9 @@ 1.5. -3 +4 ';%0A%0A
70f88a1df315e017f617e9bbb0e2ad3936d7203c
add source paths
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'), svgstore = require('gulp-svgstore'), svgmin = require('gulp-svgmin'), postcss = require('gulp-postcss'), precss = require('precss'), autoprefixer = require('autoprefixer'), path = require('path'), jade = require('gulp-jade'); // default gulp.task('default', function() { }); // process css with postcss gulp.task( 'css', function() { var processors = [ autoprefixer({ browsers: ['> 0.15% in RU'] }), precss() ]; return gulp.src( 'src/css/*.css' ) .pipe( postcss( processors )) .pipe( gulp.dest('dest/css') ); }); // build svg sprite from svg-icons gulp.task('icons', function() { return gulp .src('src/img/icons/*.svg') .pipe(svgmin(function(file) { var prefix = path.basename(file.relative, path.extname(file.relative)); return { plugins: [{ cleanupIDs: { prefix: prefix + '-', minify: true } }] }; })) .pipe(svgstore()) .pipe(gulp.dest('dest/img')); }); // compile .jade to .html gulp.task('html', function() { gulp.src('src/*.jade') .pipe(jade()) .pipe(gulp.dest('dest')); });
JavaScript
0.000001
@@ -332,24 +332,137 @@ lp-jade');%0A%0A +var paths = %7B%0A js: 'src/js/**/*.js',%0A css: 'src/css/**/*.css',%0A img: 'src/img/**/*',%0A jade: 'src/*.jade'%0A%7D;%0A%0A %0A// default%0A
76aec9d1c464f6b5cd47f7742db576511e9699c5
Add missing semicolon in gulpfile.js
gulpfile.js
gulpfile.js
var gulp = require("gulp"); var sass = require("gulp-sass"); var autoPrefixer = require("gulp-autoprefixer"); var minifyCss = require("gulp-minify-css"); var jshint = require("gulp-jshint"); var stylishJshint = require("jshint-stylish"); var uglify = require("gulp-uglify"); var plumber = require("gulp-plumber") var SASS_SRC = "./web-src/scss/*.scss"; var SASS_DEST = "./static/css"; var JS_SRC = "./web-src/js/*.js"; var JS_DEST = "./static/js"; gulp.task("sass", function () { return gulp.src(SASS_SRC) .pipe(plumber()) .pipe(sass().on("error", sass.logError)) .pipe(autoPrefixer({ browsers: [ "last 2 versions", "IE 9" ] })) .pipe(minifyCss()) .pipe(gulp.dest(SASS_DEST)); }); gulp.task("js", function() { return gulp.src(JS_SRC) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter(stylishJshint)) .pipe(jshint.reporter("fail")) .pipe(uglify()) .pipe(gulp.dest(JS_DEST)); }); gulp.task("watch", function () { //Watch Sass for changes. var sassWatch = gulp.watch(SASS_SRC, ["sass"]); sassWatch.on("change", function (event) { console.log("Event '"+ event.type + "' detected on " + event.path + ". Running sass."); }); //Watch JS for changes. var jsWatch = gulp.watch(JS_SRC, ["js"]); jsWatch.on("change", function(event) { console.log("Event '"+ event.type + "' detected on " + event.path + ". Running js."); }); });
JavaScript
0.001901
@@ -305,16 +305,17 @@ lumber%22) +; %0A%0Avar SA
c807db9fd5e0d6652fd0c206fe48a8266a87f62d
Update gulpfile to ES6 and cleanup
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var del = require('del'); var plumber = require('gulp-plumber'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var livereload = require('gulp-livereload'); var autoprefixer = require('gulp-autoprefixer'); var sass = require('gulp-sass'); var runSequence = require('run-sequence'); var connect = require('gulp-connect'); var open = require('gulp-open'); var inlinesource = require('gulp-inline-source'); var exec = require('child_process').exec, child; gulp.task('default', function(cb){ runSequence('build', ['connect', 'watch'], 'open', cb); }); gulp.task('build', function(cb){ runSequence('clean', ['lint', 'styles'], 'inlinesource', 'reload', cb); }); gulp.task('open', function(){ return gulp.src(__filename).pipe( open({uri: 'http://localhost:4567'}) ); }); gulp.task('inlinesource', function () { return gulp.src('./src/index.html') .pipe( plumber() ) .pipe( inlinesource() ) .pipe(gulp.dest('./dist')); }); gulp.task('connect', function () { child = exec('ruby ./emulator.rb', function(err, stdout, stderr) { console.log(err, stdout, stderr); }); }); gulp.task('styles', function () { return gulp.src( './src/style.scss' ) .pipe( plumber() ) .pipe( sass() ) .pipe( autoprefixer({ browsers: ['Android >= 29','ChromeAndroid >= 29','Chrome >= 29'], cascade: false })) .pipe( gulp.dest( './tmp' ) ); }); gulp.task('clean', function (cb) { del('./tmp', cb); }); gulp.task('lint', function() { return gulp.src( './src/*.js' ) .pipe( plumber() ) .pipe( jshint() ) .pipe( jshint.reporter(stylish) ); }); gulp.task('reload', function(){ return livereload.reload(); }); gulp.task('watch', function(){ livereload.listen(); gulp.watch( ['./{src,tmp}/*.{html,js,css}'], ['build'] ); gulp.watch( './src/style.scss', ['styles'] ); });
JavaScript
0
@@ -1,11 +1,13 @@ -var +const gulp @@ -32,19 +32,21 @@ gulp');%0A -var +const del @@ -70,19 +70,21 @@ 'del');%0A -var +const plumber @@ -117,19 +117,21 @@ mber');%0A -var +const jshint @@ -163,19 +163,21 @@ hint');%0A -var +const stylish @@ -212,19 +212,21 @@ lish');%0A -var +const liverel @@ -262,19 +262,21 @@ load');%0A -var +const autopre @@ -314,19 +314,21 @@ ixer');%0A -var +const sass @@ -358,19 +358,21 @@ sass');%0A -var +const runSequ @@ -405,19 +405,21 @@ ence');%0A -var +const connect @@ -452,19 +452,21 @@ nect');%0A -var +const open @@ -496,20 +496,21 @@ open');%0A -%0Avar +const inlines @@ -553,18 +553,28 @@ ');%0A -%0Avar +const exec + = re @@ -604,19 +604,8 @@ exec -,%0A child ;%0A%0Ag @@ -1130,16 +1130,8 @@ %7B%0A - child = exe @@ -1154,24 +1154,16 @@ or.rb', -function (err, st @@ -1176,21 +1176,18 @@ stderr) -%7B%0A +=%3E console @@ -1215,13 +1215,9 @@ err) -;%0A %7D + );%0A%7D @@ -1539,18 +1539,25 @@ (cb) %7B%0A - +return del('./t
666fe624baa55f119fa75c1aa131d046d9154f35
replace only once omitting "g" option in regex
gulpfile.js
gulpfile.js
// https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md // sudo npm install --global gulp-cli // npm install --save-dev gulp // Please edit config.json before starting const config = require('./config.json'); // load npm modules and gulp plugins var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var changed = require('gulp-changed'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var git = require('gulp-git'); var uglifycss = require('gulp-uglifycss'); var jsonminify = require('gulp-jsonminify'); // var replace = require('gulp-replace'); var replace = require('gulp-replace-task'); var insert = require('gulp-insert'); var jsdoc = require('gulp-jsdoc3'); var gutil = require('gulp-util'); var prompt = require('gulp-prompt'); var runSequence = require('run-sequence'); // define constants for global use const USER = config.gulp.user; const REPO = config.gulp.repo; const SRC = path.join( '..', REPO ); const DEST = path.join( '..', REPO + config.gulp.repo_suffix, config.gulp.destination ); const SRC2 = config.gulp.external_components; const SERVER_URL = param_replace( config.gulp.server_url, {'user': USER, 'repo': REPO } ); gulp.task('default', [ 'js', 'css', 'json', 'doc', 'api' ]); // remotify JavaScript files by replacing local paths by remote paths // minify JavaScript files after remotifying gulp.task('js', function() { return gulp.src(glob_pattern('js')) // the `changed` task needs to know the destination directory // upfront to be able to figure out which files changed // .pipe(changed(DEST)) // only files that has changed will pass through here // replace local paths by remote paths // .pipe(replace('../', SERVER_URL)) .pipe(replace({ patterns: [ { match: /\.\.\//g, replacement: SERVER_URL } ] })) .pipe(uglify()) // .pipe(rename({ // suffix: '.min' // })) .pipe(gulp.dest(DEST)); }); // minify CSS files gulp.task('css', function () { return gulp.src(glob_pattern('css')) // .pipe(changed(DEST)) // .pipe(replace('../', SERVER_URL)) .pipe(replace({ patterns: [ { match: /\.\.\//g, replacement: SERVER_URL } ] })) .pipe(uglifycss({ "maxLineLen": 80, "uglyComments": true })) // .pipe(rename({ // suffix: '.min' // })) .pipe(gulp.dest(DEST)); }); // minify JSON files gulp.task('json', function () { return gulp.src(glob_pattern('json')) // .pipe(changed(DEST)) // .pipe(replace('../', SERVER_URL)) .pipe(replace({ patterns: [ { match: /\.\.\//g, replacement: SERVER_URL } ] })) .pipe(insert.transform(function( contents, file ) { return 'ccm.callback[ "' + basename(file.path) + '" ](' + contents + ');'; })) .pipe(jsonminify()) // .pipe(rename({ // suffix: '.min' // })) .pipe(gulp.dest(DEST)); }); /* ************************************** * doc * generate jsdoc3 API documents from comments inside JavaScript files * using jsdoc3 * generate extra gulp task per ccm-component * for generating extra API documents per ccm-component * ************************************ */ // remember list of task names var folders = getFolders(SRC); var task_names = []; // iterate over all folders in REPO folders.map(function(folder) { if ( !folder || folder.length === 0 ) return; var sub_config = JSON.parse(JSON.stringify(config)); // separate deep copy for each folder sub_config.opts.destination = path.join('..', REPO + config.gulp.repo_suffix, config.gulp.api_dirname, folder); var task_name = 'doc_' + folder; task_names.push( task_name ); // generate extra gulp task per ccm-component, e.g. doc_blank return gulp.task( task_name, function (cb) { gulp.src( [ path.join(SRC, folder, '*.js') ], {read: false} ) .on('error', gutil.log) .pipe(jsdoc( sub_config, cb )); }); }); gulp.task('doc', function (done) { runSequence(task_names, function () { // TODO runSequence to be replaced in gulp 4 console.log('=== doc task ready ==='); done(); }); }); // write api index into index.html file of github.io home page gulp.task('api', function (done) { var index_dir = SRC + config.gulp.repo_suffix; return gulp.src( path.join( index_dir, 'index.html' ) ) .pipe(replace({ patterns: [ { match: /<!-- api_begin -->.*?<!-- api_end -->/gim, replacement: folders.reduce(function( list, component ) { return list + '<li><a href="api/' + component + '/index.html" target="_blank">' + component + ' API</a>' + '</li>'; }, '<!-- api_begin -->') + '<!-- api_end -->' } ] })) .pipe(gulp.dest( index_dir )); }); function glob_pattern(suffix){ return [SRC+'/*/*.'+suffix, '!'+SRC+'/*/*.min.'+suffix, SRC2+'/*/*.'+suffix, '!'+SRC2+'/*/*.min.'+suffix, '!params.json', '!'+SRC+'/api', '!'+SRC+'/fonts', '!'+SRC+'/images', '!'+SRC+'/javascripts', '!'+SRC+'/libs', '!'+SRC+'/stylesheets', '!'+SRC+'/.git', '!'+SRC+'/.idea' ]; } function basename( file_path ){ return file_path.substring(file_path.lastIndexOf('/') + 1); } function getFolders(dir) { return fs.readdirSync(dir) .filter(function(file) { return ! config.gulp.exclude_folders[ file ] && fs.statSync(path.join( dir, file )).isDirectory(); }); } function param_replace( param_string, replace_object ) { return param_string.replace(/\{(.*?)\}/g, function(match, param) { return param in replace_object ? replace_object[param] : match; }); }
JavaScript
0.000069
@@ -4527,17 +4527,16 @@ end --%3E/ -g im,%0A
acd746c5f6fa242ae9ab5f2691fef32bcb3b6443
clean up gulp file
gulpfile.js
gulpfile.js
const gulp = require('gulp'), mocha = require('gulp-mocha'), releaseHelper = require('release-helper'), ts = require('gulp-typescript'), tsProject = ts.createProject('tsconfig.json'), fsExtra = require('fs-extra'), runSequence = require('run-sequence'), path = require('path'), spawn = require('child_process').spawn, { join } = require('path'); //Init custom release tasks releaseHelper.init(gulp); let glue = suffix => gulp.src(`src/**/*.${suffix}`).pipe(gulp.dest('lib')); let watch = (suffix, tasks) => { tasks = tasks ? tasks : [suffix]; return gulp.watch(`src/**/*.${suffix}`, tasks); } gulp.task('pug', () => glue('pug')); gulp.task('md', () => glue('md')); gulp.task('ejs', () => glue('ejs')); gulp.task('ts', () => { let tsResult = tsProject.src() .pipe(tsProject()); return tsResult.js.pipe(gulp.dest('lib')); }); gulp.task('watch-ts', () => watch('ts')); gulp.task('watch-pug', () => watch('pug')); gulp.task('watch-ejs', () => watch('ejs')); gulp.task('watch-md', () => watch('md')); gulp.task('unit', ['build'], () => { return gulp.src('test/unit/**/*.js', { read: false }) .pipe(mocha({ require: ['babel-register'] })); }); gulp.task('it', ['build'], () => { return gulp.src(['test/integration/init.js', 'test/integration/**/*-test.js'], { read: false }) .pipe(mocha({ inspect: true, bail: true, require: ['babel-register'] })) .once('end', () => process.exit()); }); gulp.task('clean', (done) => { fsExtra.remove('lib', done); }) gulp.task('build', done => runSequence('clean', ['md', 'ejs', 'pug', 'ts'], done)); gulp.task('dev', ['build', 'watch-md', 'watch-ejs', 'watch-pug', 'watch-ts']); gulp.task('test', ['unit']);
JavaScript
0.000001
@@ -1329,23 +1329,8 @@ ha(%7B - inspect: true, bai
355119ecc3ce261aadae8a9ee0dc17375331f270
add a return statement to the gulp clean task
gulpfile.js
gulpfile.js
var path = require('path'); var del = require('del'); var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); // set variable via $ gulp --type production var environment = $.util.env.type || 'development'; var isProduction = environment === 'production'; var webpackConfig = require('./webpack.config.js').getConfig(environment); var port = $.util.env.port || 1337; var app = 'app/'; var dist = 'dist/'; // https://github.com/ai/autoprefixer var autoprefixerBrowsers = [ 'ie >= 9', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 6', 'opera >= 23', 'ios >= 6', 'android >= 4.4', 'bb >= 10' ]; gulp.task('scripts', function() { return gulp.src(webpackConfig.entry) .pipe($.webpack(webpackConfig)) .pipe(isProduction ? $.uglify() : $.util.noop()) .pipe(gulp.dest(dist + 'js/')) .pipe($.size({ title : 'js' })) .pipe($.connect.reload()); }); // copy html from app to dist gulp.task('html', function() { return gulp.src(app + 'index.html') .pipe(gulp.dest(dist)) .pipe($.size({ title : 'html' })) .pipe($.connect.reload()); }); gulp.task('styles',function(cb) { // convert stylus to css return gulp.src(app + 'stylus/main.styl') .pipe($.stylus({ // only compress if we are in production compress: isProduction, // include 'normal' css into main.css 'include css' : true })) .pipe($.autoprefixer({browsers: autoprefixerBrowsers})) .pipe(gulp.dest(dist + 'css/')) .pipe($.size({ title : 'css' })) .pipe($.connect.reload()); }); // add livereload on the given port gulp.task('serve', function() { $.connect.server({ root: dist, port: port, livereload: { port: 35729 } }); }); // copy images gulp.task('images', function(cb) { return gulp.src(app + 'images/**/*.{png,jpg,jpeg,gif}') .pipe($.size({ title : 'images' })) .pipe(gulp.dest(dist + 'images/')); }); // watch styl, html and js file changes gulp.task('watch', function() { gulp.watch(app + 'stylus/*.styl', ['styles']); gulp.watch(app + 'index.html', ['html']); gulp.watch(app + 'scripts/**/*.js', ['scripts']); gulp.watch(app + 'scripts/**/*.jsx', ['scripts']); }); // remove bundels gulp.task('clean', function(cb) { del([dist], cb); }); // by default build project and then watch files in order to trigger livereload gulp.task('default', ['images', 'html','scripts', 'styles', 'serve', 'watch']); // waits until clean is finished then builds the project gulp.task('build', ['clean'], function(){ gulp.start(['images', 'html','scripts','styles']); });
JavaScript
0.000012
@@ -2264,16 +2264,23 @@ cb) %7B%0A +return del(%5Bdis
ff9e8100df38af096e31da698e32cfc26465f193
enable recursive option.
lib/generator.js
lib/generator.js
'use strict'; /** @module express-webapp-assets/generator */ var path = require('path'), io = require('node-toybox/io'), async = require('node-toybox/async'), Assets = require('./assets'), debug = require('debug')('express-webapp-assets:generator'), DEBUG = debug.enabled; /** * generates static assets for all assets written in server-side templates/preprocessors. * * @param {AssetsConfig} [config] * @param {function} callback */ module.exports = function (config, callback) { var assets = new Assets(config); io.iterateFiles(assets.config.src, function () { return true; }, function () { return false; }, function (err, files) { if (err) { DEBUG && debug('failed to iterate files...', err); return callback(err); } var errors = []; var generated = []; // single source asset may generate multiple static files(uncompressed and compress version) var assetNames = files.reduce(function (assetNames, file) { return assetNames.concat(assets._getPossibleNames(file)); }, []); DEBUG && debug('*****************src=', assetNames); DEBUG && debug('generating', assetNames.length, 'assets from', files.length, 'files...'); async.reduce(assetNames, function (prev, assetName, next) { assets.resolve(assetName, function (err, result) { if (err) { errors.push(err); // accumulate errors //return next(err); // break on error } generated.push(result); // accumulate results next(null, generated); // ignore error and continue }); }, function (err, generated) { DEBUG && debug('generated', generated.length, 'assets with', errors.length, 'errors'); callback(err || errors, generated); }); }); };
JavaScript
0.000001
@@ -1929,13 +1929,19 @@ );%0A %7D +, true );%0A%7D;
d5ab3c8d49116d31f15f5ff09c4252523f6adde2
Add handlebars example templlate to the gulp build.
gulpfile.js
gulpfile.js
// include gulp var gulp = require('gulp'); // include plug-ins var jshint = require('gulp-jshint'); var gulpif = require('gulp-if'); var coffee = require('gulp-coffee'); var concat = require('gulp-concat'); var gutil = require('gulp-util'); var stylish = require('jshint-stylish'); var coffeelint = require('gulp-coffeelint'); // JS and coffee lint task gulp.task('lint', function() { //Js linting. gulp.src('./lib/*/*.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); //Coffee linting gulp.src('./lib/*/*.coffee') .pipe(coffeelint()) .pipe(coffeelint.reporter()); }); //Build all the javascripts file. gulp.task('browser-build', function() { //Build the js file for the browser. gulp.src(['./lib/main.js', './lib/models/*', 'lib/views/notifications-view.js', 'lib/helpers/post_rendering_helper.js', './lib/helpers/*', './lib/views/*']) .pipe(gulpif(/[.]coffee$/, coffee())).on('error', gutil.log) //browser deploy .pipe(concat('fmk.js')) .pipe(gulp.dest('./dist/browser/')) .pipe(gulp.dest('./example/app/js/')); }); gulp.task('node-build', function() { // Build the node sources. gulp.src(['./lib/helpers/*']) .pipe(gulp.dest('./dist/node/helpers/')); gulp.src(['./lib/models/*']) .pipe(gulp.dest('./dist/node/models/')); gulp.src(['./lib/views/*']) .pipe(gulp.dest('./dist/node/views/')); gulp.src(['./lib/services/*']) .pipe(gulp.dest('./dist/node/services/')); }); // gulp.task('build', ['browser-build', 'node-build']); // The default task (called when you run `gulp` from cli) gulp.task('default', ['build']); var express = require('express'); var path = require('path'); var lrserver = require('tiny-lr')(), express = require('express'), livereload = require('connect-livereload'), livereloadport = 35729, serverport = 5000; //We only configure the server here and start it only when running the watch task var server = express(); //Add livereload middleware before static-middleware server.use(livereload({ port: livereloadport })); // simple logger server.use(function(req, res, next) { gutil.log('%s %s', req.method, req.url); next(); }); server.use(express.static(__dirname + '/example/app/')); gulp.task('serve', function() { //Set up your static fileserver, which serves files in the build dir server.listen(serverport); //Set up your livereload server lrserver.listen(livereloadport); });
JavaScript
0
@@ -1444,16 +1444,37 @@ %0A%7D);%0A%0A// +All tasks by default. %0Agulp.ta @@ -1515,19 +1515,542 @@ e-build' -%5D); +, 'templates'%5D);%0A%0A//Gulp build example templates into a template.js file%0Avar handlebars = require('gulp-handlebars');%0Avar defineModule = require('gulp-define-module');%0Avar declare = require('gulp-declare');%0Avar concat = require('gulp-concat');%0A%0Agulp.task('templates', function()%7B%0A gulp.src(%5B'example/app/templates/*.hbs'%5D)%0A .pipe(handlebars())%0A .pipe(defineModule('plain'))%0A .pipe(declare(%7B%0A namespace: 'Example.templates'%0A %7D))%0A .pipe(concat('templates.js'))%0A .pipe(gulp.dest('example/app/js/'));%0A%7D);%0A%0A %0A%0A// The
b4080d3274def0088080798b0654337bf8336936
remove duplicate declaration
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var util = require('gulp-util'); var notifier = require('node-notifier'); var path = require('path'); var replace = require('gulp-replace'); var child_process = require('child_process'); var fs = require('fs'); var shell = require('gulp-shell'); var jshint = require('gulp-jshint'); var jshStylish = require('jshint-stylish'); var exec = require('child_process').exec; var runSequence = require('run-sequence'); var prompt = require('gulp-prompt'); var browserify = require('browserify'); var watchify = require('watchify'); var babelify = require('babelify'); var buffer = require('vinyl-buffer'); var source = require('vinyl-source-stream'); var notifier = require('node-notifier'); var derequire = require('gulp-derequire'); var server = require('http-server'); var livereload = require('gulp-livereload'); var pkg = require('./package.json'); var version; var logError = function( err ){ notifier.notify({ title: pkg.name, message: 'Error: ' + err.message }); util.log( util.colors.red(err) ); }; var handleErr = function( err ){ logError( err ); if( this.emit ){ this.emit('end'); } }; var getBrowserified = function( opts ){ opts = Object.assign({ debug: true, cache: {}, packageCache: {}, fullPaths: true, bundleExternal: true, entries: [ './src' ], standalone: 'cytoscape-cose-bilkent' }, opts ); return browserify( opts ).on( 'log', util.log ); }; var transform = function( b ){ return ( b // can't use babel because cose-bilkent does just use pure functions in workers... // .transform( babelify.configure({ // presets: ['es2015'], // ignore: 'node_modules/**/*', // sourceMaps: 'inline' // }) ) ) ; }; var bundle = function( b ){ return ( b .bundle() .on( 'error', handleErr ) .pipe( source('cytoscape-cose-bilkent.js') ) .pipe( buffer() ) ) ; }; gulp.task('build', function(){ return bundle( transform( getBrowserified({ fullPaths: false }) ) ) .pipe( gulp.dest('./') ) ; }); gulp.task('watch', function(){ livereload.listen({ basePath: process.cwd() }); server.createServer({ root: './', cache: -1, cors: true }).listen( '9999', '0.0.0.0' ); util.log( util.colors.green('Demo hosted on local server at http://localhost:9999/demo.html') ); gulp.watch( ['./cytoscape-cose-bilkent.js'] ) .on('change', livereload.changed) ; var update = function(){ util.log( util.colors.white('JS rebuilding via watch...') ); bundle( b ) .pipe( gulp.dest('./') ) .on('finish', function(){ util.log( util.colors.green('JS rebuild finished via watch') ); }) ; }; var b = getBrowserified(); transform( b ); b.plugin( watchify, { poll: true } ); b.on( 'update', update ); update(); }); gulp.task('default', ['build'], function( next ){ next(); }); gulp.task('publish', [], function( next ){ runSequence('confver', 'lint', 'build', 'pkgver', 'push', 'tag', 'npm', next); }); gulp.task('confver', ['version'], function(){ return gulp.src('.') .pipe( prompt.confirm({ message: 'Are you sure version `' + version + '` is OK to publish?' }) ) ; }); gulp.task('version', function( next ){ var now = new Date(); version = process.env['VERSION']; if( version ){ done(); } else { exec('git rev-parse HEAD', function( error, stdout, stderr ){ var sha = stdout.substring(0, 10); // shorten so not huge filename version = [ 'snapshot', sha, +now ].join('-'); done(); }); } function done(){ console.log('Using version number `%s` for building', version); next(); } }); gulp.task('pkgver', ['version'], function(){ return gulp.src([ 'package.json', 'bower.json' ]) .pipe( replace(/\"version\"\:\s*\".*?\"/, '"version": "' + version + '"') ) .pipe( gulp.dest('./') ) ; }); gulp.task('push', shell.task([ 'git add -A', 'git commit -m "pushing changes for v$VERSION release" || echo Nothing to commit', 'git push || echo Nothing to push' ])); gulp.task('tag', shell.task([ 'git tag -a $VERSION -m "tagging v$VERSION"', 'git push origin $VERSION' ])); gulp.task('npm', shell.task([ 'npm publish .' ])); // http://www.jshint.com/docs/options/ gulp.task('lint', function(){ return gulp.src( './src/**' ) .pipe( jshint({ funcscope: true, laxbreak: true, loopfunc: true, strict: true, unused: 'vars', eqnull: true, sub: true, shadow: true, laxcomma: true }) ) .pipe( jshint.reporter(jshStylish) ) // TODO clean up via linting //.pipe( jshint.reporter('fail') ) ; });
JavaScript
0.000004
@@ -669,49 +669,8 @@ ');%0A -var notifier = require('node-notifier');%0A var
26534ee951e8898d249487025970dc733794fb3a
Update the gulpFile
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var concat = require('gulp-concat'); /** * Build all the jade templates. * @return {function} */ gulp.task('templates', function() { var jade = require('gulp-jade'); var defineModule = require('gulp-define-module'); gulp.src('./lib/templates/*.jade') .pipe(jade({ client: true})) .pipe(defineModule('commonjs')) .pipe(gulp.dest('./lib/templates/')); }); gulp.task('browserify' ,function() { var browserify = require('browserify'); var source = require('vinyl-source-stream'); return browserify(({entries: ['./lib/index.coffee'], extensions: ['.coffee']})) .bundle() //Pass desired output filename to vinyl-source-stream .pipe(source('loggerz.js')) // Start piping stream to tasks! .pipe(gulp.dest('./dist/')) .pipe(gulp.dest('./example/')); }); gulp.task('style', function(){ var stylus = require('gulp-stylus'); gulp.src('./lib/styles/*.styl') .pipe(stylus()) .pipe(concat('hub.css')) .pipe(gulp.dest('./dist/')) .pipe(gulp.dest('./example/')); }); // var browserSync = require('browser-sync'); var reload = browserSync.reload; // Watch Files For Changes & Reload gulp.task('serve', ['browserify'], function () { browserSync({ notify: false, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: { baseDir: ['example'] } }); gulp.watch(['lib/**/*.js'],['browserify',reload]); //gulp.watch(['lib/templates/*.jade'], ['templates', reload]); //gulp.watch(['lib/styles/*.{styl,css}'], ['style', reload]); //gulp.watch(['lib/*.json'], ['browserify',reload]); //gulp.watch(['app/scripts/**/*.js'], jshint); //gulp.watch(['app/images/**/*'], reload); }); // The default task (called when you run `gulp` from cli) gulp.task('default', ['browserify'/*, 'style'*/]);
JavaScript
0.000001
@@ -1528,18 +1528,22 @@ ib/**/*. -js +coffee '%5D,%5B'bro
127e5d6c50f4c7b9d559357c6497a9c3dfa977f6
Write to correct location, copy file even if optimizing isn't possible (#639)
gulpfile.js
gulpfile.js
/* Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ 'use strict'; const path = require('path'); const gulp = require('gulp'); const gulpif = require('gulp-if'); const gulpreplace = require('gulp-replace'); const jshint = require('gulp-jshint'); const superagent = require('superagent'); const fs = require('fs-extra'); const glob = require('glob'); // Got problems? Try logging 'em // const logging = require('plylog'); // logging.setVerbose(); const ensureLazyFragments = require('./gulp/ensure-lazy-fragments.js'); const root = path.resolve(process.cwd(), 'images'); const optimizedImagesRoot = path.resolve(process.cwd(), 'images-optimized'); const imageOptions = { activities: '340x340', logos: '250,scale-down', unofficial: '340x340', banner: '2000x500,scale-down' }; // Optimize images with ImageOptim // Run with `yarn run build optimize-images` const optimizeImages = () => new Promise((resolve, reject) => { glob('images/**/*.{jpg,png,svg}', (err, files) => { for (const file of files) { const relativeFile = file.substring(file.indexOf(path.sep) + 1); fs.ensureDirSync(path.resolve(optimizedImagesRoot, path.dirname(relativeFile))); if (path.extname(file) === '.svg') { fs.copySync(file, path.resolve(optimizedImagesRoot, relativeFile)); } else { const imageCategory = path.relative(root, file).split(path.sep)[0]; const options = imageOptions[imageCategory] || 'full'; superagent.post(`https://im2.io/nddfzrzzpk/${options}`) .attach('file', file) .end((err, res) => { console.log(`Finished optimizing ${file}`); fs.writeFileSync(path.resolve(optimizedImagesRoot, relativeFile), res.body); }); } } resolve(); }) }); gulp.task('optimize-images', optimizeImages); gulp.task('replace-api', () => { return gulp.src(['build/**/*']).pipe(gulpif(/\.html$/, gulpreplace('/api/v1', 'https://api.areafiftylan.nl/api/v1'))).pipe(gulp.dest('build')) }); gulp.task('ensure-images-optimized', () => new Promise((resolve, reject) => { if (!fs.existsSync(optimizedImagesRoot)) { optimizeImages(); } resolve(); }) ); gulp.task('ensure-lazy-fragments', ensureLazyFragments); const linter = () => { return gulp.src('src/**/*.html') .pipe(jshint.extract()) // Extract JS from .html files .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }; gulp.task('linter', linter); // Changed it back to series to make it easier to test gulp.task('default', gulp.series([ 'linter', 'ensure-images-optimized', 'ensure-lazy-fragments' ])); gulp.task('post-build', gulp.series([ 'replace-api' ]));
JavaScript
0.000001
@@ -1207,11 +1207,10 @@ r: ' -200 +75 0x50 @@ -1512,24 +1512,19 @@ indexOf( -path.sep +'/' ) + 1);%0A @@ -1778,21 +1778,16 @@ y = -path. relative (roo @@ -1786,35 +1786,22 @@ tive -(root, f +F ile -) .split( -path.sep +'/' )%5B0%5D @@ -1989,16 +1989,215 @@ ) =%3E %7B%0A + if (err) %7B%0A console.warn(%60Failed optimizing $%7Bfile%7D%60);%0A fs.writeFileSync(path.resolve(optimizedImagesRoot, relativeFile), fs.readFileSync(file));%0A %7D else %7B%0A @@ -2234,32 +2234,34 @@ zing $%7Bfile%7D%60);%0A + fs.wri @@ -2331,16 +2331,28 @@ .body);%0A + %7D%0A @@ -2388,16 +2388,17 @@ ();%0A %7D) +; %0A%7D);%0A%0Agu @@ -2467,32 +2467,32 @@ e-api', () =%3E %7B%0A - return gulp.sr @@ -2619,16 +2619,17 @@ build')) +; %0A%7D);%0A%0Agu
465c49440f711302d47f03198660594867e6a211
add /g to regex (#2423)
gulpfile.js
gulpfile.js
const path = require('path'); const { src, dest, series, watch } = require('gulp'); const rename = require('gulp-rename'); const sass = require('node-sass'); const through2 = require('through2'); const postcss = require('gulp-postcss'); const cssnano = require('cssnano'); const sourcemaps = require('gulp-sourcemaps'); const iconfont = require('gulp-iconfont'); const iconfontCss = require('gulp-iconfont-css'); const fs = require('fs-extra'); const generateIcons = require('./src/icons/generateIcons.js'); const convertForIE = require('./build/npm-scripts/ie-convert-all.js'); const stylelint = require('stylelint'); const pficonFontName = 'pficon'; const config = { sourceFiles: [ './src/patternfly/patternfly*.scss', './src/patternfly/{components,layouts,patterns,utilities}/**/*.scss', '!./src/patternfly/**/_all.scss', '!./src/patternfly/patternfly-imports.scss' ] }; function pfIconFont() { return src(['./src/icons/PfIcons/*.svg']) .pipe( iconfontCss({ fontName: pficonFontName, path: 'scss', targetPath: 'pficon.scss', fontPath: './', cssClass: 'pf-icon' }) ) .pipe( iconfont({ fontName: pficonFontName, formats: ['ttf', 'eot', 'woff', 'woff2', 'svg'], timestamp: Math.round(Date.now() / 1000) }) ) .pipe(dest('./src/patternfly/assets/pficon/')); } function copyFA() { return src(require.resolve('@fortawesome/fontawesome/styles.css')) .pipe(rename('fontawesome.css')) .pipe(dest('./dist/assets/icons')); } function copyAssets() { return src('./src/patternfly/assets/**').pipe(dest('./public/assets')); } function minifyCSS() { return src('./dist/patternfly.css') .pipe(rename('patternfly.min.css')) .pipe(sourcemaps.init()) .pipe(postcss([cssnano()])) .pipe(sourcemaps.write('.')) .pipe(dest('./dist')); } function compileSASS() { return src(config.sourceFiles) .pipe( through2.obj((chunk, _, cb2) => { const scss = chunk.contents.toString(); try { const css = sass.renderSync({ // Pass filename for import resolution. Contents are not compiled. file: chunk.history[0], // This hack is to not include sass-utilities/placeholders.scss CSS more than once // in our production patternfly.css BUT still be able to compile individual SCSS files. // As soon as node-sass is updated to a libsass version that supports @use rule, we should // change `// @import "../../sass-utilities/all";` to `@use "../../sass-utilities/all";` data: scss.replace('// @import "../../sass-utilities/all";', '@import "../../sass-utilities/all";') }); let cssString = css.css.toString(); // TODO: Cleaner way to to do relative image assets in component CSS const relativePath = chunk.history[0].replace(chunk._base, ''); const numDirectories = relativePath.match(/\//g).length - 1; if (numDirectories > 0) { cssString = cssString.replace('./assets/images', `${'../'.repeat(numDirectories)}assets/images`); } chunk.contents = Buffer.from(cssString); stylelint .lint({ files: chunk.history[0], formatter: 'string' }) .then(data => { if (data.errored) { console.error(data.output); } }); } catch (error) { console.error(`Problem in ${path.relative(__dirname, chunk.history[0])}: ${error}`); } chunk.history.push(chunk.history[0].replace(/.scss$/, '.css')); cb2(null, chunk); }) ) .pipe(dest('./dist')); } function watchSASS() { module.exports.build(); // TODO: track files and only rebuild what's changed. Requires tracking `css.stats.includedFiles`. watch(config.sourceFiles, {}, compileSASS); } function copySource() { return Promise.all([ // Copy source files src(config.sourceFiles).pipe(dest('./dist')), // Copy excluded source files src(['./src/patternfly/_*.scss', './src/patternfly/**/_all.scss', './src/patternfly/patternfly-imports.scss']).pipe( dest('./dist') ), src('./src/patternfly/{components,layouts,patterns,utilities}/**/*.scss').pipe(dest('./dist')), src('./src/patternfly/sass-utilities/*').pipe(dest('./dist/sass-utilities')), // Assets src('./static/assets/images/**/*').pipe(dest('./dist/assets/images/')), src('./src/patternfly/assets/**/*').pipe(dest('./dist/assets/')), // Icons src('./src/icons/definitions/*').pipe(dest('./dist/icons/')), src('./src/icons/PfIcons/*').pipe(dest('./dist/icons/PfIcons/')), // For NPM src('./README.md').pipe(dest('./dist')), src('./package.json').pipe(dest('./dist')) ]); } function clean(cb) { ['./dist', './src/icons/PfIcons'].forEach(dir => fs.removeSync(dir)); cb(); } function pfIcons() { return generateIcons(); } function buildIE() { return convertForIE(); } module.exports = { build: series(clean, compileSASS, minifyCSS, pfIcons, copyFA, copySource), compileSASS, minifyCSS, buildIE, watchSASS, clean, pfIconFont, pfIcons, copyFA, copySource, copyAssets };
JavaScript
0
@@ -3082,25 +3082,28 @@ ace( -'. +/.%5C /assets +%5C /images -' +/g , %60$
67a9ca7aef59742746c8465b50f03cc0b89c1ec7
fix gulp
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gutil = require('gulp-util'); var clean = require('gulp-clean'); var rename = require('gulp-rename'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var qunit = require('gulp-qunit'); var fb = require('gulp-fb'); var paths = { src: [ 'src/__intro.js', 'src/core.js', 'src/attribute.js', 'src/class.js', 'src/utils.js', 'src/serialize.js', 'src/deserialize.js', 'src/object.js', 'src/asset.js', 'src/vec2.js', 'src/matrix3.js', 'src/rect.js', 'src/color.js', 'src/texture.js', 'src/sprite.js', 'src/atlas.js', 'src/fontInfo.js', 'src/editor/platform.js', 'src/editor/dom.js', 'src/editor/fileUtils.js', 'src/__outro.js', ], dev: 'bin/core.dev.js', min: 'bin/core.min.js', test: { src: 'test/unit/**/*.js', runner: 'test/lib/runner.html', lib_dev: [ 'bin/core.dev.js', ], lib_min: [ 'bin/core.min.js', ], }, ref: { src: [ 'test/lib/*.js', 'test/unit/_*.js', ], dest: '_references.js', }, }; // clean gulp.task('clean', function() { return gulp.src('bin/**/*', {read: false}) .pipe(clean()) ; }); // js-hint gulp.task('jshint', function() { return gulp.src(paths.src.concat( ['!**/__intro.js','!**/__outro.js'] )) .pipe(jshint({ forin: false, multistr: true, })) .pipe(jshint.reporter(stylish)) ; }); // dev gulp.task('dev', ['jshint'], function() { return gulp.src(paths.src) .pipe(concat('core.dev.js')) .pipe(gulp.dest('bin')) ; }); // min gulp.task('min', ['dev'], function() { return gulp.src('bin/core.dev.js') .pipe(rename('core.min.js')) .pipe(uglify()) .pipe(gulp.dest('bin')) ; }); ///////////////////////////////////////////////////////////////////////////// // test ///////////////////////////////////////////////////////////////////////////// gulp.task('unit-runner', function() { var js = paths.test.src; var dest = paths.test.src.split('*')[0]; return gulp.src(js, { read: false, base: './' }) .pipe(fb.toFileList()) .pipe(fb.generateRunner(paths.test.runner, dest, 'Fireball Core Test Suite', paths.test.lib_min, paths.test.lib_dev, paths.src)) .pipe(gulp.dest(dest)) ; }); gulp.task('test', ['dev', 'unit-runner'], function() { return gulp.src(['test/unit/**/*.html', '!**/*.dev.*']) .pipe(qunit()) ; }); ///////////////////////////////////////////////////////////////////////////// // tasks ///////////////////////////////////////////////////////////////////////////// // ref gulp.task('ref', function() { var src = paths.src;//.concat(['!src/__intro.js', '!src/__outro.js']); var files = paths.ref.src.concat(src); var destPath = paths.ref.dest; return fb.generateReference(files, destPath); }); // watch gulp.task('watch', function() { gulp.watch(paths.src, ['min']).on( 'error', gutil.log ); }); gulp.task('watch-self', ['watch'] ); // gulp.task('all', ['min', 'test', 'ref'] ); gulp.task('ci', ['min', 'test'] ); gulp.task('default', ['min'] );
JavaScript
0.000002
@@ -2833,19 +2833,19 @@ est', %5B' -dev +min ', 'unit
0c2e247ce185dd188a69943c63e341b3db5df7b4
exclude the export only files from test coverage
gulpfile.js
gulpfile.js
import gulp from 'gulp'; import path from 'path'; import fs from 'fs-extra'; import babel from 'gulp-babel'; import sourcemaps from 'gulp-sourcemaps'; import cp from 'child_process'; import yargs from 'yargs'; import istanbul from 'gulp-istanbul'; import babelIstanbul from 'babel-istanbul'; import mocha from 'gulp-mocha'; const TIMEOUT = 30000; const argv = yargs.argv; async function rm(filepath) { if (await fs.exists(filepath)) { if ((await fs.stat(filepath)).isDirectory()) { await Promise.all( (await fs.readdir(filepath)) .map(item => rm(path.resolve(filepath, item))) ); await fs.rmdir(filepath); } else { await fs.unlink(filepath); } } } gulp.task('clean', async () => ( rm(path.resolve(__dirname, 'build')) )); gulp.task('build', ['clean'], () => ( gulp.src(['src/**/*.js', '!src/**/*.test.js']) .pipe(sourcemaps.init()) .pipe(babel()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('build')) )); async function exec(command) { return new Promise((resolve, reject) => { cp.exec(command, (error, stdout) => { if (error) { reject(error); return; } resolve(stdout); }); }); } async function getVersionFromTag() { try { let tag = await exec('git describe --exact-match --tags $(git rev-parse HEAD)'); tag = tag.replace(/\r?\n|\r/g, ''); if (/^\d+.\d+.\d+/.test(tag)) { return tag; } return null; } catch (e) { return null; } } gulp.task('release-clean', async () => { if (!await fs.exists('release')) { await fs.mkdir('release'); } const files = (await fs.readdir('release')).filter(file => !/^\./.test(file)); for (const file of files) { await rm(path.resolve(__dirname, 'release', file)); } }); gulp.task('release-copy', ['build', 'release-clean'], () => ( gulp.src(['build/**', 'README.md', 'LICENSE']) .pipe(gulp.dest('release')) )); gulp.task('release', ['release-copy'], async () => { const packageInfo = JSON.parse(await fs.readFile('package.json')); delete packageInfo.scripts; packageInfo.main = 'index.js'; const version = await getVersionFromTag(); if (version) { packageInfo.version = version; } await fs.writeFile('release/package.json', JSON.stringify(packageInfo, null, 2)); }); function getTestSources() { const src = new Set(); // check --folder if (argv.folder) { if (Array.isArray(argv.folder)) { argv.folder.forEach((str) => { str.split(',').forEach((f) => { src.add(`${f}/**/*.test.js`); }); }); } else { argv.folder.split(',').forEach((f) => { src.add(`${f}/**/*.test.js`); }); } } // check --file if (argv.file) { if (Array.isArray(argv.file)) { argv.file.forEach((str) => { str.split(',').forEach((f) => { src.add(f); }); }); } else { argv.file.split(',').forEach((f) => { src.add(f); }); } } if (!src.size) { src.add('src/**/*.test.js'); } return [...src]; } gulp.task('pre-coverage', () => { const testSources = getTestSources(); return gulp.src(['src/**/*.js', '!src/**/*.test.js', '!src/integration-test/**/*.js']) .pipe(istanbul({ includeUntested: testSources.length === 1 && testSources[0] === 'src/**/*.test.js', instrumenter: babelIstanbul.Instrumenter, })) .pipe(istanbul.hookRequire()); }); gulp.task('test', ['pre-coverage'], () => ( gulp.src(getTestSources()) .pipe(mocha({ timeout: TIMEOUT, })) .pipe(istanbul.writeReports()) )); gulp.task('quick-test', () => ( gulp.src(getTestSources()) .pipe(mocha({ timeout: TIMEOUT, })) ));
JavaScript
0
@@ -3155,32 +3155,36 @@ gulp.src(%5B'src/ +lib/ **/*.js', '!src/ @@ -3200,41 +3200,8 @@ .js' -, '!src/integration-test/**/*.js' %5D)%0A
5cfc7081c11573b1b2d4ecb3d9842c874b6897e1
Fix a bug when sometimes sass changed are not propagated to the browser
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var concat = require('gulp-concat'); var gCheerio = require('gulp-cheerio'); var ngHtml2js = require("gulp-ng-html2js"); var htmlmin = require('gulp-htmlmin'); var streamqueue = require('streamqueue'); var rimraf = require('rimraf'); var domSrc = require('gulp-dom-src'); var rev = require('gulp-rev'); var revReplace = require('gulp-rev-replace'); var replace = require('gulp-replace'); // // BUILD // var target = 'dist'; var source = '.'; var excludeFiles = ['!'+source+'/node_modules/**']; var htmlminOptions = { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: false, removeComments: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true }; gulp.task('clean', function() { rimraf.sync(target); }); gulp.task('css', ['clean'], function() { var cssStream = domSrc({file:source+'/index.html',selector:'link[rel="stylesheet"]',attribute:'href'}); return cssStream .pipe(replace('../fonts/', 'fonts/')) .pipe(replace('app/img/', 'img/')) .pipe(concat('app.css')) .pipe(rev()) .pipe(gulp.dest(target+'/')) .pipe(rev.manifest({merge:true})) .pipe(gulp.dest('.')); }); gulp.task('js', ['clean'], function() { var templateStream = gulp .src(excludeFiles.concat(source + '/app/**/*.html')) .pipe(replace('app/img/', 'img/')) .pipe(htmlmin(htmlminOptions)) .pipe(ngHtml2js({ moduleName: "admin", prefix: "app/" })); var jsStream = domSrc({file:source+'/index.html',selector:'script[data-build!="exclude"]',attribute:'src'}); var combined = streamqueue({ objectMode: true }); combined.queue(jsStream); combined.queue(templateStream); return combined .done() .pipe(concat('app.js')) .pipe(rev()) .pipe(gulp.dest(target+'/')) .pipe(rev.manifest({merge:true})) .pipe(gulp.dest('.')) }); gulp.task('indexHtml', ['css', 'js'], function() { var manifest = gulp.src("rev-manifest.json"); return gulp .src(source+'/index.html') .pipe(gCheerio(function ($) { $('script[data-build!="exclude"]').remove(); $('link[rel="stylesheet"]').remove(); $('head').append('<link rel="stylesheet" href="app.css"><script src="app.js"></script>'); })) .pipe(revReplace({manifest: manifest})) .pipe(htmlmin(htmlminOptions)) .pipe(replace('app/', '')) .pipe(gulp.dest(target+'/')); }); gulp.task('copy', ['clean'], function(){ gulp.src(source+'/app/app.const.js').pipe(gulp.dest(target+'/')); gulp.src(source+'/app/img/**').pipe(gulp.dest(target+'/img/')); gulp.src(source+'/node_modules/font-awesome/fonts/**').pipe(gulp.dest(target+'/fonts/')); }); gulp.task('build', ['clean', 'css', 'js', 'indexHtml', 'copy']); // // DEV // var sass = require('gulp-sass'); var browserSync = require('browser-sync').create(); var watch = require('gulp-watch'); gulp.task('sass', function() { gulp .src('./app/sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./app/css/')) .pipe(browserSync.stream()); }); gulp.task('serve', ['sass'], function () { browserSync.init({ server: { baseDir: "./" } }); watch('./app/sass/**/*.scss', function() { gulp.start('sass'); }); watch(["index.html", "./app/**/*"]).on('change', browserSync.reload); });
JavaScript
0.000001
@@ -2906,18 +2906,16 @@ %09%09.src(' -./ app/sass @@ -3149,18 +3149,16 @@ %09watch(' -./ app/sass @@ -3234,18 +3234,16 @@ %22, %22 -./ app/**/* %22%5D). @@ -3238,16 +3238,57 @@ app/**/* +%22, %22!app/css/*.css%22, %22!app/sass/**/*.scss %22%5D).on('
a3fc4b9fe0d1957f48fcdc7ddd6021d7aaf40c42
remove timeout from hidDevice.receive as it's handled by drivers
lib/hidDevice.js
lib/hidDevice.js
/* * == BSD2 LICENSE == * Copyright (c) 2014, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. * == BSD2 LICENSE == */ /* eslint-disable no-param-reassign, no-use-before-define */ import { promisify } from 'util'; const debug = require('bows')('HidDevice'); module.exports = (config) => { // eslint-disable-next-line no-param-reassign config = config || {}; let webHid = null; const packets = []; const LISTEN_INTERVAL = 20; function readListener(event) { packets.push(new Uint8Array(event.data.buffer)); } function connect(deviceInfo, probe, cb) { if (arguments.length !== 3) { debug('hid connect called with wrong number of arguments!'); } debug('in HIDDevice.connect, info ', deviceInfo); config.deviceInfo = deviceInfo; (async () => { debug('Connecting using Web HID API'); webHid = deviceInfo.hidDevice; await webHid.open(); webHid.addEventListener('inputreport', readListener); })().then(() => cb()).catch(async (error) => { debug('Error during Web HID API connect:', error); return cb(error, null); }); } function removeListeners() { webHid.removeEventListener('inputreport', readListener); } function disconnect(deviceInfo, cb) { if (webHid === null) { cb(); } else { webHid.close(); debug('disconnected from HIDDevice'); cb(); } } function receive(cb) { const abortTimer = setTimeout(() => { clearInterval(listenTimer); debug('TIMEOUT'); cb(new Error('Timeout error'), null); }, 2000); const listenTimer = setInterval(() => { if (packets.length > 0) { clearTimeout(abortTimer); clearInterval(listenTimer); cb(null, packets.shift()); } }, LISTEN_INTERVAL); } function receiveTimeout(timeout) { return new Promise((resolve) => { const abortTimer = setTimeout(() => { clearInterval(listenTimer); resolve([]); }, timeout); const listenTimer = setInterval(() => { if (packets.length > 0) { clearTimeout(abortTimer); clearInterval(listenTimer); resolve(Array.from(packets.shift())); } }, LISTEN_INTERVAL); }); } async function send(bytes, callback) { const buf = new Uint8Array(bytes); if (bytes == null) { debug('just tried to send nothing!'); } else { try { // The CareSens driver is so far the only one to make use of report IDs, // as it implements serial over HID using a CP2110 chip if (config.deviceInfo.driverId === 'CareSens') { await webHid.sendReport(buf[0], buf.slice(1)); } else if (config.deviceInfo.driverId === 'GlucocardShineHID') { // Glucocard Shine Connex & Express uses report ID 1 await webHid.sendReport(0x01, buf); } else { await webHid.sendReport(0x00, buf); } callback(); } catch (err) { callback(err); } } } async function sendFeatureReport(bytes) { const buf = new Uint8Array(bytes); await webHid.sendFeatureReport(buf[0], buf.slice(1)); } return { connect, disconnect, removeListeners, receive, receiveTimeout, sendPromisified: promisify(send), send, sendFeatureReport, }; };
JavaScript
0
@@ -1994,167 +1994,8 @@ ) %7B%0A - const abortTimer = setTimeout(() =%3E %7B%0A clearInterval(listenTimer);%0A debug('TIMEOUT');%0A cb(new Error('Timeout error'), null);%0A %7D, 2000);%0A%0A @@ -2070,42 +2070,8 @@ ) %7B%0A - clearTimeout(abortTimer);%0A
e69cbe836fd7a91dbc79c7eb64b386397db6c423
put back serve command until watch command is debugged
gulpfile.js
gulpfile.js
/** * Copyright 2015 Mozilla * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var connect = require('gulp-connect'); var gulp = require('gulp'); var oghliner = require('oghliner'); var handlebars = require('gulp-handlebars'); var wrap = require('gulp-wrap'); var concat = require('gulp-concat'); var declare = require('gulp-declare'); var eslint = require('gulp-eslint'); var uglify = require('gulp-uglify'); var sourcemaps = require('gulp-sourcemaps'); var postcss = require('gulp-postcss'); var mqpacker = require('css-mqpacker'); var csswring = require('csswring'); var path = require('path'); var debounce = require('lodash.debounce'); gulp.task('default', ['build', 'offline']); gulp.task('build', ['templates', 'compress', 'css'], function(callback) { return gulp.src('app/**').pipe(gulp.dest('dist')); }); gulp.task('configure', oghliner.configure); gulp.task('deploy', function() { return oghliner.deploy({ rootDir: 'dist', }); }); gulp.task('lint', function() { return gulp.src(['app/scripts/sightinglist.js', 'app/scripts/app.js']).pipe(eslint({ 'rules':{ 'quotes': [1, 'single'], 'semi': [1, 'always'], 'comma-dangle': [1, 'always-multiline'], 'quote-props': [1, 'as-needed'] } })).pipe(eslint.format()); }); gulp.task('templates', function(){ return gulp.src('app/templates/*.html') .pipe(handlebars({ handlebars: require('handlebars') })) .pipe(wrap('Handlebars.template(<%= contents %>)')) .pipe(declare({ namespace: 'ebirdmybird', noRedeclare: true, // Avoid duplicate declarations })) .pipe(concat('handlebars-templates.js')) .pipe(gulp.dest('./app/scripts')); }); gulp.task('compress', ['templates'], function(){ return gulp.src([ 'app/scripts/d3.v3.js', 'app/scripts/c3.min.js', 'app/scripts/papaparse.min.js', 'app/scripts/handlebars-v4.0.4.js', 'app/scripts/handlebars-templates.js', 'app/scripts/sightinglist.js', 'app/scripts/app.js', ]) .pipe(sourcemaps.init()) .pipe(concat('compressed.js')) .pipe(uglify()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('app/scripts')); }); gulp.task('css', function() { var processors = [ mqpacker, csswring, ]; return gulp .src(['app/styles/*.css', '!app/styles/bundle.css']) .pipe(postcss(processors)) .pipe(concat('bundle.css')) .pipe(gulp.dest('app/styles')); }); gulp.task('offline', ['build'], function() { return oghliner.offline({ rootDir: 'dist/', fileGlobs: [ 'images/**', 'index.html', 'scripts/compressed.js', 'data/**', 'styles/**', ], }); }); gulp.task('watch', ['offline'], function() { var browserSyncCreator = require('browser-sync'); var browserSync = browserSyncCreator.create(); browserSync.init({ open: false, server: { baseDir: 'dist', ghostMode: false, notify: false, }, }); gulp.watch(['./app/styles/*.css'], ['css']); gulp.watch(['./app/scripts/*.js', '!./app/scripts/compressed.js'], ['compress']); gulp.watch(['./app/templates/*.html'], ['templates']); gulp.watch([ path.join('app', '**/*.*'), ], debounce(function () { return gulp.src('app/**').pipe(gulp.dest('dist')); }, 200)); });
JavaScript
0.000001
@@ -3170,32 +3170,126 @@ %5D,%0A %7D);%0A%7D);%0A%0A +gulp.task('serve', %5B'offline'%5D, function () %7B%0A connect.server(%7B%0A root: 'dist',%0A %7D);%0A%7D);%0A%0A gulp.task('watch
46e4573acf71bdf57585fd5c08e6d9680f5c6704
build task added
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'), changed = require('gulp-changed'), sass = require('gulp-sass'), csso = require('gulp-csso'), autoprefixer = require('gulp-autoprefixer'), browserify = require('browserify'), watchify = require('watchify'), source = require('vinyl-source-stream'), reactify = require('reactify'), del = require('del'), notify = require('gulp-notify'), browserSync = require('browser-sync'), reload = browserSync.reload; gulp.task('clean', function(cb) { del(['dist'], cb); }); gulp.task('browserSync', function() { browserSync({ server: { baseDir: './' } }) }); gulp.task('watchify', function() { var bundler = watchify(browserify('./scripts/app.jsx', watchify.args)); function rebundle() { return bundler .bundle() .on('error', notify.onError()) .pipe(source('app.js')) .pipe(gulp.dest('dist/js')) .pipe(reload({stream: true})); } bundler.transform(reactify) .on('update', rebundle); return rebundle(); }); gulp.task('styles', function() { return gulp.src('styles/main.scss') .pipe(changed('dist/css')) .pipe(sass({errLogToConsole: true})) .on('error', notify.onError()) .pipe(autoprefixer('last 1 version')) .pipe(csso()) .pipe(gulp.dest('dist/css')) .pipe(reload({stream: true})); }); gulp.task('watchTask', function() { gulp.watch('styles/main.scss', ['styles']); }); gulp.task('main', ['browserSync', 'watchTask', 'watchify', 'styles']); gulp.task('watch', ['clean'], function() { gulp.start('main'); }); gulp.task('default', function() { console.log('Run "gulp watch"'); });
JavaScript
0
@@ -319,33 +319,108 @@ -reactify = require('react +buffer = require('vinyl-buffer'),%0A reactify = require('reactify'),%0A uglify = require('gulp-ugl ify' @@ -559,16 +559,172 @@ c.reload +,%0A p = %7B%0A jsx: './scripts/app.jsx',%0A scss: 'styles/main.scss',%0A bundle: 'app.js',%0A distJs: 'dist/js',%0A distCss: 'dist/css'%0A %7D ;%0A%0Agulp. @@ -953,35 +953,21 @@ wserify( -'./scripts/ap p.jsx -' , watchi @@ -1093,24 +1093,24 @@ (source( -'app.js' +p.bundle ))%0A @@ -1126,25 +1126,24 @@ lp.dest( -' +p. dist -/js' +Js ))%0A @@ -1273,22 +1273,26 @@ p.task(' -styles +browserify ', funct @@ -1305,42 +1305,227 @@ %7B%0A -return gulp.src('styles/main +browserify(p.jsx)%0A .transform(reactify)%0A .bundle()%0A .pipe(source(p.bundle))%0A .pipe(buffer())%0A .pipe(uglify())%0A .pipe(gulp.dest(p.distJs));%0A%7D);%0A%0Agulp.task('styles', function() %7B%0A return gulp.src(p .scss -' )%0A @@ -1540,26 +1540,25 @@ changed( -' +p. dist -/c +C ss -' ))%0A . @@ -1708,26 +1708,25 @@ lp.dest( -' +p. dist -/c +C ss -' ))%0A . @@ -1809,34 +1809,22 @@ p.watch( -'styles/main +p .scss -' , %5B'styl @@ -1850,15 +1850,53 @@ sk(' -mai +watch', %5B'clea n' +%5D , +function() %7B%0A gulp.start( %5B'br @@ -1943,16 +1943,20 @@ yles'%5D); +%0A%7D); %0A%0Agulp.t @@ -1952,37 +1952,37 @@ %7D);%0A%0Agulp.task(' -watch +build ', %5B'clean'%5D, fu @@ -1998,25 +1998,82 @@ %7B%0A -gulp.start('main' +process.env.NODE_ENV = 'production';%0A gulp.start(%5B'browserify', 'styles'%5D );%0A%7D @@ -2140,16 +2140,30 @@ lp watch + or gulp build %22');%0A%7D);
df1628ff43344c93b3cb1d9b8df26234141df8b1
update version
gulpfile.js
gulpfile.js
/* 以下文件老版本会引用到,不能在服务器上彻底删除,但如果需要的话可以在当前代码分支中删除 /static/js/em-open.js /static/js/em-transfer.js /transfer.html /static/img/file_download.png */ var debug = false; const VERSION = '43.14.000'; const gulp = require('gulp'); const postcss = require('gulp-postcss'); const sass = require('gulp-sass'); const cssnano = require('cssnano'); const autoprefixer = require('autoprefixer'); const minifycss = require('gulp-minify-css'); const jshint = require('gulp-jshint'); const uglify = require('gulp-uglify'); const concat = require('gulp-concat'); const clean = require('gulp-clean'); const minifyHtml = require("gulp-minify-html"); const template = require('gulp-template'); //clean gulp.task('clean', function() { gulp.src([ 'static/css/im.css', 'static/js/main.js', 'im.html', 'easemob.js' ], { read: false } ) .pipe(clean({force: true})); }); //minifyHtml gulp.task('minifyHtml', function () { gulp.src('static/tpl/im.html') .pipe(minifyHtml()) .pipe(template({ WEBIM_PLUGIN_VERSION: VERSION })) .pipe(gulp.dest('.')); }); //postcss gulp.task('cssmin', function() { gulp.src([ 'static/css/src/global.scss', 'static/css/src/icon.scss', 'static/css/src/header.scss', 'static/css/src/body.scss', 'static/css/src/chat.scss', 'static/css/src/send.scss', 'static/css/src/theme.scss', 'static/css/src/ui.scss', 'static/css/src/mobile.scss', ]) .pipe(concat('im.css')) .pipe(template({ WEBIM_PLUGIN_VERSION: VERSION })) .pipe(sass()) .pipe(postcss([ autoprefixer({ browsers: ['ie >= 8', 'ff >= 10', 'Chrome >= 15', 'iOS >= 7', 'Android >= 4.4.4'] }), cssnano({ discardComments: { removeAll: true, }, mergeRules: false, zindex: false, reduceIdents: false, }), ])) .pipe(gulp.dest('static/css/')); }); //jshint gulp.task('lint', function() { gulp.src([ 'static/js/src/*.js', 'static/js/src/modules/*.js', ]) .pipe(jshint({ "laxcomma" : true, "laxbreak" : true, "expr" : true })) .pipe(jshint.reporter()); }); //compress gulp.task('combineJs', function() { var main = gulp.src([ 'static/js/src/lib/modernizr.js', 'static/js/src/sdk/strophe-1.2.8.js', 'static/js/src/sdk/adapter.js', 'static/js/src/sdk/webim.config.js', 'static/js/src/sdk/websdk-1.4.6.js', 'static/js/src/sdk/webrtc-1.4.4.js', 'static/js/src/modules/polyfill.js', 'static/js/src/modules/utils.js', 'static/js/src/modules/const.js', 'static/js/src/modules/ajax.js', 'static/js/src/modules/transfer.js', 'static/js/src/modules/api.js', 'static/js/src/modules/eventsEnum.js', 'static/js/src/modules/message.js', 'static/js/src/modules/paste.js', 'static/js/src/modules/leaveMessage.js', 'static/js/src/modules/satisfaction.js', 'static/js/src/modules/imgView.js', 'static/js/src/modules/uploadShim.js', 'static/js/src/modules/wechat.js', 'static/js/src/modules/site.js', 'static/js/src/modules/channel.js', 'static/js/src/modules/ui.js', 'static/js/src/modules/videoChat.js', 'static/js/src/modules/chat.js', 'static/js/src/modules/eventCollector.js', 'static/js/src/init.js' ]) .pipe(concat('main.js')); debug || main.pipe(uglify()); main.pipe(template({ WEBIM_PLUGIN_VERSION: VERSION })) .pipe(gulp.dest('static/js/')); var ejs = gulp.src([ 'static/js/src/modules/utils.js', 'static/js/src/modules/transfer.js', 'static/js/src/modules/eventsEnum.js', 'static/js/src/modules/notify.js', 'static/js/src/modules/titleSlide.js', 'static/js/src/modules/iframe.js', 'static/js/src/userAPI.js', ]) .pipe(concat('easemob.js')); debug || ejs.pipe(uglify()); ejs.pipe(template({ WEBIM_PLUGIN_VERSION: VERSION })) .pipe(gulp.dest('.')); var transfer = gulp.src([ 'static/js/src/modules/ajax.js', 'static/js/src/modules/transfer.js', 'static/js/src/modules/api.js', ]) .pipe(concat('em-transfer.js')); debug || transfer.pipe(uglify()); transfer.pipe(gulp.dest('static/js/')); }); //build default debug = false gulp.task('build', ['clean'], function() { gulp.start('cssmin', 'combineJs', 'minifyHtml'); }); gulp.task('dev', function(){ debug = true; gulp.start('build'); }) gulp.task('watch', function() { gulp.start('dev'); gulp.watch(['static/js/src/*.js', 'static/js/src/*/*.js'], ['combineJs']); gulp.watch(['static/css/src/*.scss'], ['cssmin']); gulp.watch(['static/tpl/im.html'], ['minifyHtml']); });
JavaScript
0
@@ -189,17 +189,17 @@ 43.14.00 -0 +1 ';%0A%0Acons
cd366f2ad8216ca6e66be0772c3ddf58f64eda0e
Modify build.
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var browserSync = require('browser-sync'); var eyeglass = require('eyeglass'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var prefix = require('gulp-autoprefixer'); var plumber = require('gulp-plumber'); var notify = require('gulp-notify'); var rename = require('gulp-rename'); var del = require('del'); var postcss = require('gulp-postcss'); var cssnano = require('cssnano'); var flexibility = require('postcss-flexibility'); var jade = require('gulp-jade'); var md = require('jstransformer')(require('jstransformer-markdown-it')); var shortid = require('shortid'); var _ = require('lodash'); var jadeInheritance = require('gulp-jade-inheritance'); var changed = require('gulp-changed'); var cached = require('gulp-cached'); var gulpif = require('gulp-if'); var dist = './dist'; var nav = []; gulp.task('default', ['styles', 'views', 'server', 'watch']); gulp.task('server', function () { return browserSync.init({ server: { injectChanges: true, baseDir: dist } }); }); gulp.task('watch', function(){ global.isWatching = true; gulp.watch('./scss/**/*.scss', ['styles']); gulp.watch('./content/**/*', ['views']); gulp.watch(dist + '/**/*.html').on('change', debounce(browserSync.reload, 500)); gulp.watch(dist + '/**/*.js').on('change', debounce(browserSync.reload, 500)); }); gulp.task('styles', function () { return gulp.src('./scss/**/*.scss') .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })) .pipe(sourcemaps.init()) .pipe(sass(eyeglass())) .pipe(prefix({ browsers: ['last 5 Chrome versions', 'last 5 Firefox versions', 'Safari >= 6', 'ie >= 9', 'Edge >= 1', 'iOS >= 8', 'Android >= 4.3'] })) .pipe(postcss([flexibility()])) .pipe(sourcemaps.write()) .pipe(gulp.dest(dist + '/css')) .pipe(postcss([cssnano()])) .pipe(rename({ suffix: '.min' })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(dist + '/css')) .pipe(browserSync.stream({ match: '**/*.css' })) ; }); gulp.task('clean', function () { del(['**/*/.DS_Store']); del([dist + '/**/*']); }); gulp.task('build', ['clean', 'styles', 'views'], function () { }); gulp.task('copy-js', function () { del([dist + '/**/*.js']); gulp.src(['./content/**/*.js']).pipe(gulp.dest(dist)); }); gulp.task('views', ['copy-js'], function () { var dir = './content'; directoryTreeToObj(dir, function (err, res) { if (err) console.error(err); var colorFamilies = require('./content/design/color/_color-families.json'); gulp.src(['./content/**/*.jade', '!./content/**/_*.jade']) .pipe(changed(dist, { extension: '.html' })) .pipe(gulpif(global.isWatching, cached('jade'))) .pipe(jadeInheritance({ basedir: dir })) .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })) .pipe(jade({ basedir: __dirname + '/content', pretty: true, md: md, locals: { nav: res, colorFamilies: colorFamilies, shortid: shortid, _: _ } })) .pipe(gulp.dest(dist)) ; }); }); var directoryTreeToObj = function(dir, done) { var fs = require('fs'); var path = require('path'); var results = []; fs.readdir(dir, function(err, files) { if (err) return done(err); files = files.filter(function (file) { return file.indexOf('_') !== 0; }); var pending = files.length; if (!pending) return done(null, { name: path.basename(dir), type: 'folder', children: results }); files.forEach(function(file) { file = path.resolve(dir, file); fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { directoryTreeToObj(file, function(err, res) { results.push({ name: path.basename(file), type: 'folder', children: res }); if (!--pending) done(null, results); }); } else { results.push({ type: 'file', name: path.basename(file) }); if (!--pending) done(null, results); } }); }); }); }; function throttle (callback, limit) { var wait = false; return function () { if (!wait) { callback.call(); wait = true; setTimeout(function () { wait = false; }, limit); } } } function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }
JavaScript
0
@@ -2329,26 +2329,8 @@ ws'%5D -, function () %7B%0A%0A%7D );%0A%0A @@ -2344,17 +2344,16 @@ sk('copy -- js', fun @@ -2364,24 +2364,29 @@ n () %7B%0A del +.sync (%5Bdist + '/* @@ -2392,16 +2392,39 @@ **/*.js' +, dist + '/content/_js' %5D);%0A gu @@ -2506,17 +2506,16 @@ , %5B'copy -- js'%5D, fu @@ -3566,16 +3566,17 @@ return +( file.ind @@ -3590,16 +3590,48 @@ ') !== 0 +) && (file.indexOf('.js') == -1) ;%0A %7D)
7baa60230492c34ca9b1bb881731e0f6b5827d25
Add renaming of index.js to memefy.js
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const browserify = require('gulp-browserify'); const pkg = require('./package.json') gulp.task('build', () => gulp.src(pkg.main) .pipe(browserify({ insertGlobals : true, debug : !gulp.env.production })) .pipe(gulp.dest('dist')) ); gulp.task('default', ['build']);
JavaScript
0.000002
@@ -66,24 +66,63 @@ owserify');%0A +const rename = require(%22gulp-rename%22);%0A const pkg = @@ -146,16 +146,17 @@ e.json') +; %0A%0Agulp.t @@ -222,18 +222,16 @@ y(%7B%0A - insertGl @@ -235,17 +235,16 @@ tGlobals - : true,%0A @@ -251,16 +251,13 @@ - debug - : !g @@ -279,18 +279,16 @@ ion%0A - %7D))%0A .p @@ -279,24 +279,90 @@ ion%0A %7D))%0A +.pipe(rename(function(path) %7B%0A path.basename = pkg.name;%0A %7D))%0A .pipe(gulp
703e38a114d943a3c07d6250e74e322bd7ccc18c
Update gulpfile.js
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var source = require('vinyl-source-stream'); var browserify = require('browserify'); var stringify = require('stringify'); var uglify = require('gulp-uglify'); var less = require('gulp-less'); var minifiyCss = require('gulp-minify-css'); var rename = require('gulp-rename'); var header = require('gulp-header'); var streamify = require('gulp-streamify'); var merge = require('merge-stream'); var gulpsync = require('gulp-sync')(gulp); var del = require('del'); var eslint = require('gulp-eslint'); var pkg = require('./package.json'); var banner = [ '/**', ' * @fileoverview ${name}', ' * @author ${author}', ' * @version ${version}', ' * @license ${license}', ' * @link ${repository.url}', ' */', '' ].join('\n'); var PATH_DIST = 'dist/'; var PATH_BUILD = 'build/'; var PATH_SAMPLES = 'samples/'; var PATH_LIB = 'lib/'; var PATH_MAPS = 'maps/'; function bundle(debug) { var b = browserify('src/js/chart.js', {debug: debug}); b.add('src/js/plugins/pluginRaphael.js'); b.transform(stringify(['.html'])); return b.bundle() .pipe(source('chart.js')); } function complieLess() { return gulp.src('src/less/style.less') .pipe(less()) .pipe(rename('chart.css')); } gulp.task('build-js', function() { return bundle(true) .pipe(gulp.dest(PATH_BUILD)); }); gulp.task('build-css', function() { return complieLess() .pipe(gulp.dest(PATH_BUILD)); }); gulp.task('build', ['build-js', 'build-css'], function() { gulp.watch('src/js/**/*', ['build-js']); gulp.watch('src/less/**/*', ['build-css']); }); gulp.task('clean', function(callback) { del([ PATH_DIST, PATH_SAMPLES + PATH_DIST, PATH_SAMPLES + PATH_LIB ], callback); }); gulp.task('deploy-js', ['lint'], function() { return bundle(false) .pipe(streamify(header(banner, pkg))) .pipe(gulp.dest(PATH_DIST)) .pipe(streamify(uglify())) .pipe(rename({extname: '.min.js'})) .pipe(streamify(header(banner, pkg))) .pipe(gulp.dest(PATH_DIST)) .pipe(gulp.dest(PATH_SAMPLES + PATH_DIST)); }); gulp.task('deploy-css', function() { return complieLess() .pipe(streamify(header(banner, pkg))) .pipe(gulp.dest(PATH_DIST)) .pipe(minifiyCss({compatibility: 'ie7'})) .pipe(rename({extname: '.min.css'})) .pipe(streamify(header(banner, pkg))) .pipe(gulp.dest(PATH_DIST)) .pipe(gulp.dest(PATH_SAMPLES + PATH_DIST)); }); gulp.task('copy-files', function() { return merge( gulp.src(PATH_MAPS + '*') .pipe(gulp.dest(PATH_DIST + PATH_MAPS)) .pipe(gulp.dest(PATH_SAMPLES + PATH_DIST + PATH_MAPS)), gulp.src([ PATH_LIB + 'tui-code-snippet/code-snippet.min.js', PATH_LIB + 'tui-component-effects/effects.min.js', PATH_LIB + 'raphael/raphael-min.js']) .pipe(gulp.dest(PATH_SAMPLES + PATH_LIB)) ); }); gulp.task('lint', function() { return gulp.src(['src/js/**/*.js']) .pipe(eslint()) .pipe(eslint.failAfterError()); }); gulp.task('deploy', gulpsync.sync(['clean', 'deploy-js', 'deploy-css', 'copy-files'])); gulp.task('default', ['build']);
JavaScript
0.000008
@@ -568,24 +568,73 @@ ge.json');%0A%0A +var readableTimestamp = (new Date()).toString();%0A var banner = @@ -797,24 +797,74 @@ tory.url%7D',%0A + ' * bundle created at %22' + readableTimestamp,%0A ' */',%0A
f04d38d541bb1f907f5a669efdf5f575414fa55e
Update gulp build for production (#29)
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'), concat = require('gulp-concat'), mainBowerFiles = require('main-bower-files'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), less = require('gulp-less'), cleanCSS = require('gulp-clean-css'), jsFiles = ['src/js/*']; gulp.task("concatVendorScripts", function () { gulp.src(mainBowerFiles({ filter: '**/*.js' })) .pipe(concat("vendor.js")) .pipe(gulp.dest("assets/js")); }); gulp.task("concatApplicationScripts", function () { gulp.src(['src/js/*.js']) .pipe(concat("application.js")) .pipe(gulp.dest("assets/js")); }); gulp.task("compileVendorStyleCss", function () { gulp.src(mainBowerFiles({ filter: '**/*.css' })) .pipe(concat("vendor-css.css")) .pipe(gulp.dest("assets/css")); }); gulp.task("compileVendorStyles", function () { gulp.src(mainBowerFiles({ filter: '**/*.less' })) .pipe(less()) .pipe(concat("vendor-less.css")) .pipe(gulp.dest("assets/css")); }); gulp.task("compileApplicationStyles", function () { gulp.src(['src/css/*.css']) .pipe(less()) .pipe(concat("application.css")) .pipe(gulp.dest("assets/css")); }); gulp.task("minifyVendorScripts", function () { gulp.src("assets/js/vendor.js") .pipe(uglify()) .pipe(rename('vendor.min.js')) .pipe(gulp.dest("assets/js")); }); gulp.task("minifyApplicationScripts", function () { gulp.src("assets/js/application.js") .pipe(uglify()) .pipe(rename('application.min.js')) .pipe(gulp.dest("assets/js")); }); gulp.task("minifyVendorStyles", function () { gulp.src("assets/css/vendor.css") .pipe(cleanCSS()) .pipe(rename('vendor.min.css')) .pipe(gulp.dest("assets/css")); }); gulp.task("minifyApplicationStyles", function () { gulp.src("assets/css/application.css") .pipe(cleanCSS()) .pipe(rename('application.min.css')) .pipe(gulp.dest("assets/css")); }); gulp.task('copyFonts', function() { gulp.src([ 'bower_components/bootstrap/fonts/glyphicons-halflings-regular.*' ]) .pipe(gulp.dest('assets/fonts/')); }); // Single task gulp.task("createDevScripts", ['concatVendorScripts', 'concatApplicationScripts']); gulp.task("createProdScripts", ['createDevScripts', 'minifyVendorScripts', 'minifyApplicationScripts']); gulp.task("createDevStyles", ['compileVendorStyles', 'compileVendorStyleCss', 'compileApplicationStyles', 'copyFonts']); gulp.task("createProdStyles", ['createDevStyles', 'minifyVendorStyles', 'minifyApplicationStyles']); gulp.task("test", ['createDevScripts', 'createDevStyles'])
JavaScript
0
@@ -1879,33 +1879,34 @@ %7B%0A gulp.src( -%22 +%5B' assets/css/appli @@ -1900,32 +1900,23 @@ ets/css/ -application +* .css -%22 +'%5D )%0A @@ -2689,16 +2689,80 @@ eateDevStyles'%5D) +;%0Agulp.task(%22build%22, %5B'createProdScripts', 'createProdStyles'%5D);
481dacdc898b16fa3582520fac7fd7f3182c21d0
add fetch features
src/routes/Fetch/modules/fetch.js
src/routes/Fetch/modules/fetch.js
import { browserHistory } from 'react-router' import cookie from 'react-cookie'; const SpotifyWebApi = require('spotify-web-api-js'); // ------------------------------------ // Constants // ------------------------------------ export const FETCH_API_CALLED = 'FETCH_API_CALLED' export const FETCH_FEATURES_CALLED = 'FETCH_FEATURES_CALLED' export const FETCH = 'FETCH_MATRIX_STORED' export const REDIRECT_TO_FEATURES = 'REDIRECT_TO_FEATURES' // ------------------------------------ // Actions // ------------------------------------ const spotify = new SpotifyWebApi(); const access_token = cookie.load('spotify_access_token'); spotify.setAccessToken(access_token); export function calledApi(offset, songList = [], total) { return (dispatch, getState) => { // Get the first set of tracks so we can get the total spotify.getMySavedTracks({offset}).then(function(data) { // Update the total number of tracks (for pagination purposes) const total = data.total; const tracks = data.items.map((item) => item.track); console.log(tracks); dispatch({ type: FETCH_API_CALLED, payload: { tracks, total } }); }); } } export function fetchFeatures(tracks) { return (dispatch, getState) => { return new Promise((listCompleteResolve) => { let features = []; let promises = []; const limit = 100; let current = 0; // Iterate through the tracks array and create slices of size 100 to query the API with while(current < tracks.length) { let upper = current + limit <= tracks.length ? current + limit : tracks.length ; const subarray = tracks.slice(current, upper); let ids = subarray.map(function(track) { return track.id }); let featuresPromise = spotify.getAudioFeaturesForTracks(ids); promises.push(featuresPromise); current += upper; } Promise.all(promises).then(function(results) { const features = []; results.forEach(function(result) { // console.log(result); result.audio_features.forEach(function(feature) { features.push(feature); }); }); dispatch({ type: FETCH_FEATURES_CALLED, payload: { features } }); }).catch(function(err) { console.log('Aw shit: ', err); }) }) } } export function redirectToFeatures() { browserHistory.push('/features') return { type: REDIRECT_TO_FEATURES } } export const actions = { calledApi, redirectToFeatures } // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { [FETCH_API_CALLED] : (state, action) => { let { offset, songList } = state; const { total, tracks } = action.payload; const newSonglist = songList.slice(0).concat(tracks); const newOffset = newSonglist.length; console.log(newOffset, newSonglist); return { ...state, songList: newSonglist, offset: newOffset, total } }, [FETCH_FEATURES_CALLED] : (state, action) => { const { features } = action.payload; console.log('action total', state.total); return { ...state, features } } } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { songList: [], offset: 0, total: 0, features: [] } export default function fetchReducer (state = initialState, action) { const handler = ACTION_HANDLERS[action.type]; return handler ? handler(state, action) : state; }
JavaScript
0.000001
@@ -2578,16 +2578,33 @@ ledApi,%0A + fetchFeatures,%0A redire
36446ceb1b601a853ec52abaa815681e8488237d
update release tasks
gulpfile.js
gulpfile.js
/** * The MIT License (MIT) * * Copyright (c) 2014,205,2016 Mickael Jeanroy <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ const path = require('path'); const gulp = require('gulp'); const KarmaServer = require('karma').Server; const git = require('gulp-git'); const bump = require('gulp-bump'); const gulpFilter = require('gulp-filter'); const tagVersion = require('gulp-tag-version'); const rollup = require('rollup'); const eslint = require('gulp-eslint'); const del = require('del'); const rollupConf = require('./rollup.conf.js'); const options = require('./conf.js'); /** * Start Karma Server and run unit tests. * * @param {boolean} singleRun If it runs once and exit or not. * @param {function} done The done callback. * @return {void} */ function startKarma(singleRun, done) { const opts = { configFile: path.join(options.root, '/karma.conf.js'), }; if (singleRun) { opts.autoWatch = true; opts.singleRun = true; opts.browsers = ['PhantomJS']; } const karma = new KarmaServer(opts, () => done()); karma.start(); } gulp.task('lint', ['clean'], () => { const sources = [ path.join(options.root, '*.js'), path.join(options.src, '**', '*.js'), path.join(options.test, '**', '*.js'), ]; return gulp.src(sources) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('test', ['clean'], (done) => { startKarma(true, done); }); gulp.task('tdd', ['clean'], (done) => { startKarma(false, done); }); gulp.task('clean', () => { return del([ options.dest, ]); }); gulp.task('build', ['clean', 'lint', 'test'], () => { return rollup .rollup(rollupConf) .then((bundle) => bundle.write(rollupConf)); }); // Release tasks ['minor', 'major', 'patch'].forEach(function(level) { gulp.task('release:' + level, ['build'], function() { const packageJsonFilter = gulpFilter((file) => file.relative === 'package.json'); const src = ['package.json', 'bower.json'].map((file) => path.join(options.root, file)); return gulp.src(src) .pipe(bump({type: level})) .pipe(gulp.dest(options.root)) .pipe(git.add({args: '-f'})) .pipe(git.commit('release: release version')) .pipe(packageJsonFilter) .pipe(tagVersion()); }); }); gulp.task('release', ['release:minor']);
JavaScript
0.000001
@@ -2865,25 +2865,25 @@ lp.task( -' +%60 release: ' + leve @@ -2878,17 +2878,17 @@ ase: -' + +$%7B level +%7D%60 , %5B' @@ -2919,24 +2919,17 @@ const -packageJ +j sonFilte @@ -2947,170 +2947,388 @@ ter( -(file) =%3E file.relative === 'package.json');%0A const src = %5B'package.json', 'bower.json'%5D.map((file) =%3E path.join(options.root, file));%0A%0A return gulp.src(src +'**/*.json', %7Brestore: true%7D);%0A const pkgJsonFilter = gulpFilter('**/package.json', %7Brestore: true%7D);%0A const bundleFilter = gulpFilter('**/*.js', %7Brestore: true%7D);%0A%0A const src = %5B%0A path.join(options.root, 'package.json'),%0A path.join(options.root, 'bower.json'),%0A options.dest,%0A %5D;%0A%0A return gulp.src(src)%0A%0A // Bump version.%0A .pipe(jsonFilter )%0A @@ -3395,16 +3395,74 @@ .root))%0A + .pipe(jsonFilter.restore)%0A%0A // Commit release.%0A .p @@ -3539,16 +3539,38 @@ rsion')) +%0A%0A // Create tag. %0A . @@ -3575,22 +3575,18 @@ .pipe(p -ackage +kg JsonFilt @@ -3614,16 +3614,235 @@ rsion()) +%0A .pipe(pkgJsonFilter.restore)%0A%0A // Remove generated bundle and commit for the next release.%0A .pipe(bundleFilter)%0A .pipe(git.rm(%7Bargs: '-r'%7D))%0A .pipe(git.commit('release: prepare next release')) ;%0A %7D);%0A
132822c44fc6916a01a547a2cfb70e1305b737ea
Update gulp to change name of generated file
gulpfile.js
gulpfile.js
var gulp = require('gulp'), rimraf = require('rimraf'), jshint = require('gulp-jshint'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), insert = require('gulp-insert'), p = require('./package.json') ; //Folders and annotation var src = 'src/', dest = 'dist/', annotation = '/* ' + p.name + ' v' + p.version + ' | Copyright (c) ' + new Date().getFullYear() + ' ' + p.homepage + ' | ' + p.license + ' license */\n'; gulp.task('clean', function(cb) { rimraf(dest, cb); }); gulp.task('scripts', ['clean'], function() { return gulp.src(src + '*.js') .pipe(jshint()) .pipe(jshint.reporter()) .pipe(uglify()) .pipe(rename('jquery.seslider-' + p.version + '.min.js')) .pipe(insert.prepend(annotation)) .pipe(gulp.dest(dest)); ; }); gulp.task('default', ['scripts'], function() { });
JavaScript
0
@@ -726,26 +726,8 @@ ider --' + p.version + ' .min
8c852d90fa0fa1737a9dd5cb82a36367453c4259
Rename CUDA to CUDA C++ in language dropdown (#2938)
lib/languages.js
lib/languages.js
// Copyright (c) 2017, Compiler Explorer Authors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import path from 'path'; import fs from 'fs-extra'; import _ from 'underscore'; /*** * Language object type * * @typedef {Object} CELanguage * @property {string} id - Id of language. Added programmatically based on CELanguages key * @property {string} name - UI display name of the language * @property {string} monaco - Monaco Editor language ID (Selects which language Monaco will use to highlight the code) * @property {string[]} extensions - Usual extensions associated with the language. First one is used as file input etx * @property {string[]} alias - Different ways in which we can also refer to this language * @property {string} [formatter] - Format API name to use (See https://godbolt.org/api/formats) */ /*** * Currently supported languages on Compiler Explorer * * @typedef {Object.<string, CELanguage>} CELanguages */ /*** * Current supported languages * @type {CELanguages} */ export const languages = { 'c++': { name: 'C++', monaco: 'cppp', extensions: ['.cpp', '.cxx', '.h', '.hpp', '.hxx', '.c', '.cc', '.ixx'], alias: ['gcc', 'cpp'], previewFilter: /^\s*#include/, formatter: 'clangformat', }, llvm: { name: 'LLVM IR', monaco: 'llvm-ir', extensions: ['.ll'], alias: [], }, cppx: { name: 'Cppx', monaco: 'cppp', extensions: ['.cpp', '.cxx', '.h', '.hpp', '.hxx', '.c'], alias: [], previewFilter: /^\s*#include/, }, cppx_gold: { name: 'Cppx-Gold', monaco: 'cppx-gold', extensions: ['.usyntax', '.cpp', '.cxx', '.h', '.hpp', '.hxx', '.c'], alias: [], }, cppx_blue: { name: 'Cppx-Blue', monaco: 'cppx-blue', extensions: ['.blue', '.cpp', '.cxx', '.h', '.hpp', '.hxx', '.c'], alias: [], }, c: { name: 'C', monaco: 'nc', extensions: ['.c', '.h'], alias: [], previewFilter: /^\s*#include/, }, openclc: { name: 'OpenCL C', monaco: 'openclc', extensions: ['.cl', '.ocl'], alias: [], }, cpp_for_opencl: { name: 'C++ for OpenCL', monaco: 'cpp-for-opencl', extensions: ['.clcpp', '.cl', '.ocl'], alias: [], }, rust: { name: 'Rust', monaco: 'rust', extensions: ['.rs'], alias: [], formatter: 'rustfmt', }, d: { name: 'D', monaco: 'd', extensions: ['.d'], alias: [], }, go: { name: 'Go', monaco: 'go', extensions: ['.go'], alias: [], }, ispc: { name: 'ispc', monaco: 'ispc', extensions: ['.ispc'], alias: [], }, haskell: { name: 'Haskell', monaco: 'haskell', extensions: ['.hs', '.haskell'], alias: [], }, java: { name: 'Java', monaco: 'java', extensions: ['.java'], alias: [], }, kotlin: { name: 'Kotlin', monaco: 'kotlin', extensions: ['.kt'], alias: [], }, scala: { name: 'Scala', monaco: 'scala', extensions: ['.scala'], alias: [], }, ocaml: { name: 'OCaml', monaco: 'ocaml', extensions: ['.ml', '.mli'], alias: [], }, python: { name: 'Python', monaco: 'python', extensions: ['.py'], alias: [], }, swift: { name: 'Swift', monaco: 'swift', extensions: ['.swift'], alias: [], }, pascal: { name: 'Pascal', monaco: 'pascal', extensions: ['.pas', '.dpr'], alias: [], }, fortran: { id: 'fortran', name: 'Fortran', monaco: 'fortran', extensions: ['.f90', '.F90', '.f95', '.F95', '.f'], alias: [], }, assembly: { name: 'Assembly', monaco: 'asm', extensions: ['.asm'], alias: ['asm'], }, analysis: { name: 'Analysis', monaco: 'asm', extensions: ['.asm'], // maybe add more? Change to a unique one? alias: ['tool', 'tools'], }, cuda: { name: 'CUDA', monaco: 'cuda', extensions: ['.cu'], alias: ['nvcc'], monacoDisassembly: 'ptx', }, zig: { name: 'Zig', monaco: 'zig', extensions: ['.zig'], alias: [], }, clean: { name: 'Clean', monaco: 'clean', extensions: ['.icl'], alias: [], }, ada: { name: 'Ada', monaco: 'ada', extensions: ['.adb', '.ads'], alias: [], }, nim: { name: 'Nim', monaco: 'nim', extensions: ['.nim'], alias: [], }, crystal: { name: 'Crystal', monaco: 'crystal', extensions: ['.cr'], alias: [], }, circle: { name: 'C++ (Circle)', monaco: 'cppcircle', extensions: ['.cpp', '.cxx', '.h', '.hpp', '.hxx', '.c'], alias: [], previewFilter: /^\s*#include/, }, ruby: { name: 'Ruby', monaco: 'ruby', extensions: ['.rb'], alias: [], monacoDisassembly: 'asmruby', }, cmake: { name: 'CMake', monaco: 'cmake', extensions: ['.txt'], alias: [], }, }; _.each(languages, (lang, key) => { lang.id = key; try { lang.example = fs.readFileSync(path.join('examples', lang.id, 'default' + lang.extensions[0]), 'utf8'); } catch (error) { lang.example = 'Oops, something went wrong and we could not get the default code for this language.'; } });
JavaScript
0.000001
@@ -5637,16 +5637,20 @@ e: 'CUDA + C++ ',%0A
44900923d38cdfb104283b7943185f131cd45f4f
use the number helper for number rules
lib/lexer/dsl.js
lib/lexer/dsl.js
var elf = require ( "../runtime/runtime" ) , Rule = require ( "./rule/rule" ) ; var LexerDSL = elf.Object.clone({ rule: function (name, regex, action, arity) { var rule = Rule.create(name, regex, action, arity); this.rules.push(rule); return rule; }, name : function (regex, helper) { return this.rule('name', regex, helper); }, number : function (regex, helper) { return this.rule("number", regex, helper || this.helpers.literal) }, string : function (regex, helper) { return this.rule("string", regex, helper || this.helpers.literal) }, regex : function (regex, helper) { return this.rule("regex", regex, helper || this.helpers.literal); }, operator : function (regex, helper) { return this.rule("operator", regex, helper); }, eol : function (regex, helper) { return this.rule("eol", regex, helper || this.helpers.value("(eol)")); }, skip : function (regex) { return this.rule("(skip)", regex, this.helpers.skip) }, helpers: { number : function (str) { return parseFloat(str, 10); }, literal : function (str) { return parseFloat(str, 10) ? parseFloat(str, 10) : str.substring(1, str.length - 1); }, skip : function ( ) { return null; }, value : function (val) { return function () { return val; } }, trim : function (str) { return str.trim(); } } }); module.exports = LexerDSL;
JavaScript
0.000004
@@ -461,39 +461,38 @@ %7C%7C this.helpers. -literal +number )%0A %7D,%0A%0A string @@ -1155,52 +1155,8 @@ turn - parseFloat(str, 10) ? parseFloat(str, 10) : str
eeba85dd6d155eaae30234368e7dd7d0dd6cd55d
Add favicons
src/server/frontend/html.react.js
src/server/frontend/html.react.js
import Component from '../../client/components/component.react'; import React from 'react'; export default class Html extends Component { static propTypes = { bodyHtml: React.PropTypes.string.isRequired, isProduction: React.PropTypes.bool.isRequired, title: React.PropTypes.string.isRequired, version: React.PropTypes.string.isRequired }; render() { // Only for production. For dev, it's handled by webpack with livereload. const linkStyles = this.props.isProduction && <link href={`/build/app.css?v=${this.props.version}`} rel="stylesheet" />; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <title>{this.props.title}</title> {linkStyles} </head> <body dangerouslySetInnerHTML={{__html: this.props.bodyHtml}} /> </html> ); } }
JavaScript
0.000006
@@ -84,16 +84,51 @@ 'react'; +%0Aimport favicons from './favicons'; %0A%0Aexport @@ -885,16 +885,53 @@ /title%3E%0A + %7B/* this.renderLinks() */%7D%0A @@ -1060,10 +1060,439 @@ );%0A %7D%0A%0A + renderLinks() %7B%0A return favicons.map(this.renderLink, this)%0A %7D%0A%0A renderLink(link, key) %7B%0A const %7BisProduction, version%7D = this.props;%0A // TODO: Why is not es7.objectRestSpread enabled?%0A //const %7Bhref, ...linkProps%7D = link;%0A const path = !isProduction ? '/assets/favicon/' : '/';%0A%0A return (%0A %3Clink%0A key=%7Bkey%7D%0A href=%7B%60$%7Bpath%7D$%7Bhref%7D?v=$%7Bversion%7D%60%7D%0A %7B...linkProps%7D%0A /%3E%0A )%0A %7D%0A %7D%0A
51ea5425778763abb6c403366e1c6e264232e09b
fix build
gulpfile.js
gulpfile.js
var gulp = require('gulp'), clean = require('gulp-clean'), shell = require('gulp-shell'), jsdoc = require("gulp-jsdoc"), webserver = require('gulp-webserver'); // steps // 1. clean /public folder // 2. generate new /public with hexo // 3. replace /public/downloads with /source/downloads // 4. generate api docs to /public // 1 gulp.task('clean-public', function(){ return gulp.src('public', {read: false}) .pipe(clean()); }); // 2 gulp.task('generate-hexo', ['clean-public'], shell.task(['node ./node_modules/hexo/bin/hexo generate'], {cwd: './'})); // 3 gulp.task('clean-public-downloads', ['generate-hexo'], function(){ return gulp.src('public/downloads', {read: false}) .pipe(clean()); }); gulp.task('copy-source-download', ['clean-public-downloads'] ,function() { return gulp.src('source/downloads/**') .pipe(gulp.dest('public/downloads')); }); // 4 gulp.task('docs', ['generate-hexo'], function() { return gulp.src("konva.js") .pipe(jsdoc('./public/api', { "path": "ink-docstrap", "cleverLinks" : false, "monospaceLinks" : false, "dateFormat" : "ddd MMM Do YYYY", "outputSourceFiles" : true, "outputSourcePath" : true, "systemName" : "Konva", "footer" : "", "copyright" : "Konva Copyright © 2015 The contributors to the Konva project.", "navType" : "vertical", "theme" : "cosmo", "linenums" : true, "collapseSymbols" : false, "inverseNav" : true, "highlightTutorialCode" : true, "analytics" : { "ua" : "UA-54202824-2", "domain" : "http://konvajs.github.io" } })) }); gulp.task('server', function() { gulp.src('public') .pipe(webserver({})); }); gulp.task('generate', [ 'clean-public', 'generate-hexo', 'clean-public-downloads', 'copy-source-download', // 'docs' ]); gulp.task('default', ['generate', 'server']);
JavaScript
0.000001
@@ -1974,11 +1974,8 @@ ',%0A - // 'do
a8ba05a4e7f39c97ea6bb30f0db3ec7ee3971d41
fix typo
lib/matrix-3d.js
lib/matrix-3d.js
var math = require('mathjs'); /* * Conversion Functions */ // Convert Degree to Radian var d2r = function(d) { return (d * math.pi )/180; } module.exports.d2r = d2r; // Convert Radian to Degree var r2d = function(r) { return (180 * r) / math.pi; } module.exports.r2d = r2d; // Roundoff to 0 Cos, cos(pi/2) is a very small floating number in JS. this function will make it to 0. // param: r - radian var cos_roundoff = function(r) { var cos = math.cos(r); if ((cos | 0) === 0) { cos = 0; } return cos; } module.exports.cos_roundoff = cos_roundoff; // Roundoff to 0 Sin var sin_roundoff = function(r) { var sin = math.sin(r); if ((sin | 0) === 0) { sin = 0; } return sin; } module.exports.sin_roundoff = sin_roundoff; /* * Actual 3D matrix operation. */ // Return the 4x4 matrix for Translation var translate = function(x, y, z) { var m = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; m[0][3] = x || 0; m[1][3] = y || 0; m[2][3] = z || 0; return m; } module.exports.translate = translate; var translate_x = function(x) { return translate(x, 0, 0); } module.exports.translate_x = translate_x; var translate_y = function(y) { return translate(0, y, 0); } module.exports.translate_y = translate_y; var translate_z = function(z) { return translate(0, 0, z); } module.exports.translate_z = translate_z; // Return the 4x4 matrix for Rotation. /* Rotate on X-axis, * param: d - degree */ var rotate_x = function(d) { var m = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; var r = d2r(d); var cos = cos_roundoff(r); var sin = sin_roundoff(r); m[1][1] = cos; m[1][2] = -1 * sin; m[2][1] = sin; m[2][2] = cos; return m; } module.exports.rotate_x = rotate_x; var rotate_y = function(d) { var m = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; var r = d2r(d); var cos = cos_roundoff(r); var sin = sin_roundoff(r); m[0][0] = cos; m[0][2] = sin; m[2][0] = -1 * sin; m[2][2] = cos; return m; } module.exports.rotate_y = rotate_y; var rotate_z = function(d) { var m = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]; var r = d2r(d); var cos = cos_roundoff(r); var sin = sin_roundoff(r); m[0][0] = cos; m[0][1] = -1 * sin; m[1][0] = sin; m[1][1] = cos; return m; } module.exports.rotate_z = rotate_z; var rotate_2d = rotate_z; module.exports.rotate_2d = rotate_2d; tranlate_y
JavaScript
0.999991
@@ -2414,16 +2414,5 @@ d;%0A%0A -tranlate_y%0A %0A
4d1baaf0b907f4bfa428836bb3fcb3bdb268d418
Add bootstrap-list-filter to gulp
gulpfile.js
gulpfile.js
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Less | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.less('app.less'); // Base Scripts and Styles mix.scripts([ './bower_components/jquery/dist/jquery.min.js', './bower_components/bootstrap/dist/js/bootstrap.min.js', './bower_components/tooltipster/js/jquery.tooltipster.min.js' ], 'public/js/app.js'); mix.styles([ './bower_components/tooltipster/css/themes/tooltipster-light.css', './bower_components/tooltipster/css/tooltipster.css', './bower_components/animate.css/animate.min.css', ], 'public/css/styles.css'); // News Helpers mix.scripts([ './bower_components/jquery-bootstrap-newsbox/dist/jquery.bootstrap.newsbox.min.js', ], 'public/js/newsbox.js'); // Form Helpers mix.scripts([ './bower_components/bootstrap-select/dist/js/bootstrap-select.min.js', './bower_components/bootstrap-validator/dist/validator.min.js', './bower_components/speakingurl/speakingurl.min.js', './bower_components/jquery-slugify/dist/slugify.min.js', ], 'public/js/forms.js'); mix.copy([ './bower_components/bootstrap-select/dist/js/i18n/*.min.js', ], 'public/js/bootstrap-select/i18n'); mix.styles([ './bower_components/bootstrap-select/dist/css/bootstrap-select.min.css', ], 'public/css/forms.css'); // Date & Time Helpers mix.scripts([ './bower_components/moment/min/moment-with-locales.min.js', './bower_components/moment-timezone/builds/moment-timezone.min.js', './bower_components/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js', ], 'public/js/datetime.js'); mix.styles([ './bower_components/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css', ], 'public/css/datetime.css'); // Tour Helpers mix.scripts([ './bower_components/bootstrap-tour/build/js/bootstrap-tour.min.js', ], 'public/js/tour.js'); mix.styles([ './bower_components/bootstrap-tour/build/css/bootstrap-tour.min.css', ], 'public/css/tour.css'); });
JavaScript
0.000002
@@ -1481,32 +1481,113 @@ lugify.min.js',%0A + './bower_components/bootstrap-list-filter/bootstrap-list-filter.min.js',%0A %5D, 'public/j
b0977e5f1c28f1ec39f919726544db175607e029
add gulp build task
gulpfile.js
gulpfile.js
const gulp = require('gulp') const browserSync = require('browser-sync').create() const sass = require('gulp-sass') const plumber = require('gulp-plumber') const gutil = require('gulp-util') const uncss = require('gulp-uncss') const fs = require('fs') const juice = require('juice') // Compile sass into CSS & auto-inject into browsers gulp.task('sass', () => { return gulp.src('working/scss/*.scss') // plumber is used so that the watch task does not break when there is some wrong code .pipe(plumber(function (error) { gutil.beep() console.log(error) this.emit('end') })) .pipe(sass()) .pipe(gulp.dest('working/css')) .pipe(browserSync.stream()) }) // Compile sass into CSS, remove unneeded CSS and dump it into the working folder for use in build process // it is not neccessary to create a build CSS file just for the purpose of building the final email gulp.task('css', () => { return gulp.src('working/scss/*.scss') .pipe(plumber(function (error) { gutil.beep() console.log(error) this.emit('end') })) .pipe(sass()) .pipe(uncss({ html: ['working/index.html'] })) .pipe(gulp.dest('working/css')) }) gulp.task('premailer', () => { // read the html file return fs.readFile('working/index.html', 'utf-8', (err, html) => { if (err) throw (err) // read the css file fs.readFile('working/css/styles.css', 'utf-8', (err, css) => { if (err) throw (err) // pass both the html and css string into juice. This is done because of path issues in the html // => juice does not find the css because of the relative path import in the html file fs.writeFile('build/index.html', juice.inlineContent(html, css), (err) => { if (err) throw (err) console.log('Wrote to build') }) }) }) }) gulp.task('serve', gulp.series('sass', function () { browserSync.init({ server: 'working' }) gulp.watch('working/scss/*.scss', ['sass']).on('change', browserSync.reload) gulp.watch('working/*.html').on('change', browserSync.reload) })) gulp.task('build', gulp.series('css', 'premailer'))
JavaScript
0.000002
@@ -1847,24 +1847,645 @@ %7D)%0A %7D)%0A%7D)%0A%0A +const premailer = (done) =%3E %7B%0A fs.readFile('working/index.html', 'utf-8', (err, html) =%3E %7B%0A if (err) throw (err)%0A // read the css file%0A fs.readFile('working/css/styles.css', 'utf-8', (err, css) =%3E %7B%0A if (err) throw (err)%0A // pass both the html and css string into juice. This is done because of path issues in the html%0A // =%3E juice does not find the css because of the relative path import in the html file%0A fs.writeFile('build/index.html', juice.inlineContent(html, css), (err) =%3E %7B%0A if (err) throw (err)%0A console.log('Wrote to build')%0A done()%0A %7D)%0A %7D)%0A %7D)%0A%7D%0A%0A gulp.task('s @@ -2759,17 +2759,16 @@ ('css', -' premaile @@ -2768,12 +2768,11 @@ remailer -' ))%0A
27ca2c86c893bf26533074447d447c6950262f95
Fix typo original
src/services/blob/blob.service.js
src/services/blob/blob.service.js
import assert from 'assert'; import concat from 'concat-stream'; import dauria from 'dauria'; import makeDebug from 'debug'; import mimeTypes from 'mime-types'; import { Service, createService, helpers } from 'mostly-feathers-mongoose'; import fp from 'mostly-func'; import request from 'request'; import stream from 'stream'; import BlobModel from '../../models/blob.model'; import defaultHooks from './blob.hooks'; import { fromBuffer, bufferToHash } from './util'; const debug = makeDebug('playing:content-services:blobs'); const defaultOptions = { name: 'blobs', }; export class BlobService extends Service { constructor (options) { options = Object.assign({}, defaultOptions, options); assert(options.blobs, 'BlobService blobs option required'); super(options); } setup (app) { super.setup(app); this.storage = app.get('storage'); if (!this.storage) { throw new Error('app context `storage` must be provided'); } this.hooks(defaultHooks(this.options)); } get (id, params) { let [batchId, index] = id.split('.'); debug('get', batchId, index); const readBlob = (blob) => { debug('readBlob', blob); return this._readBlob(blob).then(buffer => { blob.file = dauria.getBase64DataURI(buffer, blob.mimetype); }); }; if (index !== undefined) { return this._getBlob(batchId, index).then(blob => params.query.embedded !== undefined? readBlob(blob) : blob); } else { return super.get(id, params).then(result => { debug('getBatch', result); result.blobs = helpers.transform(result.blobs); return result; }); } } _readBlob (blob, bucket) { return new Promise((resolve, reject) => { this.storage.createReadStream(blob) .on('error', reject) .pipe(concat(buffer => { resolve(buffer); })); }); } _getBlob (batchId, index) { return super.get(batchId).then(result => { if (!result) throw new Error('Blob batch id not exists'); const batch = result.data || result; const blobs = batch.blobs || []; if (index >= blobs.length) throw new Error('Blob index out of range of the batch'); return blobs[index]; }).then(helpers.transform); } create (data, params) { return super.create(data, params); } update (id, data, params) { debug('update', id, data, params); assert(params.file, 'params file not provided.'); const name = params.file.originalname; const mimetype = params.file.mimetype; const ext = mimeTypes.extension(mimetype); const size = params.file.size; const getBuffer = (file) => { if (file.url) { const req = request.defaults({ encoding: null }); return new Promise((resolve, reject) => { req.get(file.url, function (err, res, buffer) { if (err) return reject(err); return resolve(buffer); }); }); } if (file.key) { return this._readBlob(file); } debug('getBuffer not supports this file', file); throw new Error('getBuffer not supported on this file'); }; const getBatch = (id) => { return super.get(id).then(result => { if (!result) throw new Error('Blob batch id not exists'); return result.data || result; }); }; const writeBlob = ([batch, buffer]) => { batch.blobs = batch.blobs || []; const bucket = data.bucket || this.storage.bucket; const index = parseInt(data.index) || batch.blobs.length; const vender = data.vender || this.storage.name; const key = `${id}.${index}.${ext}`; return new Promise((resolve, reject) => { fromBuffer(buffer) .pipe(this.storage.createWriteStream({ bucket, key, name, vender, mimetype, size }, (error) => { if (error) return reject(error); let blob = { bucket, key, index, name, vender, mimetype, size }; if (index < batch.blobs.length) { batch.blobs[index] = blob; } else { batch.blobs.push(blob); } return resolve(batch.blobs); })) .on('error', reject); }); }; const updateBlobs = (blobs) => { return super.patch(id, { blobs: blobs }).then(batch => { return batch.blobs && batch.blobs[batch.blobs.length - 1]; }); }; return Promise.all([ getBatch(id), getBuffer(params.file) ]) .then(writeBlob) .then(updateBlobs); } patch (id, data, params) { return super.update(id, data, params); } remove (id) { let [batchId, index] = id.split('.'); debug('remove', batchId, index); const removeBlob = (blob) => { debug('remove blob', blob); return new Promise((resolve, reject) => { this.storage.remove({ key: blob.key }, error => error ? reject(error) : resolve(blob)); }); }; if (index !== undefined) { return this._getBlob(batchId, index).then(removeBlob); } else { return super.remove(batchId); } } attachOnDocument (id, data, params, original) { assert(data.context && data.context.currentDocument, 'context.currentDocument not provided.'); assert(data.context && data.context.documentType, 'context.documentType not provided.'); const svcDocuments = this.app.service('documents'); let blobs = (original.blobs || []).map((blob) => { blob.batch = original.id; return fp.dissoc('id', blob); }); return svcDocuments.get(data.context.currentDocument).then((doc) => { if (!doc) throw new Error('currentDocument not exists'); let files = (doc.files || []).concat(blobs); debug('attachOnDocument', files); return svcDocuments.patch(doc.id, { files: files }); }); } removeFromDocument (id, data, params, orignal) { assert(data.context && data.context.currentDocument, 'context.currentDocument not provided.'); assert(data.context && data.context.documentType, 'context.documentType not provided.'); assert(data.xpath, 'data.xpath not provided.'); const svcDocuments = this.app.service('documents'); return svcDocuments.get(data.context.currentDocument).then((doc) => { if (!doc) throw new Error('currentDocument not exists'); if (data.xpath.startsWith('files')) { let [xpath, index] = data.xpath.split('/'); let files = fp.remove(parseInt(index), 1, doc.files || []); debug('removeFromDocument', xpath, index, files); return svcDocuments.patch(doc.id, { files: files }); } else { let xpath = data.xpath; debug('removeFromDocument', xpath); return svcDocuments.patch(doc.id, { [xpath]: null }); } }); } } export default function init (app, options) { options = Object.assign({ ModelName: 'blob' }, options); return createService(app, BlobService, BlobModel, options); } init.Service = BlobService;
JavaScript
0.999998
@@ -5936,16 +5936,17 @@ ms, orig +i nal) %7B%0A
2143256b88157bf63ef11085c98026c6ef480cb0
add optional host port
gulpfile.js
gulpfile.js
'use strict' const gulp = require('gulp') const plumber = require('gulp-plumber') const watch = require('gulp-watch') const gulpif = require('gulp-if') const sass = require('gulp-sass') const postcss = require('gulp-postcss') const budo = require('budo') const argv = require('yargs').argv; const uglify = require('gulp-uglify') const rename = require('gulp-rename') const stream = require('gulp-streamify') const source = require('vinyl-source-stream') const browserify = require('browserify') const babelify = require('babelify').configure({ presets: ['es2015', 'react'] }) const entry = './source/index.js' const outfile = 'bundle.js' gulp.task('sass', function() { gulp.src('./source/sass/global.scss') .pipe(plumber()) .pipe(sass()) .pipe(postcss([ require('postcss-assets')({ loadPaths: ['**'], basePath: './app', cachebuster: true }), require('autoprefixer')({ browsers: ['last 1 version'] }), require('csswring')() ])) .pipe(gulp.dest('./app')) }) gulp.task('watch', ['sass'], function(callback) { // dev server let server = budo(entry, { serve: outfile, port: 3000, live: true, dir: './app', open: argv.open, browserify: { transform: babelify }, stream: process.stdout }).on('exit', callback) // watch files watch(['source/sass/**/*.{scss,sass}'], () => gulp.start('sass')) watch(['./app/**/*.{html,json}'], () => server.reload()) }) gulp.task('script', function() { var bundler = browserify(entry, { transform: babelify }).bundle() return bundler .pipe(source('index.js')) .pipe(gulpif(argv.production, stream(uglify()))) .pipe(rename(outfile)) .pipe(gulp.dest('./app')) }) gulp.task('bundle', ['sass', 'script'])
JavaScript
0
@@ -1236,16 +1236,40 @@ port: + argv.port ? argv.port : 3000,%0A
7e91bc20c40ac50f7bb3f1e27064d8e335e733cb
add missing plugins
src/plugins/module.js
src/plugins/module.js
angular.module('ngCordova.plugins', [ 'ngCordova.plugins.deviceMotion', 'ngCordova.plugins.camera', 'ngCordova.plugins.geolocation', 'ngCordova.plugins.deviceOrientation', 'ngCordova.plugins.dialogs', 'ngCordova.plugins.vibration', 'ngCordova.plugins.network', 'ngCordova.plugins.device', 'ngCordova.plugins.barcodeScanner', 'ngCordova.plugins.splashscreen', 'ngCordova.plugins.keyboard', 'ngCordova.plugins.contacts', 'ngCordova.plugins.statusbar', 'ngCordova.plugins.file', 'ngCordova.plugins.socialSharing', 'ngCordova.plugins.globalization', 'ngCordova.plugins.sqlite', 'ngCordova.plugins.ga', 'ngCordova.plugins.push', 'ngCordova.plugins.spinnerDialog', 'ngCordova.plugins.sms', 'ngCordova.plugins.pinDialog', 'ngCordova.plugins.localNotification', 'ngCordova.plugins.toast', 'ngCordova.plugins.flashlight', 'ngCordova.plugins.capture', 'ngCordova.plugins.appAvailability', 'ngCordova.plugins.prefs', 'ngCordova.plugins.printer', 'ngCordova.plugins.bluetoothSerial', 'ngCordova.plugins.backgroundGeolocation', 'ngCordova.plugins.facebookConnect' ]);
JavaScript
0.000016
@@ -1107,13 +1107,75 @@ Connect' +,%0A 'ngCordova.plugins.adMob',%0A 'ngCordova.plugins.googleMap' %0A%5D);%0A
a83850e7f4e269ce8692aeaec631e5b713f4df18
include bourbon and neat
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gulpSass = require('gulp-sass'); var rimraf = require('rimraf'); var sequence = require('run-sequence'); var merge = require('merge-stream'); var runElectron = require('gulp-run-electron'); var useref = require('gulp-useref'); gulp.task('run-app', function() { gulp.src('dist') .pipe(runElectron([], { cwd: 'dist' })); }); gulp.task('electron', function() { var js = gulp.src('src/main.js') .pipe(gulp.dest('dist')); var pkg = gulp.src('src/package.json') .pipe(gulp.dest('dist')); return merge(js, pkg); }); gulp.task('copy', function() { return gulp.src('src/**/*.html') .pipe(useref()) .pipe(gulp.dest('dist')); }); gulp.task('sass', function() { return gulp.src(['./src/sass/*.scss']) .pipe(gulpSass().on('error', gulpSass.logError)) .pipe(gulp.dest('./dist')); }); gulp.task('clean', function(cb) { return rimraf('dist', cb); }); gulp.task('watch', function() { gulp.watch('src/sass/*.scss', ['sass', runElectron.rerun]); gulp.watch(['src/**/*.html', 'src/**/*.js'], ['copy', runElectron.rerun]); }); gulp.task('build', function() { sequence(['clean'], ['sass', 'copy', 'electron']); }); gulp.task('default', function() { sequence(['clean'], ['sass', 'copy', 'electron'], ['watch', 'run-app']); }); gulp.task('help', function() { var chalk = require('chalk'); console.log(''); console.log(chalk.bold('Unifi Monitor - Electron')); console.log(chalk.cyan(' gulp '), 'Build and watch for changes, and run application'); console.log(chalk.cyan(' gulp build '), 'Build application to ', chalk.yellow('dist')); console.log(chalk.cyan(' gulp run-app '), 'Start the application currently in ', chalk.yellow('dist')); console.log(''); });
JavaScript
0.000002
@@ -259,16 +259,63 @@ seref'); +%0Avar neat%09%09= require('node-neat').includePaths; %0A%0Agulp.t @@ -806,16 +806,54 @@ ulpSass( +%7B%0A%09%09%09includePaths: %5B%5D.concat(neat)%0A%09%09%7D ).on('er
c7ea12de7e1e46b75bdd5d24099a6eb1923b4fe3
Stop resetting maintainer_can_modify PR input field
lib/models/pr.js
lib/models/pr.js
"use strict"; const Head = require("./branch").Head; const Base = require("./branch").Base; const MergeBase = require("./branch").MergeBase; const File = require("./file"); const WattsiFile = File.WattsiFile; const AddedWattsiFile = File.UnchangedWattsiFile; const RemovedWattsiFile = File.UnchangedWattsiFile; const UnchangedWattsiFile = File.UnchangedWattsiFile; const Config = require("./config"); const GithubAPI = require("../github-api"); const GH_API = require("../GH_API"); const WattsiClient = require("../wattsi-client"); class PR { constructor(id, installation) { if (typeof id != "string") { throw new TypeError(`Incorrect Id: ${ JSON.stringify(id, null, 4) }`) } if (typeof installation != "object") { throw new TypeError(`Incorrect Installation object: ${ JSON.stringify(installation, null, 4) }`) } this._id = id; this._installation = installation; let parts = id.split("/"); this._owner = parts[0]; this._repo = parts[1]; this._number = parts[2]; } init(options) { return this.setupApi(options) .then(_ => this.requestConfig()) .then(_ => this.requestPR()) .then(_ => this.requestMergeBase()) .then(_ => this.getPreviewFiles()); } request(url, options, body) { return this._api.request(url, options, body); } requestPR() { return this.request(GH_API.GET_PR).then(payload => this.payload = payload); } setupApi(options) { this._api = new GithubAPI(this, options); return this._api.requestAuthHeaders() .then(headers => this._api.setAuthHeaders(headers)); } requestConfig() { return new Config(this).request().then(config => this.config = config); } get config() { if (!("_config" in this)) { throw new Error("Invalid state"); } return this._config; } get postProcessingConfig() { return this.config.post_processing; } set config(config) { return this._config = config; } requestCommits() { return this.request(GH_API.GET_PR_COMMITS).then(commits => this.commits = commits); } requestMergeBase() { return this.request(GH_API.GET_COMPARE_COMMITS, { base: this.payload.base.sha, head: this.payload.head.sha }).then(payload => { this.merge_base_sha = payload.merge_base_commit.sha; this.files = payload.files; }); } get commits() { if (!("_commits" in this)) { throw new Error("Invalid state"); } return this._commits; } set commits(commits) { return this._commits = commits; } get head_sha() { return this.payload.head.sha; } get merge_base_sha() { if (!("_merge_base_sha" in this)) { throw new Error("Invalid state"); } return this._merge_base_sha; } set merge_base_sha(merge_base_sha) { return this._merge_base_sha = merge_base_sha; } get files() { if (!("_files" in this)) { throw new Error("Invalid state"); } return this._files; } set files(files) { return this._files = files; } get preview_files() { if (!("_preview_files" in this)) { throw new Error("Invalid state"); } return this._preview_files; } set preview_files(preview_files) { return this._preview_files = preview_files; } updateBody(content) { return this.request(GH_API.PATCH_PR, null, { title: this.payload.title, body: content, state: this.payload.state, base: this.payload.base.ref, maintainer_can_modify: this.payload.maintainer_can_modify }); } get payload() { return this._payload; } set payload(payload) { return this._payload = payload; } get installation() { return this._installation; } get number() { return this._number; } get owner() { return this._owner; } get repo() { return this._repo; } get id() { return this._id; } get body() { return this._body = this._body || (this.payload.body || "").replace(/\r\n/g, "\n").trim(); } get processor() { return this.config.type.toLowerCase(); } get aws_s3_bucket() { if (process.env.ALLOW_MULTIPLE_AWS_BUCKETS == "no") { return process.env.AWS_BUCKET_NAME; } return this.owner == "whatwg" ? process.env.WHATWG_AWS_BUCKET_NAME : process.env.AWS_BUCKET_NAME; } get isMultipage() { return !!this.config.multipage; } requiresPreview() { return !(/<!--\s*no preview\s*-->/.test(this.body)); } touchesSrcFile() { let relFiles = this.relevantSrcFiles; return this.files.some(f => relFiles.indexOf(f.filename) > -1); } get relevantSrcFiles() { return [this.config.src_file]; } getPreviewFiles() { if (this.processor == "wattsi") { this.wattsi = new WattsiClient(this); return this.wattsi.getFilenames().then(_ => { this.preview_files = []; this.unchanged_files = []; this.wattsi.modifiedFiles.forEach(f => { this.preview_files.push(new WattsiFile(this, this.wattsi, f)); }); this.wattsi.addedFiles.forEach(f => { this.preview_files.push(new AddedWattsiFile(this, this.wattsi, f)); }); this.wattsi.removedFiles.forEach(f => { this.unchanged_files.push(new RemovedWattsiFile(this, this.wattsi, f)); }); this.wattsi.unchangedFiles.forEach(f => { this.unchanged_files.push(new UnchangedWattsiFile(this, this.wattsi, f)); }); }); } else { this.preview_files = [ new File(this) ]; return Promise.resolve(); } } cacheAll() { function next(files) { if (files.length) { let file = files.pop(); return file.cache().then(_ => next(files)); } return Promise.resolve(); } return next(this.preview_files.slice(0)) .then(_ => { if (this.unchanged_files) { return next(this.unchanged_files.slice(0)) }; }) .then(_ => { if (this.wattsi) { return this.wattsi.cleanup(); } }); } } module.exports = PR;
JavaScript
0
@@ -3790,211 +3790,21 @@ -title: this.payload.title,%0A body: content,%0A state: this.payload.state,%0A base: this.payload.base.ref,%0A maintainer_can_modify: this.payload.maintainer_can_modify +body: content %0A
70bb45f133e0d86dd8cef480f2164ef99e25ac17
add nepiOpy count to lokalita
src/shared/app/models/Lokalita.js
src/shared/app/models/Lokalita.js
/** Created by hhj on 2/16/16. */ import { Record } from 'immutable' import { NepiOpyFactory } from './NepiOpy' export class Lokalita extends Record({ id: 0, ixlok: 0, kraj: '', obec: '', cast: '', ulice: '', cispop: 0, cisori: 0, cisdop: 0, chardop: '', cisevi: 0, akrlok: '', kodObjektUIR: 0, bunka: 0, nepiOpy: NepiOpyFactory(), }) { constructor(args = {}) { if (args && args.nepiOpy) args.nepiOpy = NepiOpyFactory(args.nepiOpy.data || args.nepiOpy) if (args.cisdop) args.chardop = String.fromCharCode('a'.charCodeAt(0) + args.cisdop - 1) super(args) } } export default Lokalita
JavaScript
0.000001
@@ -356,16 +356,35 @@ tory(),%0A + nepiOpyCount: 0,%0A %7D) %7B%0A c @@ -595,16 +595,84 @@ op - 1)%0A + if (args.nepiOpyCount) args.nepiOpyCount = args.nepiOpyCount%5B0%5D%0A supe
5337f4682f369b692196ee1b54d4f121a65c8f7a
use `Array.every()` for `getIdentityValues` fallback
src/shell/base/base.controller.js
src/shell/base/base.controller.js
import angular from 'angular' export default class BaseCtrl { constructor($scope, DebugService, $stateParams, CRUDService, AlertService, $q, PayloadService, $window) { var vm = this // Injectables vm.$scope = $scope vm.DebugService = DebugService vm.$stateParams = $stateParams vm.CRUDService = CRUDService vm.AlertService = AlertService vm.$q = $q vm.PayloadService = PayloadService vm.$window = $window // Loader vm.loader() vm.$scope.$on('reloadData', function() { // ToDo: Redraw (re-render) grid. Ex.: when hiding, showing columns vm.loader() }) // Debug Modal vm.$scope.$on('openDebugModal', () => { vm.openDebugModal() }) } // General-purpose debug modal openDebugModal() { var vm = this vm.DebugService.show({ metadata: vm.options.metadata, fields: vm.options.fields, model: vm.options.data, }) } loader() { // Declare but leave empty to be used by child controllers console.warn('BaseController.loader() called (not overriden)') // eslint-disable-line no-console } /* Common Handlers (override if needed) */ onDelete(selected) { var vm = this var payload if (confirm('Are your sure to Delete selected record(s)?')) { // eslint-disable-line no-alert /** * Create payload to be sent */ payload = { tableName: vm.options.metadata.catalogName, primaryKey: vm.options.metadata.primaryKey, identityKey: vm.options.metadata.identityKey, } // Set DeleteRows payload.deleteRows = [] // Set primaryKey and/or identityKey as DeleteRows angular.forEach(selected, function(row, index) { var identifier = row[vm.options.metadata.primaryKey] || row[vm.options.metadata.identityKey] payload.deleteRows[index] = {} if (payload.primaryKey) { payload.deleteRows[index][payload.primaryKey] = identifier } if (payload.identityKey) { payload.deleteRows[index][payload.identityKey] = identifier } }) vm.CRUDService.delete(payload).then(function(res) { if (res.success === true) { if (res.data[0].status === 'error') { vm.AlertService.show('danger', 'Error', res.data[0].statusMessage + ' [statusId: ' + res.data[0].statusId + ']') } else if (res.data[0].status === 'success') { vm.AlertService.show('success', 'Deleted', 'Record(s) successfully deleted') // Remove row(s) from Grid // http://stackoverflow.com/questions/26614641/how-to-properly-delete-selected-items-ui-grid-angular-js // angular.forEach(selected, function(row, index) { // vm.data.splice(vm.data.lastIndexOf(row), 1); // }); // Emit 'reloadData' instead vm.$scope.$emit('reloadData') } } else { // Do nothing. HTTP 500 responses handled by ErrorInterceptor } }) } } onNew(catalogName) { var vm = this /* Get id value from nested formly template (if that's the case) */ const id = vm.getIdentityValues(vm.options.metadata, vm.$scope.model) this.$scope.$emit('goToState', 'main.panel.form', { catalogName: catalogName, mode: 'insert', filters: undefined, // force no filters ref: id.reference || undefined, refId: id.value || undefined, }) } onOpen(selected) { var vm = this const id = vm.getIdentityValues(vm.options.metadata, selected) vm.$scope.$emit('goToState', 'main.panel.form', { catalogName: vm.options.metadata.catalogName, mode: vm.options.metadata.mode, filters: id.filters, ref: vm.options.metadata.foreignReference || undefined, refId: undefined, // force no refId }) } onNext(selected) { var vm = this const id = vm.getIdentityValues(vm.options.metadata, selected) // ToDo: PanaxDB Routes vm.$scope.$emit('goToState', 'main.panel.form', { catalogName: vm.options.metadata.catalogName, mode: 'edit', // force edit mode filters: id.filters, ref: undefined, // force no reference refId: undefined, // force no refId }) } onPaginationChange(newPage, newPageSize) { var vm = this /* Avoid double call to `vm.loader()` when first page already loaded Apply for grid, form (w nested grid), master-detail */ if (vm.loadedOnce === true) { vm.loadedOnce = false return } vm.loader({pageIndex: newPage, pageSize: newPageSize}) } /* Support methods */ getIdentityValues(metadata, model) { let type, key, value, reference, filters /* Get type of identity and reference if present */ type = !!metadata.identityKey ? 'identityKey' : 'primaryKey' reference = metadata.foreignReference || undefined /* then get identity key or fallback to 'id' || 'Id' || 'ID' */ if (metadata[type]) { key = metadata[type] } else if (model['id']) { // eslint-disable-line dot-notation key = 'id' } else if (model['Id']) { // eslint-disable-line dot-notation key = 'Id' } else if (model['ID']) { // eslint-disable-line dot-notation key = 'ID' } /* finally get value & craft filters */ if (angular.isArray(model)) { value = metadata[key] || undefined filters = '[' + key + ' IN (' angular.forEach(model, function(row, index, arr) { filters += `'${row[key]}'` if (index !== arr.length - 1) { filters += ', ' } }) filters += ')]' } else { value = model && model[key] || undefined filters = `'${key}=${value}'` } return { type, key, value, reference, filters, } } }
JavaScript
0.000002
@@ -5111,245 +5111,200 @@ lse -if (model%5B'id'%5D) %7B +%7B%0A // +t es -lint-disable-line dot-notation%0A key = 'id'%0A %7D else if (model%5B'Id'%5D) %7B // eslint-disable-line dot-notation%0A key = 'Id'%0A %7D else if (model%5B'ID'%5D) %7B // eslint-disable-line dot-notation%0A key = 'ID' +t every possible name%0A // http://stackoverflow.com/a/6260865/171809%0A %5B'id', 'Id', 'ID'%5D.every((name) =%3E %7B%0A key = model%5Bname%5D && name%0A return !key%0A %7D) %0A
f5925f754ecae2011d966e40bd41e0d436767e4c
Change target folder
gulpfile.js
gulpfile.js
// Include gulp var gulp = require('gulp'), uglify = require('gulp-uglify'), concat = require('gulp-concat'), minifycss = require('gulp-minify-css'), minifyhtml = require('gulp-minify-html'), imagemin = require('gulp-imagemin'), pngquant = require('imagemin-pngquant'); // Minify JavaScript gulp.task('scripts', function() { gulp.src(paths.scripts) //.pipe(concat('all.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist/js')); }); // Minify CSS gulp.task('styles', function() { gulp.src(paths.styles) .pipe(minifycss()) .pipe(gulp.dest('dist/css')); }); // Minify HTML gulp.task('content', function() { gulp.src(paths.content) .pipe(minifyhtml({ empty: true, quotes: true })) .pipe(gulp.dest('dist')); }); // Optimize Images gulp.task('images', function () { gulp.src( paths.images[0] ) .pipe(imagemin({ optimizationLevel: 6, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] })) .pipe(gulp.dest('dist/img')); gulp.src( paths.images[1] ) .pipe(imagemin({ progressive: true, optimizationLevel: 6, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] })) .pipe(gulp.dest('dist/img')); }); // Watch files gulp.task('watch', function() { gulp.watch(paths.scripts, ['scripts']); gulp.watch(paths.styles, ['styles']); }); // Path to various files var paths = { content: ['src/*.html'], scripts: ['src/js/*.js'], styles: ['src/css/*.css'], images: ['src/img/*.png', 'src/img/*.jpg'] }; // Call the Gulp task gulp.task('default', ['content', 'scripts', 'styles', 'images']);
JavaScript
0.000001
@@ -424,20 +424,15 @@ st(' -dist/ js'));%0A + %0A%7D); @@ -544,21 +544,16 @@ p.dest(' -dist/ css'));%0A @@ -713,20 +713,16 @@ p.dest(' -dist '));%0A%7D); @@ -931,37 +931,32 @@ pipe(gulp.dest(' -dist/ img'));%0A%0A%09gulp.s @@ -1104,32 +1104,32 @@ gquant()%5D%0A%09%09%7D))%0A + %09%09.pipe(gulp.des @@ -1135,13 +1135,8 @@ st(' -dist/ img'
26f961408c1dfbd434d9ae2f2fc69d262a3a4802
Remove glamor from overdrive itself
lib/overdrive.js
lib/overdrive.js
import React from 'react' import ReactDOM from 'react-dom' import {css} from 'glamor'; const defaultSpeed = 200; const components = {}; class Overdrive extends React.Component { constructor(props) { super(props); this.state = { loading: true }; } animate(prevPosition, prevElement) { const {speed = defaultSpeed} = this.props; const transition = { transition: `transform ${speed / 1000}s, opacity ${speed / 1000}s`, transformOrigin: '0 0 0' }; const bodyElement = document.createElement('div'); window.document.body.appendChild(bodyElement); prevPosition.top += window.scrollY; const nextPosition = this.getPosition(true); const noTransform = 'scaleX(1) scaleY(1) translateX(0px) translateY(0px)'; const targetScaleX = prevPosition.width / nextPosition.width; const targetScaleY = prevPosition.height / nextPosition.height; const targetTranslateX = prevPosition.left - nextPosition.left; const targetTranslateY = prevPosition.top - nextPosition.top; const sourceStart = React.cloneElement(prevElement, { key: '1', className: css({ ...transition, ...prevPosition, opacity: 1, transform: noTransform }).toString() }); const sourceEnd = React.cloneElement(prevElement, { key: '1', className: css({ ...transition, ...prevPosition, margin: nextPosition.margin, opacity: 0, transform: `matrix(${1/targetScaleX}, 0, 0, ${1/targetScaleY}, ${-targetTranslateX}, ${-targetTranslateY})` }).toString() }); const targetStart = React.cloneElement(this.props.children, { key: '2', className: css({ ...transition, ...nextPosition, margin: prevPosition.margin, opacity: 0, transform: `matrix(${targetScaleX}, 0, 0, ${targetScaleY}, ${targetTranslateX}, ${targetTranslateY})` }).toString() }); const targetEnd = React.cloneElement(this.props.children, { key: '2', className: css({ ...transition, ...nextPosition, opacity: 1, transform: noTransform }).toString() }); const start = <div>{sourceStart}{targetStart}</div>; const end = <div>{sourceEnd}{targetEnd}</div>; this.setState({loading: true}); ReactDOM.render(start, bodyElement); setTimeout(() => { ReactDOM.render(end, bodyElement); setTimeout(() => { this.setState({loading: false}); window.document.body.removeChild(bodyElement); }, speed); }, 0); } componentDidMount() { const {id, animationDelay} = this.props; if (components[id]) { const {prevPosition, prevElement} = components[id]; components[id] = false; if (animationDelay) { setTimeout(() => { this.animate(prevPosition, prevElement); }, animationDelay); } else { this.animate(prevPosition, prevElement); } } else { this.setState({loading: false}); } } componentWillUnmount() { const {id} = this.props; const prevElement = React.cloneElement(this.props.children); const prevPosition = this.getPosition(); components[id] = { prevPosition, prevElement }; setTimeout(() => { components[id] = false; }, 100); } getPosition(addOffset) { const node = this.element; const rect = node.getBoundingClientRect(); const computedStyle = getComputedStyle(node); const marginTop = parseInt(computedStyle.marginTop, 10); const marginLeft = parseInt(computedStyle.marginLeft, 10); return { top: (rect.top - marginTop) + ((addOffset ? 1 : 0) * window.scrollY), left: (rect.left - marginLeft), width: rect.width, height: rect.height, margin: computedStyle.margin, padding: computedStyle.padding, borderRadius: computedStyle.borderRadius, position: 'absolute' }; } render() { const {id, speed, animationDelay, style = {}, ...rest} = this.props; const newStyle = { ...style, opacity: (this.state.loading ? 0 : 1) }; return ( <div ref={c => (this.element = c && c.firstChild)} style={newStyle} {...rest}> {this.props.children} </div> ); } } Overdrive.propTypes = { id: React.PropTypes.string.isRequired, speed: React.PropTypes.number, animationDelay: React.PropTypes.number }; export default Overdrive;
JavaScript
0.000001
@@ -56,36 +56,8 @@ dom' -%0Aimport %7Bcss%7D from 'glamor'; %0A%0Aco @@ -1182,39 +1182,31 @@ -className: css( +style: %7B%0A @@ -1335,36 +1335,24 @@ %7D -).toString() %0A %7D); @@ -1443,39 +1443,31 @@ -className: css( +style: %7B%0A @@ -1726,36 +1726,24 @@ %7D -).toString() %0A %7D); @@ -1844,39 +1844,31 @@ -className: css( +style: %7B%0A @@ -2121,36 +2121,24 @@ %7D -).toString() %0A %7D); @@ -2245,23 +2245,15 @@ -className: css( +style: %7B%0A @@ -2373,32 +2373,32 @@ rm: noTransform%0A + %7D).t @@ -2398,20 +2398,8 @@ %7D -).toString() %0A
3ee6f9293edd48a1ca8302f799f8a339549952a1
Add gulp task to run tests on file change.
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var del = require('del'); var babel = require('gulp-babel'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var mocha = require('gulp-mocha'); var mochaBabelRegister = require('babel/register'); var buildDestination = 'build' gulp.task('build', function() { del([buildDestination], function() { var bundleStream = browserify({ entries: './index.js', debug: true, }).bundle(); return bundleStream .pipe(source('min-flux.js')) .pipe(buffer()) .pipe(babel()) .pipe(gulp.dest(buildDestination)); }); }); gulp.task('test', function() { var MinFlux = require('./index'); var expect = require('chai').expect; return gulp.src(['test/**/*.js'], { read: false }) .pipe(mocha({ reporter: 'dot', require: [ './index', 'chai', ], })); }); gulp.task('default', ['test']);
JavaScript
0
@@ -704,85 +704,8 @@ ) %7B%0A - var MinFlux = require('./index');%0A var expect = require('chai').expect;%0A%0A%0A re @@ -802,71 +802,127 @@ - require: %5B%0A './index',%0A 'chai',%0A %5D,%0A %7D) +%7D));%0A%7D);%0A%0Agulp.task('live-test', function() %7B%0A return gulp.watch(%5B'index.js', 'lib/**/*.js', 'test/**/*.js'%5D, %5B'test'%5D );%0A%7D
2eae6024f98ac76d8571581046ce25de2e86cf68
blank line
gulpfile.js
gulpfile.js
/* var ts = require("gulp-typescript") // according to https://www.npmjs.com/package/gulp-typescript // not supported var tsProject = ts.createProject('tsconfig.json', { inlineSourceMap : false }) */ // gulp.task('scripts', function() { // var tsResult = tsProject.src() // gulp.src("lib/* * / * .ts") // or tsProject.src() // .pipe(tsProject()) // // return tsResult.js.pipe(gulp.dest('release')) // }) // * var gulp = require('gulp') var ts = require('gulp-typescript') var sourcemaps = require('gulp-sourcemaps') /** * Directory containing generated sources which still contain * JSDOC etc. */ var genDir = 'gen' var srcDir = 'src' var testDir = 'test' gulp.task('watch', function () { gulp.watch([srcDir + '/**/*.js', testDir + '/**/*.js', srcDir + '/**/*.ts', 'gulpfile.js'], ['tsc', 'babel', 'test', 'standard']) }) const babel = require('gulp-babel') /** * compile tsc (including srcmaps) * @input srcDir * @output genDir */ gulp.task('tsc', function () { var tsProject = ts.createProject('tsconfig.json', { inlineSourceMap: false }) var tsResult = tsProject.src() // gulp.src('lib/*.ts') .pipe(sourcemaps.init()) // This means sourcemaps will be generated .pipe(tsProject()) // ts({ // ... // })) return tsResult.js .pipe(babel({ comments: true, presets: ['es2015'] })) // .pipe( ... ) // You can use other plugins that also support gulp-sourcemaps .pipe(sourcemaps.write()) // Now the sourcemaps are added to the .js file .pipe(gulp.dest('gen')) }) var jsdoc = require('gulp-jsdoc3') gulp.task('doc', function (cb) { gulp.src([srcDir + '/**/*.js', 'README.md', './gen/**/*.js'], {read: false}) .pipe(jsdoc(cb)) }) var instrument = require('gulp-instrument') gulp.task('instrument', function () { return gulp.src([genDir + '/**/*.js']) .pipe(instrument()) .pipe(gulp.dest('gen_cov')) }) var newer = require('gulp-newer') var imgSrc = 'src/**/*.js' var imgDest = 'gen' // compile standard sources with babel, // as the coverage input requires this // gulp.task('babel', ['tsc'], function () { // Add the newer pipe to pass through newer images only return gulp.src([imgSrc, 'gen_tsc/**/*.js']) .pipe(newer(imgDest)) .pipe(babel({ comments: true, presets: ['es2015'] })) .pipe(gulp.dest('gen')) }) var nodeunit = require('gulp-nodeunit') var env = require('gulp-env') /** * This does not work, as we are somehow unable to * redirect the lvoc reporter output to a file */ gulp.task('testcov', function () { const envs = env.set({ DO_COVERAGE: '1' }) // the file does not matter gulp.src(['./**/match/dispatcher.nunit.js']) .pipe(envs) .pipe(nodeunit({ reporter: 'lcov', reporterOptions: { output: 'testcov' } })).pipe(gulp.dest('./cov/lcov.info')) }) gulp.task('test', ['tsc', 'babel'], function () { gulp.src(['test/**/*.js']) .pipe(nodeunit({ reporter: 'minimal' // reporterOptions: { // output: 'testcov' // } })).on('error', function (err) { console.log('This is weird: ' + err.message) }) .pipe(gulp.dest('./out/lcov.info')) }) gulp.task('testmin', ['tsc', 'babel'], function () { gulp.src(['test/**/*.js']) .pipe(nodeunit({ reporter: 'minimal' // reporterOptions: { // output: 'testcov' // } })).on('error', function (err) { console.log('This is weird: ' + err.message) }) .pipe(gulp.dest('./out/lcov.info')) }) // .pipe(gulp.dest('./cov')) // default file name: src-cov.js // }) // shoudl be replaced by ESLINT and a typescript output // compliant config var standard = require('gulp-standard') gulp.task('standard', ['babel'], function () { return gulp.src(['src/**/*.js', 'test/**/*.js', 'gulpfile.js']) .pipe(standard()) .pipe(standard.reporter('default', { breakOnError: true, quiet: true })) }) var coveralls = require('gulp-coveralls') gulp.task('coveralls', function () { gulp.src('testcov/**/lcov.info') .pipe(coveralls()) }) // Default Task gulp.task('coverage', ['tsc', 'babel', 'standard', 'instrument', 'doc', 'coveralls']) // Default Task gulp.task('default', ['tsc', 'babel', 'standard', 'instrument', 'doc', 'test'])
JavaScript
0.999991
@@ -2853,17 +2853,16 @@ '))%0A%7D)%0A%0A -%0A gulp.tas
59ca17998801770666c812e00942c0887ded1156
Add return statement to gulp task
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var iife = require('gulp-iife'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); gulp.task('default', ['scripts']); gulp.task('scripts', function () { gulp.src('src/**/*.js') .pipe(concat('vk-api-angular.js')) .pipe(iife()) .pipe(gulp.dest('dist/')) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dist/')); }); gulp.task('watch', ['default'], function () { gulp.watch('src/**/*.js', ['scripts']); });
JavaScript
0.000299
@@ -235,24 +235,31 @@ tion () %7B%0A +return gulp.src('sr
6ed25eb7e8ee8573a08b82799b63f44d9ef04b58
fix proxy conflict
gulpfile.js
gulpfile.js
var path = require('path'); var clean = require("gulp-clean"); var express = require('express'); var gulp = require('gulp'); var runSequence = require('run-sequence'); var ts = require('gulp-typescript'); var util = require('gulp-util'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var _ = require('lodash'); var appIndexHtmlFilename = 'index.html'; var appProjectName = 'stencil'; var compiledJsFilename = appProjectName + '.compiled.js'; var webServerPort = 3000; var proxyServerPort = 3001; var isPackageRun = false; var isPackageRelease = false; var isExpressOnProxyServer = true; var sources = { ts: 'app/**/*.ts', build: './build/app', dist: './dist/app', html: 'app/' + appIndexHtmlFilename, assets: [ 'app/assets/**/*.*' ] }; /*********************************************************************************************************************** * Local functions / Utilities **********************************************************************************************************************/ gulp.task('clean', function() { return gulp.src([ sources.build, sources.dist ], { read: false }) .pipe(clean()); }); gulp.task('start-server', function() { var server = express(); var port = isExpressOnProxyServer ? proxyServerPort : webServerPort; server.get('/', function(request, response) { response.sendFile(path.join(__dirname, '/', sources.html)); }) .use(express.static(path.resolve(__dirname))) .listen(port); if (!isExpressOnProxyServer) { util.log('express @ http://localhost:' + port); } }); gulp.task('webpack-dev-server', function() { var options = require('./webpack.config'); options.entry = []; options.entry.push('app/' + appProjectName + '.ts'); options.entry.push('webpack-dev-server/client?http://localhost:' + webServerPort, 'webpack/hot/dev-server'); options.plugins.push(new webpack.HotModuleReplacementPlugin()); var devServerOptions = { hot: true, watchDelay: 300, stats: { cached: false, cachedAssets: false, colors: true, context: __dirname }, proxy: { '*': "http://localhost:" + proxyServerPort } }; var webpackServer = new WebpackDevServer(webpack(options), devServerOptions); webpackServer.listen(webServerPort, function () { util.log("webpack @ http://localhost:" + webServerPort) }); }); /*********************************************************************************************************************** * Copy-ish Tasks **********************************************************************************************************************/ gulp.task('copy-index-html', function() { return gulp.src(sources.html) .pipe(gulp.dest(isPackageRelease ? sources.dist : sources.build)); }); gulp.task('copy-assets', function() { return gulp.src(sources.assets, { base: 'assets' }) .pipe(gulp.dest(path.join(isPackageRelease ? sources.dist : sources.build))); }); /*********************************************************************************************************************** * Transpiler Tasks **********************************************************************************************************************/ gulp.task('webpackify', function(callback) { var webpackOptions = require('./webpack.config'); var outputPath = isPackageRelease ? sources.dist : sources.build; webpackOptions.entry = { stencil: 'app/' + appProjectName + '.ts' }; webpackOptions.output = { filename: path.join(outputPath, '/', compiledJsFilename) }; webpack(webpackOptions, function (err, stats) { if (err) throw new gutil.PluginError("webpack", err); callback(); }); }); /*********************************************************************************************************************** * Common Tasks **********************************************************************************************************************/ gulp.task('build', function() { runSequence( 'clean', [ 'copy-assets', 'copy-index-html' ], 'webpackify' ); }); gulp.task('run', function() { isExpressOnProxyServer = false; runSequence( 'start-server' ); }); gulp.task('watchrun', function() { runSequence( 'webpack-dev-server' ); }); gulp.task('release', function() { isPackageRelease = true; runSequence( 'clean', [ 'copy-assets', 'copy-index-html' ], 'webpackify' ); }); gulp.task('releaserun', function() { isPackageRun = true; isPackageRelease = true; runSequence( 'release', 'run' ); }); gulp.task('default', ['watchrun']);
JavaScript
0.000001
@@ -619,19 +619,20 @@ erver = -tru +fals e;%0A%0Avar @@ -4403,44 +4403,8 @@ ) %7B%0A - isExpressOnProxyServer = false;%0A @@ -4486,36 +4486,86 @@ ion() %7B%0A -runSequence( +isExpressOnProxyServer = true;%0A runSequence(%0A 'run', %0A 'we
d22e1aaa77161948ff562b093c6fe6ccc0f01307
Replace gulp-changed with del
gulpfile.js
gulpfile.js
const gulp = require("gulp"), sass = require("gulp-sass"), sassGlob = require("gulp-sass-glob"), watch = require("gulp-watch"), concat = require("gulp-concat"), changed = require('gulp-changed'), del = require('del'); del.sync(['resources/**/*']); gulp.task('default', [ 'copy', 'sass', 'concatJS', 'sass:watch', 'copy:watch', 'concatJS:watch' ]); gulp.task('sass', function(){ return gulp.src('src/scss/**/*.scss') .pipe(sassGlob()) .pipe(sass({}).on('error', sass.logError)) .pipe(gulp.dest('resources/stylesheets')); }); gulp.task('concatJS', function(){ return gulp.src('src/javascript/**/*.js') .pipe(changed('resources/javascript')) .pipe(concat('main.js')) .pipe(gulp.dest('resources/javascript')); }); gulp.task('copy', function(){ return gulp.src(['src/**/*','!src/{scss,scss/**}','!src/{javascript,javascript/**}']) //.pipe(changed('resources/')) .pipe(gulp.dest('resources/')); }); gulp.task('sass:watch', function(){ gulp.watch('src/scss/**/*.scss', ["sass"]); }); gulp.task('concatJS:watch', function(){ gulp.watch('src/javascript/**/*.js', ["concatJS"]); }); gulp.task('copy:watch', function(){ gulp.watch(['src/**/*','!src/{scss,scss/**}','!src/{javascript,javascript/**}'], ["copy"]) }); //gulp.watch('src/scss/**/*.scss', ['sass']); //gulp.watch('src/javascript/**/*.js', ['concatJS']); //gulp.watch(['src/**/*','!src/{scss,scss/**}','!src/{javascript,javascript/**}'], ['copy']);
JavaScript
0.999993
@@ -158,43 +158,8 @@ %22),%0A -changed = require('gulp-changed'),%0A del @@ -1222,199 +1222,4 @@ %7D);%0A -%0A//gulp.watch('src/scss/**/*.scss', %5B'sass'%5D);%0A//gulp.watch('src/javascript/**/*.js', %5B'concatJS'%5D);%0A//gulp.watch(%5B'src/**/*','!src/%7Bscss,scss/**%7D','!src/%7Bjavascript,javascript/**%7D'%5D, %5B'copy'%5D);%0A
d3836d4f9a515ce82ca7b7480e74d61c2286c459
Add loaders and take out stripDebug
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var jsdoc = require('gulp-jsdoc'); var concat = require('gulp-concat'); var stripDebug = require('gulp-strip-debug'); var uglify = require('gulp-uglify'); var _libfiles = [ 'node_modules/three/examples/js/controls/DeviceOrientationControls.js', 'node_modules/three/examples/js/effects/CardboardEffect.js', 'node_modules/tween.js/src/Tween.js', 'src/lib/OrbitControls.js', 'src/lib/GSVPano.js', 'src/lib/modifier/BendModifier.js', ]; var _panolensfiles = [ 'src/Panolens.js', 'src/util/DataImage.js', 'src/util/Modes.js', 'src/util/TextureLoader.js', 'src/panorama/Panorama.js', 'src/panorama/ImagePanorama.js', 'src/panorama/GoogleStreetviewPanorama.js', 'src/panorama/CubePanorama.js', 'src/panorama/BasicPanorama.js', 'src/panorama/VideoPanorama.js', 'src/panorama/EmptyPanorama.js', 'src/interface/Tile.js', 'src/interface/TileGroup.js', 'src/interface/SpriteText.js', 'src/widget/*.js', 'src/infospot/*.js', 'src/viewer/*.js', 'src/util/font/Bmfont.js' ]; var _readme = [ 'README.md' ]; gulp.task( 'default', [ 'minify', 'docs' ] ); gulp.task( 'minify', function() { return gulp.src( _libfiles.concat( _panolensfiles ) ) .pipe( concat( 'panolens.js', { newLine: ';' } ) ) .pipe( stripDebug() ) .pipe( gulp.dest( './build/' ) ) .pipe( concat( 'panolens.min.js' ) ) .pipe( uglify() ) .pipe( gulp.dest( './build/' ) ); }); gulp.task( 'docs', function() { return gulp.src( _panolensfiles.concat( _readme ) ) .pipe( jsdoc( 'docs' ) ); });
JavaScript
0
@@ -564,16 +564,78 @@ rc/util/ +ImageLoader.js',%0A%09'src/util/TextureLoader.js',%0A%09'src/util/Cube TextureL @@ -1293,24 +1293,26 @@ ;' %7D ) )%0A %09 +// .pipe( strip
0c5e8cd6c96275a1db428bc572bea0418e7b3c31
Fix an error in the clean task
gulpfile.js
gulpfile.js
var del = require('del'); var gulp = require('gulp'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var $ = require('gulp-load-plugins')(); var config = require('./webpack.config.js'); gulp.task('js', function (cb) { webpack(config, function (err, stats) { if(err) throw new gutil.PluginError("webpack", err); $.util.log("[webpack]", stats.toString({ colors: true })); cb(); }); }); gulp.task('html', function () { gulp.src('./src/*.html') .pipe(gulp.dest('./build')); }); gulp.task('css', function () { gulp.src('./src/css/*.css') .pipe(gulp.dest('./build/css')); }); gulp.task('clean', function (cb) { del(['build']).then(cb); }); gulp.task('build', ['html', 'css', 'js']); gulp.task('dev', ['html', 'css'], function () { // Start a webpack-dev-server var compiler = webpack(config); new WebpackDevServer(compiler, { // server and middleware options }).listen(8080, "localhost", function(err) { if(err) throw new gutil.PluginError("webpack-dev-server", err); // Server listening $.util.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html"); }); });
JavaScript
0.999999
@@ -706,18 +706,42 @@ %5D).then( -cb +function () %7B%0A cb()%0A %7D );%0A%7D);%0A%0A
88aa9473760e723209b6ff248f06ba683dad14b4
Make MessageMentions#channels return an empty collection in DMs (#1430)
src/structures/MessageMentions.js
src/structures/MessageMentions.js
const Collection = require('../util/Collection'); /** * Keeps track of mentions in a {@link Message} */ class MessageMentions { constructor(message, users, roles, everyone) { /** * Whether `@everyone` or `@here` were mentioned * @type {boolean} */ this.everyone = Boolean(everyone); if (users) { if (users instanceof Collection) { /** * Any users that were mentioned * @type {Collection<Snowflake, User>} */ this.users = new Collection(users); } else { this.users = new Collection(); for (const mention of users) { let user = message.client.users.get(mention.id); if (!user) user = message.client.dataManager.newUser(mention); this.users.set(user.id, user); } } } else { this.users = new Collection(); } if (roles) { if (roles instanceof Collection) { /** * Any roles that were mentioned * @type {Collection<Snowflake, Role>} */ this.roles = new Collection(roles); } else { this.roles = new Collection(); for (const mention of roles) { const role = message.channel.guild.roles.get(mention); if (role) this.roles.set(role.id, role); } } } else { this.roles = new Collection(); } /** * Content of the message * @type {Message} * @private */ this._content = message.content; /** * Guild the message is in * @type {?Guild} * @private */ this._guild = message.channel.guild; /** * Cached members for {@MessageMention#members} * @type {?Collection<Snowflake, GuildMember>} * @private */ this._members = null; /** * Cached channels for {@MessageMention#channels} * @type {?Collection<Snowflake, GuildChannel>} * @private */ this._channels = null; } /** * Any members that were mentioned (only in {@link TextChannel}s) * @type {?Collection<Snowflake, GuildMember>} * @readonly */ get members() { if (this._members) return this._members; if (!this._guild) return null; this._members = new Collection(); this.users.forEach(user => { const member = this._guild.member(user); if (member) this._members.set(member.user.id, member); }); return this._members; } /** * Any channels that were mentioned (only in {@link TextChannel}s) * @type {?Collection<Snowflake, GuildChannel>} * @readonly */ get channels() { if (this._channels) return this._channels; if (!this._guild) return null; this._channels = new Collection(); let matches; while ((matches = this.constructor.CHANNELS_PATTERN.exec(this._content)) !== null) { const chan = this._guild.channels.get(matches[1]); if (chan) this._channels.set(chan.id, chan); } return this._channels; } } /** * Regular expression that globally matches `@everyone` and `@here` * @type {RegExp} */ MessageMentions.EVERYONE_PATTERN = /@(everyone|here)/g; /** * Regular expression that globally matches user mentions like `<#81440962496172032>` * @type {RegExp} */ MessageMentions.USERS_PATTERN = /<@!?[0-9]+>/g; /** * Regular expression that globally matches role mentions like `<@&297577916114403338>` * @type {RegExp} */ MessageMentions.ROLES_PATTERN = /<@&[0-9]+>/g; /** * Regular expression that globally matches channel mentions like `<#222079895583457280>` * @type {RegExp} */ MessageMentions.CHANNELS_PATTERN = /<#([0-9]+)>/g; module.exports = MessageMentions;
JavaScript
0
@@ -2442,32 +2442,42 @@ mentioned (only +populated in %7B@link TextCh @@ -2489,33 +2489,32 @@ %7Ds)%0A * @type %7B -? Collection%3CSnowf @@ -2621,16 +2621,55 @@ annels;%0A + this._channels = new Collection();%0A if ( @@ -2685,34 +2685,24 @@ ild) return -null;%0A this._channe @@ -2703,35 +2703,16 @@ channels - = new Collection() ;%0A le
4f1730d76c5d16ad8ff570249f928621c2039a1f
Fix gulp hanging at end of build (#950)
gulpfile.js
gulpfile.js
(function(){ "use strict"; var path = require('path'), gulp = require('gulp'), concat = require('gulp-concat'), ngAnnotate = require('gulp-ng-annotate'), uglify = require('gulp-uglify'), jshint = require('gulp-jshint'), semistandard = require('gulp-semistandard'), KarmaServer = require('karma').Server, dependencies = require('./web/public/dependencies.json'), app = require('./web/public/app.json'), less = require('gulp-less'), del = require('del'); var lessFiles = [ relativePath('./web/public/css/app.less'), relativePath('./web/public/js/directives/**/*.less')]; function relativePath(paths) { if (paths.constructor === [].constructor) { for (var i = 0; i < paths.length; i++) { paths[i] = path.join(__dirname, paths[i]); } return paths; } else { return path.join(__dirname, paths); } } gulp.task('clean', function () { return del(relativePath([ './web/public/dist/**/*' ])); }); gulp.task('jshint', function () { return gulp.src(relativePath([ './web/controllers/**/*.js', './lib/**/*.js', './web/models/!**!/!*.js', './web/public/js/**/*.js' ])) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(jshint.reporter('fail')); }); gulp.task('semistandard', function () { return gulp.src(relativePath([ './lib/**/*.js' ])) .pipe(semistandard()) .pipe(semistandard.reporter('default', { breakOnError: true })); }); gulp.task('build-dependencies', ['clean'], function () { return gulp.src(relativePath(dependencies)) .pipe(ngAnnotate()) .pipe(concat('dependencies.js')) .pipe(uglify()) .pipe(gulp.dest(relativePath('./web/public/dist/'))); }); gulp.task('build-less', ['clean'], function () { return gulp.src(lessFiles) .pipe(concat('app.less')) .pipe(less({ compress: true, paths: relativePath('./web/public/css/') })) .pipe(gulp.dest(relativePath('./web/public/dist/css/'))) }); gulp.task('build', ['clean', 'jshint', 'build-less', 'build-dependencies'], function () { return gulp.src(relativePath(app)) .pipe(ngAnnotate()) .pipe(concat('app.js')) //.pipe(uglify()) // Commented out until we figure it out why it's breaking .pipe(gulp.dest(relativePath('./web/public/dist/'))); }); gulp.task('test', ['semistandard', 'build'], function (done) { new KarmaServer({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done).start(); }); gulp.task('watch-less', ['build-less'], function(){ return gulp.watch([ relativePath('./web/public/css/**/*.less'), relativePath('./web/public/js/directives/**/*.less')], ['build-less']); }); gulp.task('default', ['test']); gulp.task('dev', ['watch-less']); })();
JavaScript
0
@@ -2912,14 +2912,119 @@ ss'%5D);%0A%0A + gulp.on('stop', function () %7B process.exit(0); %7D);%0A gulp.on('err', function () %7B process.exit(1); %7D);%0A %7D)();%0A
c727e206e5b14429bdf4ed88ebf11f6a94081356
Disable gulp-notifier
gulpfile.js
gulpfile.js
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Less | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.less('app.less'); });
JavaScript
0.000007
@@ -34,16 +34,53 @@ xir');%0A%0A +process.env.DISABLE_NOTIFIER = true%0A%0A /*%0A %7C---
b2a69adb9cfa09314775107d5cabc9c375826174
Lowercase the error source to match 'npm'
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var uglify = require('gulp-uglifyjs'); var deleteFiles = require('del'); var sass = require('gulp-sass'); var filelog = require('gulp-filelog'); var include = require('gulp-include'); var colours = require('colors/safe'); // Paths var environment; var repoRoot = __dirname + '/'; var bowerRoot = repoRoot + 'bower_components'; var npmRoot = repoRoot + 'node_modules'; var govukToolkitRoot = npmRoot + '/govuk_frontend_toolkit'; var dmToolkitRoot = bowerRoot + '/digitalmarketplace-frontend-toolkit/toolkit'; var sspContentRoot = bowerRoot + '/digital-marketplace-ssp-content'; var assetsFolder = repoRoot + 'app/assets'; var staticFolder = repoRoot + 'app/static'; var govukTemplateFolder = repoRoot + 'bower_components/govuk_template'; var govukTemplateAssetsFolder = govukTemplateFolder + '/assets'; var govukTemplateLayoutsFolder = govukTemplateFolder + '/views/layouts'; // JavaScript paths var jsSourceFile = assetsFolder + '/javascripts/application.js'; var jsDistributionFolder = staticFolder + '/javascripts'; var jsDistributionFile = 'application.js'; // CSS paths var cssSourceGlob = assetsFolder + '/scss/application*.scss'; var cssDistributionFolder = staticFolder + '/stylesheets'; // Configuration var sassOptions = { development: { outputStyle: 'expanded', lineNumbers: true, includePaths: [ assetsFolder + '/scss', dmToolkitRoot + '/scss', govukToolkitRoot + '/stylesheets', ], sourceComments: true, errLogToConsole: true }, production: { outputStyle: 'compressed', lineNumbers: true, includePaths: [ assetsFolder + '/scss', dmToolkitRoot + '/scss', govukToolkitRoot + '/stylesheets', ], }, }; var uglifyOptions = { development: { mangle: false, output: { beautify: true, semicolons: true, comments: true, indent_level: 2 }, compress: false }, production: { mangle: true } }; var logErrorAndExit = function logErrorAndExit(err) { var printError = function (type, message) { console.log('Gulp ' + colours.red('ERR! ') + type + ': ' + message); }; printError('message', err.message); printError('file name', err.fileName); printError('line number', err.lineNumber); process.exit(1); }; gulp.task('clean', function (cb) { var fileTypes = []; var complete = function (fileType) { fileTypes.push(fileType); if (fileTypes.length == 2) { cb(); } }; var logOutputFor = function (fileType) { return function (err, paths) { if (paths !== undefined) { console.log('💥 Deleted the following ' + fileType + ' files:\n', paths.join('\n')); } complete(fileType); }; }; deleteFiles(jsDistributionFolder + '/**/*', logOutputFor('JavaScript')); deleteFiles(cssDistributionFolder + '/**/*', logOutputFor('CSS')); }); gulp.task('sass', function () { var stream = gulp.src(cssSourceGlob) .pipe(filelog('Compressing SCSS files')) .pipe( sass(sassOptions[environment])) .on('error', logErrorAndExit) .pipe(gulp.dest(cssDistributionFolder)); stream.on('end', function () { console.log('💾 Compressed CSS saved as .css files in ' + cssDistributionFolder); }); return stream; }); gulp.task('js', function () { var stream = gulp.src(jsSourceFile) .pipe(filelog('Compressing JavaScript files')) .pipe(include()) .pipe(uglify( jsDistributionFile, uglifyOptions[environment] )) .pipe(gulp.dest(jsDistributionFolder)); stream.on('end', function () { console.log('💾 Compressed JavaScript saved as ' + jsDistributionFolder + '/' + jsDistributionFile); }); return stream; }); function copyFactory(resourceName, sourceFolder, targetFolder) { return function() { return gulp .src(sourceFolder + "/**/*", { base: sourceFolder }) .pipe(gulp.dest(targetFolder)) .on('end', function () { console.log('📂 Copied ' + resourceName); }); }; } gulp.task( 'copy:template_assets:stylesheets', copyFactory( "GOV.UK template stylesheets", govukTemplateAssetsFolder + '/stylesheets', staticFolder + '/stylesheets' ) ); gulp.task( 'copy:template_assets:images', copyFactory( "GOV.UK template images", govukTemplateAssetsFolder + '/images', staticFolder + '/images' ) ); gulp.task( 'copy:template_assets:javascripts', copyFactory( 'GOV.UK template Javascript files', govukTemplateAssetsFolder + '/javascripts', staticFolder + '/javascripts' ) ); gulp.task( 'copy:dm_toolkit_assets:stylesheets', copyFactory( "stylesheets from the Digital Marketplace frontend toolkit", dmToolkitRoot + '/scss', 'app/assets/scss/toolkit' ) ); gulp.task( 'copy:dm_toolkit_assets:images', copyFactory( "images from the Digital Marketplace frontend toolkit", dmToolkitRoot + '/images', staticFolder + '/images' ) ); gulp.task( 'copy:govuk_toolkit_assets:images', copyFactory( "images from the GOVUK frontend toolkit", govukToolkitRoot + '/images', staticFolder + '/images' ) ); gulp.task( 'copy:dm_toolkit_assets:templates', copyFactory( "templates from the Digital Marketplace frontend toolkit", dmToolkitRoot + '/templates', 'app/templates/toolkit' ) ); gulp.task( 'copy:images', copyFactory( "image assets from app to static folder", assetsFolder + '/images', staticFolder + '/images' ) ); gulp.task( 'copy:govuk_template', copyFactory( "GOV.UK template into app folder", govukTemplateLayoutsFolder, 'app/templates/govuk' ) ); gulp.task( 'copy:ssp_content', copyFactory( "content YAML into app folder", sspContentRoot, 'app/content' ) ); gulp.task('watch', ['build:development'], function () { var jsWatcher = gulp.watch([ assetsFolder + '/**/*.js' ], ['js']); var cssWatcher = gulp.watch([ assetsFolder + '/**/*.scss' ], ['sass']); var notice = function (event) { console.log('File ' + event.path + ' was ' + event.type + ' running tasks...'); }; cssWatcher.on('change', notice); jsWatcher.on('change', notice); }); gulp.task('set_environment_to_development', function (cb) { environment = 'development'; cb(); }); gulp.task('set_environment_to_production', function (cb) { environment = 'production'; cb(); }); gulp.task( 'copy', [ 'copy:ssp_content', 'copy:template_assets:images', 'copy:template_assets:stylesheets', 'copy:template_assets:javascripts', 'copy:govuk_toolkit_assets:images', 'copy:dm_toolkit_assets:stylesheets', 'copy:dm_toolkit_assets:images', 'copy:dm_toolkit_assets:templates', 'copy:images', 'copy:govuk_template' ] ); gulp.task( 'compile', [ 'copy' ], function() { gulp.start('sass'); gulp.start('js'); } ); gulp.task('build:development', ['set_environment_to_development', 'clean'], function () { gulp.start('compile'); }); gulp.task('build:production', ['set_environment_to_production', 'clean'], function () { gulp.start('compile'); });
JavaScript
0.998563
@@ -2072,17 +2072,17 @@ le.log(' -G +g ulp ' +
5f9884433df23b78ca063001cfb594081ca5bc35
Add command exists to utils
app/libs/utils/index.js
app/libs/utils/index.js
'use strict'; module.exports = { camelCase: require('./camel-case'), colorString: require('./color-string'), nestOptions: require('./nest-options'), uid: require('./uid'), request: require('./request'), metadata: require('./metadata'), framerate: require('./framerate'), normalizeLanguage: require('./normalize-language'), pad: require('./pad'), output: require('./output') };
JavaScript
0.000006
@@ -387,12 +387,58 @@ output') +,%0A commandExists: require('./command-exists') %0A%7D;%0A
99dab100b7ec1ac276b321a814ccefca744872fd
Add missing window check. See #12461
src/renderers/webvr/WebVRManager.js
src/renderers/webvr/WebVRManager.js
/** * @author mrdoob / http://mrdoob.com/ */ import { Matrix4 } from '../../math/Matrix4.js'; import { Vector4 } from '../../math/Vector4.js'; import { ArrayCamera } from '../../cameras/ArrayCamera.js'; import { PerspectiveCamera } from '../../cameras/PerspectiveCamera.js'; function WebVRManager( renderer ) { var scope = this; var device = null; var frameData = null; if ( typeof window !== 'undefined' && 'VRFrameData' in window ) { frameData = new window.VRFrameData(); } var matrixWorldInverse = new Matrix4(); var standingMatrix = new Matrix4(); var standingMatrixInverse = new Matrix4(); var cameraL = new PerspectiveCamera(); cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 ); cameraL.layers.enable( 1 ); var cameraR = new PerspectiveCamera(); cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 ); cameraR.layers.enable( 2 ); var cameraVR = new ArrayCamera( [ cameraL, cameraR ] ); cameraVR.layers.enable( 1 ); cameraVR.layers.enable( 2 ); // var currentSize, currentPixelRatio; function onVRDisplayPresentChange() { if ( device !== null && device.isPresenting ) { var eyeParameters = device.getEyeParameters( 'left' ); var renderWidth = eyeParameters.renderWidth; var renderHeight = eyeParameters.renderHeight; currentPixelRatio = renderer.getPixelRatio(); currentSize = renderer.getSize(); renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 ); } else if ( scope.enabled ) { renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio ); } } if ( typeof window !== 'undefined' ) { window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false ); } // this.enabled = false; this.standing = false; this.getDevice = function () { return device; }; this.setDevice = function ( value ) { if ( value !== undefined ) device = value; }; this.getCamera = function ( camera ) { if ( device === null ) return camera; device.depthNear = camera.near; device.depthFar = camera.far; device.getFrameData( frameData ); // var pose = frameData.pose; if ( pose.position !== null ) { camera.position.fromArray( pose.position ); } else { camera.position.set( 0, 0, 0 ); } if ( pose.orientation !== null ) { camera.quaternion.fromArray( pose.orientation ); } camera.updateMatrixWorld(); var stageParameters = device.stageParameters; if ( this.standing && stageParameters ) { standingMatrix.fromArray( stageParameters.sittingToStandingTransform ); standingMatrixInverse.getInverse( standingMatrix ); camera.matrixWorld.multiply( standingMatrix ); camera.matrixWorldInverse.multiply( standingMatrixInverse ); } if ( device.isPresenting === false ) return camera; // cameraL.near = camera.near; cameraR.near = camera.near; cameraL.far = camera.far; cameraR.far = camera.far; cameraVR.matrixWorld.copy( camera.matrixWorld ); cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse ); cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix ); cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix ); if ( this.standing && stageParameters ) { cameraL.matrixWorldInverse.multiply( standingMatrixInverse ); cameraR.matrixWorldInverse.multiply( standingMatrixInverse ); } var parent = camera.parent; if ( parent !== null ) { matrixWorldInverse.getInverse( parent.matrixWorld ); cameraL.matrixWorldInverse.multiply( matrixWorldInverse ); cameraR.matrixWorldInverse.multiply( matrixWorldInverse ); } // envMap and Mirror needs camera.matrixWorld cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse ); cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse ); cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix ); cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix ); // HACK @mrdoob // https://github.com/w3c/webvr/issues/203 cameraVR.projectionMatrix.copy( cameraL.projectionMatrix ); // var layers = device.getLayers(); if ( layers.length ) { var layer = layers[ 0 ]; if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) { cameraL.bounds.fromArray( layer.leftBounds ); } if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) { cameraR.bounds.fromArray( layer.rightBounds ); } } return cameraVR; }; this.getStandingMatrix = function () { return standingMatrix; }; this.submitFrame = function () { if ( device && device.isPresenting ) device.submitFrame(); }; this.dispose = function () { window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange ); }; } export { WebVRManager };
JavaScript
0
@@ -4625,24 +4625,67 @@ ction () %7B%0A%0A +%09%09if ( typeof window !== 'undefined' ) %7B%0A%0A%09 %09%09window.rem @@ -4753,24 +4753,29 @@ tChange );%0A%0A +%09%09%7D%0A%0A %09%7D;%0A%0A%7D%0A%0Aexpo
e2e0087d868755300174cddb511409e824f40805
add qunit for gulp
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gulpFilter = require('gulp-filter'); var clean = require('gulp-clean'); var rename = require('gulp-rename'); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var qunit = require('gulp-qunit'); var paths = { src: [ 'src/__intro.js', 'src/core.js', 'src/utils.js', 'src/serialize.js', 'src/object.js', 'src/asset.js', 'src/rect.js', 'src/texture.js', 'src/spriteTexture.js', 'src/atlas.js', 'src/__outro.js', ], dev: 'bin/core.dev.js', min: 'bin/core.min.js', }; // clean gulp.task('clean', function() { return gulp.src('bin/**/*', {read: false}) .pipe(clean()) ; }); // dev gulp.task('dev', function() { var filter = gulpFilter( ['!__intro.js','!__outro.js'] ); return gulp.src(paths.src) .pipe(filter) .pipe(jshint()) .pipe(jshint.reporter(stylish)) .pipe(filter.restore()) .pipe(concat('core.dev.js')) .pipe(gulp.dest('bin')) ; }); // min gulp.task('min', ['dev'], function() { return gulp.src('bin/core.dev.js') .pipe(rename('core.min.js')) .pipe(uglify()) .pipe(gulp.dest('bin')) ; }); // gulp.task('default', ['min'] );
JavaScript
0.000001
@@ -25,25 +25,25 @@ ');%0Avar gulp -F +f ilter = requ @@ -876,9 +876,9 @@ gulp -F +f ilte @@ -1296,16 +1296,137 @@ ;%0A%7D);%0A%0A +// test%0Agulp.task('test', %5B'dev'%5D, function() %7B%0A return gulp.src('test/unit/**/*.html')%0A .pipe(qunit())%0A ;%0A%7D);%0A%0A //%0Agulp.
9b2347968e19c19bf810df0d6f0f36ece10a24fb
Update piwik-api.js
lib/piwik-api.js
lib/piwik-api.js
/** * nodejs-piwik-api **/ var http = require("http"); var url = require("url"); var PiwikAPI = function() { this.configure = this.configure.bind(this); this.get = this.get.bind(this); }; PiwikAPI.prototype.configure = function(options) { if(!options) { console.log("Merci de spécifier des options"); process.exit(1); } if(!options.url) { console.log("Please enter a valid url"); process.exit(1); } if(options.url.indexOf("http://") < 0) { options.url = "http://" + options.url; } var u = url.parse(options.url); this.host = u.hostname || ""; this.path = u.path || ""; this.port = options.port || ""; this.token = options.defaultToken || "anonymous"; } PiwikAPI.prototype.get = function(options, vars, cb) { // options if(!options) { options = {}; } var method = options.method; var token = options.token || this.token; // variables if(!vars) { vars = {}; } var ch = ""; for(key in vars) { var value = vars[key]; if(Object.prototype.toString.call(value) === '[object Array]') { // array var tab = value; for(k in tab) { ch += "&" + key + "[]=" + encodeURIComponent(tab[k]); } } else if(Object.prototype.toString.call(value) === '[object Object]') { // object var tab = value; for(k in tab) { ch += "&" + key + "[" + k + "]=" + encodeURIComponent(tab[k]); } } else { // string ch += "&" + key + "=" + encodeURIComponent(value); } } // get var path = this.path + "?module=API&method=" + method + "&format=json&token_auth=" + token + ch; http.get({host: this.host, port: this.port, path: path}, function(response) { var str = ""; response.on("data", function(chunk) { str += chunk; }); response.on("end", function() { str = JSON.parse(str); cb(str); }); }); }; module.exports = new PiwikAPI;
JavaScript
0.000001
@@ -614,16 +614,26 @@ .port %7C%7C + u.port %7C%7C %22%22;%0A%09th
1da7508cf17a24588e3ac0f8617da122b7a45e45
fix mistake
gulpfile.js
gulpfile.js
var gulp = require('gulp'), jshint = require('gulp-jshint'), concat = require('gulp-continuous-concat'), uglify = require('gulp-uglify'), gzip = require('gulp-gzip'), babel = require('gulp-babel'), rimraf = require('rimraf'), watch = require('gulp-watch'), plumber = require('gulp-plumber'), debug = require('gulp-debug'), addsrc = require('gulp-add-src'), livereload = require('gulp-livereload'); files = [ './js/*.jsx', './js/*.js' ], deps = [ './bower_components/react/react.js', './bower_components/react/react-dom.js' ]; gulp.task('clean-scripts', function (cb) { return rimraf('./resources/public', cb); }); gulp.task('deploy', function() { gulp.src(files) .pipe(babel()) .pipe(addsrc(deps)) .pipe(concat('questionnaire.js')) .pipe(uglify()) .pipe(gzip()) .pipe(gulp.dest('./public/scripts')); }); gulp.task('dev', function() { gulp.src(files) .pipe(watch('js/*.jsx')) .pipe(debug()) .pipe(babel()) .pipe(plumber()) .pipe(addsrc.prepend(deps)) .pipe(concat('questionmark.js')) .pipe(debug()) .pipe(gulp.dest('./resources/public')) .pipe(livereload({start: true})); }); gulp.task('lint', function () { gulp.src(['file.js']) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-stylish')); });
JavaScript
0.999908
@@ -433,17 +433,17 @@ reload') -; +, %0A%0A fi
2e339d0df1f76c055e9a21e47dddc2dc935d5837
add gulp-unused
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var eslint = require('gulp-eslint'); gulp.task('coverage', function() { return gulp.src(['index.js', 'lib/*.js']) .pipe(istanbul()) .pipe(istanbul.hookRequire()); }); gulp.task('mocha', ['coverage'], function() { return gulp.src('test/*.js') .pipe(mocha({reporter: 'spec'})) .pipe(istanbul.writeReports()); }); gulp.task('eslint', function() { return gulp.src(['gulpfile.js', 'index.js', 'lib/*.js']) .pipe(eslint()) .pipe(eslint.format()); }); gulp.task('default', ['mocha', 'eslint']);
JavaScript
0.999296
@@ -67,24 +67,61 @@ lp-mocha');%0A +var unused = require('gulp-unused');%0A var istanbul @@ -339,21 +339,20 @@ p.task(' -mocha +test ', %5B'cov @@ -493,18 +493,16 @@ p.task(' -es lint', f @@ -537,40 +537,46 @@ c(%5B' -gulpfile +* .js', ' -index +lib/* .js', ' -lib +test/%7B*,support /* +%7D .js' @@ -646,31 +646,177 @@ sk(' -default', %5B'mocha', 'es +unused', function() %7B%0A return gulp.src(%5B'index.js', 'lib/*.js'%5D)%0A .pipe(unused(%7Bkeys: Object.keys(require('./lib/utils.js'))%7D));%0A%7D);%0A%0Agulp.task('default', %5B'test', ' lint
5edcd8b1bf1dc5751135a4f9f5d8f730f9a68db7
Update gulp deprecated code.
gulpfile.js
gulpfile.js
var gulp = require('gulp'), spawn = require('child_process').spawn, node; gulp.task('server', function() { if (node) node.kill() node = spawn('node', ['index.js'], {stdio: 'inherit'}) node.on('close', function (code) { if (code === 8) { gulp.log('Error detected, waiting for changes...'); } }); }) gulp.task('default', function() { gulp.run('server') gulp.watch(['./index.js', './lib/**/*.js'], function() { gulp.run('server') }) }) process.on('exit', function() { if (node) node.kill() })
JavaScript
0
@@ -360,27 +360,29 @@ () %7B%0A gulp. -run +start ('server')%0A%0A @@ -379,17 +379,17 @@ server') -%0A +; %0A gulp. @@ -431,52 +431,24 @@ '%5D, -function() %7B%0A gulp.run('server')%0A %7D)%0A%0A%7D) +%5B'server'%5D);%0A%7D)%0A %0A%0Apr @@ -505,8 +505,9 @@ ill()%0A%7D) +%0A
cb8cb0b683a5b2bd4e6975102fbca627e47c3a17
Fix syntax error in standard Javascript.
lib/readfiles.js
lib/readfiles.js
var fs = require('fs'), path = require('path'); /** * merge two objects by extending target object with source object * @param target object to merge * @param source object to merge * @param {Boolean} [modify] whether to modify the target * @returns {Object} extended object */ function extend(target, source, modify) { var result = target ? modify ? target : extend({}, target, true) : {}; if (!source) return result; for (var key in source) { if (source.hasOwnProperty(key) && source[key] !== undefined) { result[key] = source[key]; } } return result; } /** * determine if a string is contained within an array or matches a regular expression * @param {String} str string to match * @param {Array|Regex} match array or regular expression to match against * @returns {Boolean} whether there is a match */ function matches(str, match) { if (Array.isArray(match)) return match.indexOf(str) > -1; return match.test(str); } /** * read files and call a function with the contents of each file * @param {String} dir path of dir containing the files to be read * @param {String} encoding file encoding (default is 'utf8') * @param {Object} options options hash for encoding, recursive, and match/exclude * @param {Function(error, string)} callback callback for each files content * @param {Function(error)} complete fn to call when finished * @param {String} _rootDir internal copy of the initial dir (for excludeRelDir) */ function readFiles(dir, options, callback, complete, _rootDir=null) { if (typeof options === 'function') { complete = callback; callback = options; options = {}; } if (typeof options === 'string') options = { encoding: options }; options = extend({ recursive: true, encoding: 'utf8', doneOnErr: true }, options); if ( options.recursive ) _rootDir = _rootDir || dir var files = []; var done = function(err) { if (typeof complete === 'function') { if (err) return complete(err); complete(null, files); } }; fs.readdir(dir, function(err, list) { if (err)  { if (options.doneOnErr === true) { if (err.code === 'EACCES') return done(); return done(err); } } var i = 0; if (options.reverse === true || (typeof options.sort == 'string' && (/reverse|desc/i).test(options.sort))) { list = list.reverse(); } else if (options.sort !== false) list = list.sort(); (function next() { var filename = list[i++]; if (!filename) return done(null, files); var file = path.join(dir, filename); fs.stat(file, function(err, stat) { if (err && options.doneOnErr === true) return done(err); if (stat && stat.isDirectory()) { if (options.recursive) { if (options.matchDir && !matches(filename, options.matchDir)) return next(); if (options.excludeDir && matches(filename, options.excludeDir)) return next(); if (options.excludeRelDir && matches(path.relative(_rootDir, file), options.excludeRelDir)) return next(); readFiles(file, options, callback, function(err, sfiles) { if (err && options.doneOnErr === true) return done(err); files = files.concat(sfiles); next(); }, _rootDir); } else next(); } else if (stat && stat.isFile()) { if (options.match && !matches(filename, options.match)) return next(); if (options.exclude && matches(filename, options.exclude)) return next(); if (options.filter && !options.filter(filename)) return next(); if (options.shortName) files.push(filename); else files.push(file); fs.readFile(file, options.encoding, function(err, data) { if (err) { if (err.code === 'EACCES') return next(); if (options.doneOnErr === true) { return done(err); } } if (callback.length > 3) if (options.shortName) callback(null, data, filename, next); else callback(null, data, file, next); else callback(null, data, next); }); } else { next(); } }); })(); }); } module.exports = readFiles;
JavaScript
0
@@ -1572,13 +1572,8 @@ tDir -=null ) %7B%0A
a331e01c54cff71de3afc5ce40ff76d81d43a2f1
return response as an error
lib/rpcclient.js
lib/rpcclient.js
var http = require('http'); var https = require('https'); var buffer = require('buffer'); /* Rpc Client Object * * new Client (options) * - options: json options object * * Define: json options object: { * port: int port of rpc server, default 5080 for http or 5433 for https * host: string domain name or ip of rpc server, default '127.0.0.1' * path: string with default path, default '/' * * contentType: string with content-type, default 'application/json' * * login: string rpc login name, default null * hash: string rpc password (hash), default null * * ssl: json ssl object, default null * * Define: 'json ssl object: { * ca: array of string with ca's to use, default null * key: string with private key to use, default null * pfx: string with key, cert and ca info in PFX format, default null * cert: string with the public x509 certificate to use, default null * strict: boolean false to disable remote cert verification, default true * passphrase: string passphrase to be used to acces key or pfx, default null * protocol: string ssl protocol to use, default 'SSLv3_client_method' * sniName: string name for Server Name Indication, default 'RPC-Server' * } * } */ var Client = function (options) { var serv, agent; var self = this; options = options || {}; var conf = { host: options.host || '127.0.0.1', path: options.path || '/', contentType: options.contentType || 'application/json', hash: options.hash || null, login: options.login || null, }; if (options.ssl) { conf.ssl = { sniName: options.ssl.sniName || 'RPC-Server', protocol: options.ssl.protocol || 'SSLv3_client_method' }; if (options.ssl.pfx) { conf.ssl.pfx = options.ssl.pfx; conf.ssl.strict = options.ssl.strict || true; } else { if (options.ssl.ca) { conf.ssl.ca = options.ssl.ca; conf.ssl.strict = options.ssl.strict || true; } if (options.ssl.key && options.ssl.cert) { conf.ssl.key = options.ssl.key; conf.ssl.cert = options.ssl.certs; } } if (options.ssl.passphrase) { conf.ssl.passphrase = options.ssl.passphrase; } } if (conf.ssl) { serv = https; agent = new https.Agent(); conf.port = options.port || 5433; } else { serv = http; agent = new http.Agent(); conf.port = options.port || 5080; } /* Private: Returns options object for http request */ var buildOptions = function (opts) { var options = { agent: agent, method: opts.method, host: conf.host, port: conf.port, path: opts.path, headers: { 'host': conf.host + ':' + conf.port, 'content-type': conf.contentType, 'content-length': opts.length, } }; if (opts.login && opts.hash) options.auth = opts.login + ':' + opts.hash; if (conf.ssl) { options.servername = conf.ssl.sniName || 'RPC-Server'; options.secureProtocol = conf.ssl.protocol || 'SSLv3_client_method'; if (conf.ssl.pfx) { options.pfx = conf.ssl.pfx; options.rejectUnauthorized = conf.ssl.strict || true; } else { if (conf.ssl.key && conf.ssl.cert) { options.key = conf.ssl.key; options.cert = conf.ssl.cert; } if (conf.ssl.ca) { options.ca = conf.ssl.ca; options.rejectUnauthorized = conf.ssl.strict || true; } } if (conf.ssl.passphrase) options.passphrase = conf.ssl.passphrase; } return options; }; /* Public: Call a function on remote server. * - data: json request object, required * - callback: function (error, result) -> null, required * - opts: json options object, default {} * * Define: '' { * path: string request path, defaul '/' * method: string request method, default 'POST' * * hash: string user password, default null * login: string user login name, default null * } */ this.call = function (data, callback, opts) { opts = opts || {} var body = new Buffer(JSON.stringify(data)); var options = buildOptions({ length: body.length, method: opts.method || 'POST', path: opts.path || conf.path, login: opts.login || conf.login, hash: opts.hash || conf.hash }); var request = serv.request(options); request.on('error', function (error) { //TODO Proccess Request Error console.error(error); callback(error); }); request.on('response', function (response) { var data = ''; response.on('data', function(bytes) { data += bytes; }); response.on('end', function() { var error, result; //TODO Deal with 401 and other codes if (response.statusCode === 200 || response.statusCode === 304) { if (data.length > 0) { try { result = JSON.parse(data); } catch (err) { error = err; console.error("Client error: failed to parse response from server."); } } } else console.log("Client: TODO Status Code: " + response.statusCode); callback(error, result); }); }); request.end(body); }; options = null; }; module.exports = Client;
JavaScript
0.00003
@@ -5207,21 +5207,57 @@ %7D -%0A else + else %7B%0A error = response;%0A con @@ -5317,16 +5317,26 @@ usCode); +%0A %7D %0A%0A
185a565dffc37c7bc75db8fd95fa550c6c311e85
Allow resolving the active child of a Typefield
src/resources/elements/typefield.js
src/resources/elements/typefield.js
import {containerless, bindable} from 'aurelia-framework'; import {Field} from './abstract/field'; import {parseJSON} from '../jsonparser'; /** * Typefield is a {@link Field} that shows different child forms depending on * the type the user chooses. * * This allows for theoretically infinite nesting because it uses lazy * evaluation and supports $refs in type options. */ @containerless export class Typefield extends Field { /** * The type that is currently selected. * @type {String} */ @bindable selectedType = ''; /** * The key where to put the value of the child field to in the output of this * field. * @type {String} */ valueKey = ''; /** * The key where to put the key of this field ({@link #key}) in the output of * this field. * @type {String} */ keyKey = ''; /** * The current key of this field. Exists as a legend field in the form if * {@link #keyKey} is defined. * @type {String} */ key = ''; /** * The placeholder for the key form field. * @type {String} */ keyPlaceholder = ''; /** * Whether or not to show the chosen type in the value of this field. * @type {Boolean} */ showType = true; /** * Whether or not to copy the value over to the new child when switching types. * * N.B. Absolutely nothing is done to ensure the data ends up in the right * place. Only use this if most of the fields in different types are in nearly * the same places. * @type {Boolean} */ copyValue = false; /** * The current child field. * @type {Field} * @private */ child = undefined; /** * The schemas for the available types. * @type {Object} */ types = {}; /** * Whether or not the UI element should be collapsed (i.e. only show the title) * @type {Boolean} */ collapsed = false; isCollapsible = true; /* * Called by child fields when they are collapsed/uncollapsed. * Unused in Typefields, currently only used in Arrayfields. */ childCollapseChanged(field, isNowCollapsed) {} toggleCollapse() { this.setCollapsed(!this.collapsed); } setCollapsed(collapsed) { this.collapsed = collapsed; if (this.parent) { this.parent.childCollapseChanged(this, this.collapsed); } } /** @inheritdoc */ init(id = '', args = {}) { args = Object.assign({ valueKey: '', keyKey: '', keyPlaceholder: 'Object key...', showType: true, copyValue: false, collapsed: false, types: { 'null': { 'type': 'text' } } }, args); this.types = args.types; this.valueKey = args.valueKey; this.keyKey = args.keyKey; this.keyPlaceholder = args.keyPlaceholder; this.showType = args.showType; this.copyValue = args.copyValue; this.collapsed = args.collapsed; this.defaultType = args.defaultType; this.selectedType = args.defaultType || Object.keys(this.types)[0]; this.selectedTypeChanged(this.selectedType); return super.init(id, args); } /** * Check if this field doesn't currently have a child or if the child is empty. */ isEmpty() { if (!this.child) { return true; } return this.child.isEmpty(); } /** * Called by Aurelia when the selected type changes (e.g. from the dropdown) * @param {String} newType The new type. */ selectedTypeChanged(newType) { const newSchema = this.types[newType]; const value = this.copyValue ? this.getValue() : undefined; let newChild; if (newSchema.hasOwnProperty('$ref')) { newChild = this.resolveRef(newSchema.$ref).clone(); } else { newChild = parseJSON(newType, JSON.parse(JSON.stringify(newSchema))); } if (newChild) { newChild.parent = this; if (value) { this.setValue(value); } this.child = newChild; } this.onChange(); } /** * Get the value of this field. * * If the value of the child is undefined, this will return undefined. * * The value of the child will be put into an object with {@link #valueKey} or * `value` as the key if the value is not already an object and one of the * following is true: * a) {@link #showType} is {@linkplain true} * b) {@link #keyKey} is defined * c) {@link #valueKey} is defined * If {@link #valueKey} is defined, the child value will be put into an object * as described previously regardless of whether or not the child value is an * object. * * If {@link #showType} is {@linkplain true}, the name of the selected type * will be added to the return object. * If {@link #keyKey} is defined, the return object will contain a field with * {@link #keyKey} as its key and the key from the fieldset legend as the value. * * @return {Object} The processed value. */ getValue() { if (!this.child) { return undefined; } let value = this.child.getValue(); // True if the value of the child is either not an object or is an array. // In other words, can/should we put named fields in the value directly? const valueIsNotObject = typeof value !== 'object' || Array.isArray(value); // If valueKey is set, the value of the child should always be stored in an // object with valueKey as the key for the value of the child. // // If the value is not an object or is an array AND either keyKey or // showType is set, the above should be done regardless of whether or not // valueKey is set. if (this.valueKey || (valueIsNotObject && (this.keyKey || this.showType))) { const valueKey = this.valueKey || 'value'; value = { [valueKey]: value }; } if (this.keyKey) { value[this.keyKey] = this.key; } if (this.showType) { value.type = this.selectedType; } return value; } setValue(value) { if (this.keyKey && value.hasOwnProperty(this.keyKey)) { this.key = value[this.keyKey]; } if (!this.showType) { this.child.setValue(value); } else if (typeof value === 'object' && !Array.isArray(value)) { delete value.type; this.child.setValue(value); } else { this.child.setValue(value[this.valueKey || 'value']); } } setType(type) { this.selectedType = type; } getType() { return this.selectedType; } /** * Get all the possible type names. * @return {String[]} The names of the possible types. */ get possibleTypes() { return Object.keys(this.types); } }
JavaScript
0.000002
@@ -6311,24 +6311,283 @@ dType;%0A %7D%0A%0A + resolvePath(path) %7B%0A const superResolv = super.resolvePath(path);%0A if (superResolv) %7B%0A return superResolv;%0A %7D%0A%0A if (this.child && path%5B0%5D === ':child') %7B%0A return this.child.resolvePath(path.splice(1));%0A %7D%0A return undefined;%0A %7D%0A%0A /**%0A * G
7c155c2641079acdb07972778383fd1d7dd4f313
Disable v2 tag tests
src/schema/v2/__tests__/tag.test.js
src/schema/v2/__tests__/tag.test.js
/* eslint-disable promise/always-return */ import { runQuery } from "schema/v2/test/utils" describe("Tag", () => { describe("For just querying the tag artworks", () => { // If this test fails because it's making a gravity request to /tag/x, it's // because the AST checks to find out which nodes we're requesting // is not working correctly. This test is to make sure we don't // request to gravity. it("returns filtered artworks", () => { const context = { authenticatedLoaders: {}, unauthenticatedLoaders: { filterArtworksLoader: sinon .stub() .withArgs("filter/artworks", { tag_id: "butt", aggregations: ["total"], }) .returns( Promise.resolve({ hits: [ { id: "oseberg-norway-queens-ship", title: "Queen's Ship", artists: [], }, ], aggregations: [], }) ), }, } const query = ` { tag(id: "butt") { filteredArtworks(aggregations:[TOTAL]){ hits { slug } } } } ` return runQuery(query, context).then( ({ tag: { filteredArtworks: { hits }, }, }) => { expect(hits).toEqual([{ slug: "oseberg-norway-queens-ship" }]) } ) }) }) })
JavaScript
0
@@ -109,16 +109,87 @@ () =%3E %7B%0A + // FIXME: Tag no longer has a direct connection to filtered artworks%0A descri @@ -190,16 +190,21 @@ describe +.skip (%22For ju @@ -1251,16 +1251,26 @@ Artworks +Connection (aggrega
0f20aff2693f7292a2c8eb966d0394d96979b28f
Add Atomic Scheduler Master Lock
lib/scheduler.js
lib/scheduler.js
// To read notes about the master locking scheme, check out: // https://github.com/resque/resque-scheduler/blob/master/lib/resque/scheduler/locking.rb const EventEmitter = require('events').EventEmitter const os = require('os') const Queue = require('./queue.js').Queue class Scheduler extends EventEmitter { constructor (options, jobs) { super() if (!jobs) { jobs = {} } const defaults = { timeout: 5000, // in ms stuckWorkerTimeout: 60 * 60 * 1000, // 60 minutes in ms masterLockTimeout: 60 * 3, // in seconds name: os.hostname() + ':' + process.pid // assumes only one worker per node process } for (let i in defaults) { if (options[i] === null || options[i] === undefined) { options[i] = defaults[i] } } this.options = options this.name = this.options.name this.master = false this.running = false this.processing = false this.queue = new Queue({ connection: options.connection }, jobs) this.queue.on('error', (error) => { this.emit('error', error) }) } async connect () { await this.queue.connect() this.connection = this.queue.connection } async start () { this.processing = false if (!this.running) { this.emit('start') this.running = true this.pollAgainLater() } } async end () { this.running = false clearTimeout(this.timer) if (this.processing === false) { if (this.connection.connected === true || this.connection.connected === undefined || this.connection.connected === null) { try { await this.releaseMasterLock() } catch (error) { this.emit('error', error) } } try { await this.queue.end() } catch (error) { this.emit('error', error) } this.emit('end') } else { return new Promise((resolve) => { setTimeout(async () => { await this.end() resolve() }, (this.options.timeout / 2)) }) } } async poll () { this.processing = true clearTimeout(this.timer) let isMaster = await this.tryForMaster() if (!isMaster) { this.master = false this.processing = false return this.pollAgainLater() } if (!this.master) { this.master = true this.emit('master') } this.emit('poll') let timestamp = await this.nextDelayedTimestamp() if (timestamp) { this.emit('workingTimestamp', timestamp) await this.enqueueDelayedItemsForTimestamp(timestamp) return this.poll() } else { await this.checkStuckWorkers() this.processing = false return this.pollAgainLater() } } async pollAgainLater () { if (this.running === true) { this.timer = setTimeout(() => { this.poll() }, this.options.timeout) } } masterKey () { return this.connection.key('resque_scheduler_master_lock') } async tryForMaster () { const masterKey = this.masterKey() if (!this.connection || !this.connection.redis) { return } let lockedByMe = await this.connection.redis.setnx(masterKey, this.options.name) if (lockedByMe === true || lockedByMe === 1) { await this.connection.redis.expire(masterKey, this.options.masterLockTimeout) return true } let currentMasterName = await this.connection.redis.get(masterKey) if (currentMasterName === this.options.name) { await this.connection.redis.expire(masterKey, this.options.masterLockTimeout) return true } return false } async releaseMasterLock () { if (!this.connection || !this.connection.redis) { return } let isMaster = await this.tryForMaster() if (!isMaster) { return false } let delted = await this.connection.redis.del(this.masterKey()) this.master = false return (delted === 1 || delted === true) } async nextDelayedTimestamp () { let time = Math.round(new Date().getTime() / 1000) let items = await this.connection.redis.zrangebyscore( this.connection.key('delayed_queue_schedule'), '-inf', time, 'limit', 0, 1 ) if (items.length === 0) { return } return items[0] } async enqueueDelayedItemsForTimestamp (timestamp) { let job = await this.nextItemForTimestamp(timestamp) if (job) { await this.transfer(timestamp, job) await this.enqueueDelayedItemsForTimestamp(timestamp) } else { await this.cleanupTimestamp(timestamp) } } async nextItemForTimestamp (timestamp) { let key = this.connection.key('delayed:' + timestamp) let job = await this.connection.redis.lpop(key) await this.connection.redis.srem(this.connection.key('timestamps:' + job), ('delayed:' + timestamp)) return JSON.parse(job) } async transfer (timestamp, job) { await this.queue.enqueue(job.queue, job['class'], job.args) this.emit('transferredJob', timestamp, job) } async cleanupTimestamp (timestamp) { let key = this.connection.key('delayed:' + timestamp) let length = await this.connection.redis.llen(key) if (length === 0) { await this.connection.redis.del(key) await this.connection.redis.zrem(this.connection.key('delayed_queue_schedule'), timestamp) } } async checkStuckWorkers () { if (!this.options.stuckWorkerTimeout) { return } const keys = await this.connection.getKeys(this.connection.key('worker', 'ping', '*')) const payloads = await Promise.all(keys.map(async (k) => { return JSON.parse(await this.connection.redis.get(k)) })) const nowInSeconds = Math.round(new Date().getTime() / 1000) const stuckWorkerTimeoutInSeconds = Math.round(this.options.stuckWorkerTimeout / 1000) for (let i in payloads) { if (!payloads[i]) continue const { name, time } = payloads[i] const delta = nowInSeconds - time if (delta > stuckWorkerTimeoutInSeconds) { await this.forceCleanWorker(name, delta) } i++ } } async forceCleanWorker (workerName, delta) { const errorPayload = await this.queue.forceCleanWorker(workerName) this.emit('cleanStuckWorker', workerName, errorPayload, delta) } } exports.Scheduler = Scheduler
JavaScript
0
@@ -3101,10 +3101,8 @@ .set -nx (mas @@ -3126,16 +3126,60 @@ ons.name +, 'NX', 'EX', this.options.masterLockTimeout )%0A if @@ -3227,92 +3227,8 @@ ) %7B%0A - await this.connection.redis.expire(masterKey, this.options.masterLockTimeout)%0A
665110c1a06585ceea5483ffa3919c3035abc20b
Add init tags Set to new reverse index docs
src/search/search-index/pipeline.js
src/search/search-index/pipeline.js
import normalizeUrl from 'normalize-url' import transformPageText from 'src/util/transform-page-text' import { convertMetaDocId } from 'src/activity-logger' import { extractContent, keyGen } from './util' import { DEFAULT_TERM_SEPARATOR } from '.' // Simply extracts the timestamp component out the ID of a visit or bookmark doc, // which is the only data we want at the moment. export const transformMetaDoc = doc => convertMetaDocId(doc._id).timestamp const urlNormalizationOpts = { normalizeProtocol: true, // Prepend `http://` if URL is protocol-relative stripFragment: true, // Remove trailing hash fragment stripWWW: true, // Remove any leading `www.` removeTrailingSlash: true, removeQueryParameters: [/.+/], // Remove all query params from terms indexing removeDirectoryIndex: [/^(default|index)\.\w{2,4}$/], // Remove things like tralining `/index.js` or `/default.php` } /** * @param {string} url A raw URL string to attempt to extract parts from. * @returns {any} Object containing `domain` and `remainingUrl` keys. Values should be the `domain.tld.cctld` part and * everything after, respectively. If regex matching failed on given URL, error will be logged and simply * the URL with protocol and opt. `www` parts removed will be returned for both values. */ function transformUrl(url) { let parsed const normalized = normalizeUrl(url, urlNormalizationOpts) try { parsed = new URL(normalized) } catch (error) { console.error(`cannot parse URL: ${url}`) return { hostname: normalized, pathname: normalized } } return { hostname: parsed ? parsed.hostname : normalized, pathname: parsed ? parsed.pathname : normalized, } } /** * @typedef IndexLookupDoc * @type {Object} * @property {string} latest Latest visit/bookmark timestamp time for easy scoring. * @property {string} domain Filter term extracted from page URL. * @property {Set} urlTerms Set of searchable terms extracted from page URL. * @property {Set} terms Set of searchable terms extracted from page content. * @property {Set} visits Set of visit index doc IDs, extracted from visit docs. * @property {Set} bookmarks Set of bookmark index doc IDs, extracted from bookmark docs. */ /** * Function version of "pipeline" logic. Applies transformation logic * on a given doc. * * @param {IndexRequest} req Page doc + assoc. meta event docs. * @returns {IndexLookupDoc} Doc structured for indexing. */ export default function pipeline({ pageDoc: { _id: id, content, url }, visitDocs = [], bookmarkDocs = [], }) { // First apply transformations to the URL const { pathname, hostname } = transformUrl(url) // Throw error if no searchable content; we don't really want to index these (for now) so allow callers // to handle (probably by ignoring) if (!content || !content.fullText || !content.fullText.length === 0) { return Promise.reject(new Error('Page has no searchable content')) } // Run the searchable content through our text transformations, attempting to discard useless data. const { text: transformedContent } = transformPageText({ text: content.fullText, }) const { text: transformedTitle } = transformPageText({ text: content.title, }) const { text: transformedUrlTerms } = transformPageText({ text: pathname, }) // Extract all terms out of processed content let titleTerms, urlTerms const terms = new Set( extractContent(transformedContent, { separator: DEFAULT_TERM_SEPARATOR, key: 'term', }), ) if (transformedTitle && transformedTitle.length) { // Extract all terms out of processed title titleTerms = new Set( extractContent(transformedTitle, { separator: DEFAULT_TERM_SEPARATOR, key: 'title', }), ) } if (pathname && pathname.length) { // Extract all terms out of processed URL urlTerms = new Set( extractContent(transformedUrlTerms, { separator: DEFAULT_TERM_SEPARATOR, key: 'url', }), ) } // Create timestamps to be indexed as Sets const visits = visitDocs.map(transformMetaDoc) const bookmarks = bookmarkDocs.map(transformMetaDoc) return Promise.resolve({ id, terms, urlTerms: urlTerms || new Set(), domain: keyGen.domain(hostname), titleTerms: titleTerms || new Set(), visits: new Set(visits.map(keyGen.visit)), bookmarks: new Set(bookmarks.map(keyGen.bookmark)), }) }
JavaScript
0
@@ -2257,16 +2257,79 @@ k docs.%0A + * @property %7BSet%7D tags Set of searchable tags - init'd empty.%0A */%0A%0A/** @@ -4734,21 +4734,46 @@ bookmark)),%0A + tags: new Set(),%0A %7D)%0A%7D%0A
f3e34f95d3b49bc90131b375a7a6478f70885968
Add Stuff to array
src/regions/states.js
src/regions/states.js
import Collection from '../Collection'; class _States { constructor() { // Get our default Data this.data = this.defaults(); // New up a collection const collection = new Collection; // Add shared collection stuff Object.assign(this.data.__proto__, collection); // Assign any custom collection methods, or override collections // this.data.other = this.other; ? How does this even work this.data.__proto__.withArmedForces = this._withArmedForces; // return the raw array return this.data; } _withArmedForces() { console.log(this.__proto__); this.push({ code: 'AE', name: 'ARMED FORCES AFRICA \ CANADA \ EUROPE \ MIDDLE EAST', }); this.push({ code: 'AA', name: 'ARMED FORCES AMERICA (EXCEPT CANADA)', }); this.push({ code: 'AP', name: 'ARMED FORCES PACIFIC' }); return this; } defaults() { return [ { code: 'AL', name: 'ALABAMA', }, { code: 'AK', name: 'ALASKA', }, { code: 'AS', name: 'AMERICAN SAMOA', }, { code: 'AZ', name: 'ARIZONA', }, { code: 'AR', name: 'ARKANSAS', }, { code: 'CA', name: 'CALIFORNIA', }, { code: 'CO', name: 'COLORADO', }, { code: 'CT', name: 'CONNECTICUT', }, { code: 'DE', name: 'DELAWARE', }, { code: 'DC', name: 'DISTRICT OF COLUMBIA', }, { code: 'FM', name: 'FEDERATED STATES OF MICRONESIA', }, { code: 'FL', name: 'FLORIDA', }, { code: 'GA', name: 'GEORGIA', }, { code: 'GU', name: 'GUAM GU', }, { code: 'HI', name: 'HAWAII', }, { code: 'ID', name: 'IDAHO', }, { code: 'IL', name: 'ILLINOIS', }, { code: 'IN', name: 'INDIANA', }, { code: 'IA', name: 'IOWA', }, { code: 'KS', name: 'KANSAS', }, { code: 'KY', name: 'KENTUCKY', }, { code: 'LA', name: 'LOUISIANA', }, { code: 'ME', name: 'MAINE', }, { code: 'MH', name: 'MARSHALL ISLANDS', }, { code: 'MD', name: 'MARYLAND', }, { code: 'MA', name: 'MASSACHUSETTS', }, { code: 'MI', name: 'MICHIGAN', }, { code: 'MN', name: 'MINNESOTA', }, { code: 'MS', name: 'MISSISSIPPI', }, { code: 'MO', name: 'MISSOURI', }, { code: 'MT', name: 'MONTANA', }, { code: 'NE', name: 'NEBRASKA', }, { code: 'NV', name: 'NEVADA', }, { code: 'NH', name: 'NEW HAMPSHIRE', }, { code: 'NJ', name: 'NEW JERSEY', }, { code: 'NM', name: 'NEW MEXICO', }, { code: 'NY', name: 'NEW YORK', }, { code: 'NC', name: 'NORTH CAROLINA', }, { code: 'ND', name: 'NORTH DAKOTA', }, { code: 'MP', name: 'NORTHERN MARIANA ISLANDS', }, { code: 'OH', name: 'OHIO', }, { code: 'OK', name: 'OKLAHOMA', }, { code: 'OR', name: 'OREGON', }, { code: 'PW', name: 'PALAU', }, { code: 'PA', name: 'PENNSYLVANIA', }, { code: 'PR', name: 'PUERTO RICO', }, { code: 'RI', name: 'RHODE ISLAND', }, { code: 'SC', name: 'SOUTH CAROLINA', }, { code: 'SD', name: 'SOUTH DAKOTA', }, { code: 'TN', name: 'TENNESSEE', }, { code: 'TX', name: 'TEXAS', }, { code: 'UT', name: 'UTAH', }, { code: 'VT', name: 'VERMONT', }, { code: 'VI', name: 'VIRGIN ISLANDS', }, { code: 'VA', name: 'VIRGINIA', }, { code: 'WA', name: 'WASHINGTON', }, { code: 'WV', name: 'WEST VIRGINIA', }, { code: 'WI', name: 'WISCONSIN', }, { code: 'WY', name: 'WYOMING', }, ]; } } let States = new _States; export default States;
JavaScript
0
@@ -562,24 +562,26 @@ ces() %7B%0A +// console.log(
05238a3ba7881bf6ec11bd4d7da6d53665294129
Fix an issue with trailing newlines
lib/transform.js
lib/transform.js
var hash = require('farmhash').fingerprint64; var stream = require('readable-stream'); var util = require('util'); function Transformer(){ // call the parent stream.Transform.call(this); // polyfill for non-ES6 if (!global.Set) { // lazy load a HashSet impl global.Set = require('hashes').HashSet; // polyfill methods to match ES6 Set if (!Set.prototype.has) { Object.defineProperties(Set.prototype, { has: { get: function (){ return this.contains; } }, size: { get: function (){ return this.count(); } } }); } } // define props this.count = 0; this.set = new Set(); this.started = false; // processing piece this.process = function process(element){ var key = hash(element); this.count++; if (!this.set.has(key)) { this.set.add(key); if (this.started) { this.push('\n' + element); } else { this.push(element); this.started = true; } } }; // implement _transform on the stream this._transform = function (chunk, encoding, done) { var data = chunk.toString(); if (this._lastLineData) { data = this._lastLineData + data; } var lines = data.split('\n'); this._lastLineData = lines.splice(lines.length - 1, 1)[0]; lines.forEach(this.process, this); done(); }; // implement _flush on the stream this._flush = function (done) { if (this._lastLineData) { this.process.bind(this, this._lastLineData); } this._lastLineData = null; done(); }; } // inherit from the Transform stream util.inherits(Transformer, stream.Transform); // export the new stream module.exports = Transformer;
JavaScript
0.00009
@@ -1534,18 +1534,18 @@ ind(this -, +)( this._la
9facf82ee23f418abae6aca4fa7a79da3eda01fc
use a HEAD request to get SSL cert info, not a get
lib/util/http.js
lib/util/http.js
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var url = require('url'); var version = require('util/version'); var http = require('http'); var urllib = require('url'); var misc = require('util/misc'); var sprintf = require('extern/sprintf').sprintf; var sys = require('sys'); var fs = require('fs'); var log = require('util/log'); var Errorf = require('util/misc').Errorf; var uri = require('extern/restler/lib/vendor/uri'); var rest = require('extern/restler/lib/restler'); var version = require('util/version'); var crypto = require('crypto'); var dotfiles = require('util/client_dotfiles'); var config = require('util/config'); exports.client = function(remote) { var conf = config.get(); // TODO: remote lookup function remote_lookup(a) { // TODO: Allow custom remotes return {host: 'localhost', port: 49443}; } var r = remote_lookup(remote); var client = null; if (conf.ssl_enabled) { var sslcontext = crypto.createCredentials({method: 'TLSv1_client_method'}); sslcontext.context.setCiphers(conf.ssl_ciphers); client = http.createClient(r.port, r.host, true, sslcontext); } else { client = http.createClient(r.port, r.host); } client.headers = {'host': r.host, 'user-agent': version.toString()}; // TOOD: SSL verify fingerprint return client; }; exports.get_server_ssl_cert_info = function(remote_url, callback) { var conf = config.get(); var callback_called = false; var url_object = url.parse(remote_url); if (url_object.protocol !== 'https:') { callback(new Error('Protocol must be https')); return; } var port = url_object.port || '443'; var hostname = url_object.hostname; var sslcontext = crypto.createCredentials({method: 'TLSv1_client_method'}); sslcontext.context.setCiphers(conf.ssl_ciphers); var client = http.createClient(port, hostname, true, sslcontext); var request = client.request('/'); request.on('response', function(response) { var peer_cert = client.getPeerCertificate(); if (!peer_cert) { callback(new Error('Unable to fetch certificate information')); return; } if (callback_called) { return; } callback(null, peer_cert); callback_called = true; }); function on_error(err) { if (callback_called) { return; } callback(err); callback_called = true; } client.on('error', on_error); request.on('error', on_error); request.end(); }; /** * Write JSON to an HTTP response. * * @param {http.ServerResponse} res The HTTP Response to which to write the data. * @param {Integer} code The HTTP response code to use. * @param {Object} data The data to write to the response. */ exports.return_json = function(res, code, data) { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(data)); }; /** * Return a JSON formatted error with a response code an an optinoal message. * * @param {http.ServerResponse} res The HTTP Response to which to write the * error. * @param {Integer} code The HTTP response code to use. * @param {String} message An optional error message. */ exports.return_error = function(res, code, message) { var response = {'code': code}; if (message !== undefined) { response.message = message; } exports.return_json(res, code, response); }; exports.put = function(url, options) { options.headers = options.headers ? options.headers : {}; options.headers['User-Agent'] = version.toString(); options.timeout = 3000; return rest.put(url, options); }; exports.put_file = function(source, url, options) { var stream = fs.createReadStream(source, {'bufferSize': options.bufferSize ? bufferSize : 1024 * 64}); options.data_stream = stream; /* TODO: refactor into a UI thing in restler */ if (options.spinner) { fs.stat(source, function(err, stats) { if (err) { throw err; } var spin = require('util/spinner').percent('Uploading ' + source, stats.size); spin.start(); var l = 0; stream.addListener('data', function(chunk) { l += chunk.length; spin.tick(l); }); stream.addListener('close', function() { spin.end(); }); }); } return exports.put(url, options); }; /** * Issue a GET or POST request to the specified URL. * * @param {Object} client Client object (in most cases, one returned by exports.client function) * @param {String} path Path to append to the remote prefix. * @param {String} method What kind of request to perform (GET / POST / PUT). * @param {Boolean} parse_json true to parse the response as JSON. * @return {*} Response String if parse_json is false, Object otherwise. */ exports.get_response_with_client = function(client, path, method, parse_json, callback) { var data_buffer, data; var callback_called = false; if (!misc.in_array(method, ['GET', 'PUT', 'POST'])) { return callback(new Error(sprintf('Invalid method: %s', method))); } var request = client.request(method, path, client.headers); client.on('error', function(err) { if (callback_called) { return; } callback(err, null); callback_called = true; }); request.on('response', function(response) { data_buffer = []; response.setEncoding('utf-8'); response.on('error', callback); response.on('data', function(chunk) { data_buffer.push(chunk); }); response.on('end', function() { data = data_buffer.join(''); if (parse_json && data.length > 0) { data = JSON.parse(data); } if (callback_called) { return; } callback(null, data); callback_called = true; }); }); request.end(); }; /** * Issue a GET or POST request to the specified URL. * * @param {String} remote name of the remote. * @param {String} path to append to the remote prefix. * @param {String} method What kind of request to perform (GET / POST / PUT). * @param {Boolean} parse_json true to parse the response as JSON. * @return {*} Response String if parse_json is false, Object otherwise. */ exports.get_response = function(remote, path, method, parse_json, callback) { var client = exports.client(remote); return exports.get_response_with_client(client, path, method, parse_json, callback); };
JavaScript
0
@@ -2640,16 +2640,24 @@ request( +'HEAD', '/');%0A%0A
374f5b53c741010f514d2e5d63c16a1540726564
add field state in despatch logging
lib/utils/log.js
lib/utils/log.js
import memoize from 'lodash/memoize'; import isError from 'lodash/isError'; import { error } from './global'; /*eslint-disable no-console*/ const consoleError = window.console && console.error ? (...args) => console.error(...args) : () => {}; //const consoleLog = window.console && console.log ? (...args) => console.log(...args) : () => {}; const consoleWarn = window.console && console.warn ? (...args) => console.warn(...args) : () => {}; //export const logError = (...args) => { // consoleError('ReactFractalField ERROR: ', ...args); // // error.publish(...args); //}; export const logLabeledError = (label, ...args) => { consoleError(`[ReactFractalField ${label}]`, ...args); error.publish(...args); }; export const logWarn = memoize((...args) => { consoleWarn('[ReactFractalField]', ...args); }, (...args) => args.map((arg) => isError(arg) ? arg.message : arg).join(',')); export const logDispatch = (window.console && console.log && console.time && console.group && console.timeEnd && console.groupEnd && process.env.NODE_ENV !== 'production') ? (enabled, store, { type, fieldID, payload }) => { if (!enabled) { return () => {}; } const oldVersion = store.version; const label = `[ReactFractalField] DISPATCH "${type}" (${fieldID}): `; console.time('time'); return () => { const newState = store.getState(); const newVersion = store.version; if (oldVersion !== newVersion) { console.group(label, isError(payload) ? `Error: ${payload.message}` : payload); console.log('state', newState); console.timeEnd('time'); console.groupEnd(label); } else { console.groupCollapsed(label, payload); console.log('state', newState); console.timeEnd('time'); console.groupEnd(label); } }; } : () => () => {}; /*eslint-enable no-console*/
JavaScript
0
@@ -1540,32 +1540,92 @@ te', newState);%0A + console.log('field state', newState.fields%5BfieldID%5D);%0A console.ti @@ -1759,32 +1759,92 @@ te', newState);%0A + console.log('field state', newState.fields%5BfieldID%5D);%0A console.ti
6a8356e15523483da955f82086afbf745a2a1ff1
Update lib/wellknown.js
lib/wellknown.js
lib/wellknown.js
/* * This is a collection of well known SMTP service providers */ module.exports = { "Gmail":{ host: "smtp.gmail.com", secureConnection: true, port: 465, requiresAuth: true }, "Yahoo":{ host: "smtp.mail.yahoo.com", secureConnection: true, port: 465, requiresAuth: true }, "Hotmail":{ host: "smtp.live.com", port: 587, requiresAuth: true }, "hot.ee":{ host: "mail.hot.ee", requiresAuth: true }, "mail.ee":{ host: "smtp.mail.ee", requiresAuth: true }, "SES":{ host: "email-smtp.us-east-1.amazonaws.com", secureConnection: true, port: 465, requiresAuth: true }, "Zoho":{ host: "smtp.zoho.com", secureConnection: true, port: 465, requiresAuth: true }, "iCloud":{ host:"smtp.mail.me.com", port: 587, requiresAuth: true }, "SendGrid":{ host: "smtp.sendgrid.net", port: 587, requiresAuth: true }, "Postmark":{ host: "smtp.postmarkapp.com", port: 25, requiresAuth: true } };
JavaScript
0
@@ -1186,20 +1186,152 @@ sAuth: true%0A + %7D,%0A %22yandex%22:%7B%0A host: %22smtp.yandex.ru%22,%0A port: 465,%0A secureConnection: true,%0A requiresAuth: true%0A %7D%0A%7D;