Ejemplo n.º 1
0
 .then(function(res) {
   return _.chain(res)
     .filter(filterPullRequestMerges)
     .map(extractPullRequestId)
     .value();
 })
    return Promise.all(widgetsPromisesArray).then((modulesArrays) => {
        modulesArrays = _.chain(modulesArrays).flatten().filter().uniq().value();

        return modulesArrays;
    });
Ejemplo n.º 3
0
function uri2Identifier(uri) {
    return _.chain(uri).split('/').compact().join('-').value();
}
Ejemplo n.º 4
0
    sourceFileMappings.forEach(function(sourceFileMapping) {

        var input = sourceFileMapping;
       
        var output = rename(input, "responsive");
        var outputLog = input + ".devices.log";
        
        var outputDevices = [];

        try{

            var stylesheets = split(rework(read(input)).use(moveMedia()));

            write(output, read(input));

            var devicesTemp = _.chain(stylesheets)
                .omit('')
                .keys()
                .map(function(tag){ return { name: tag, groups: groupsOf(tag) }; })
                .map(function(ob){ return _.map(ob.groups, function(group){return { device: group, tagName: ob.name};})})
                .flatten()
                .groupBy(function(group){ return group.device;})
                .mapValues(function(value){ return _.map(value, function(vo){return vo.tagName;})})
                .value();
            

            var devices = _.chain(devicesTemp)
                .transform(function(result, n, key){ result[key] = mergeing(key, devicesTemp) })
                .value();

            write(outputLog, JSON.stringify(devices));
        
            var general = stringify(stylesheets[''], options);
            
            var breakpoints = _.reduce(medias, function(result,n){ 
                                        result[n.device] = n.breakpoint;
                                        return result;
                                    }, {}
                                );

             _.chain(devices)
               .mapValues(function(tags){ return general + mapReduce(tags, stylesheets); })
               .forEach(function(value, key){
                            var deviceOutPut = rename(input, key);
                            var newValue = (["t","m"].indexOf(key) >= 0) ? value.replace(/\(max-width:[\d]+px\)/gi,"(max-width:"+breakpoints[key]+"px)") : value
                            write(deviceOutPut, newValue);
                            console.log(deviceOutPut);
                     }).value();

        } catch (err) {
                         console.log("error:"+err.message);
                         problems.push({
                             message: err.message,
                             severity: "error",
                             source: input
                         });

                    
                         compileDone();
                     }

    });
Ejemplo n.º 5
0
function getNextStop(time, scales) {
  return _.chain(getAllPoints(scales))
    .filter(d => d > time)
    .min()
    .value();
}
 .then(r => vm.measurablesByCategory = _
     .chain(r.data)
     .map(m => Object.assign({}, m, { displayName: truncateMiddle(m.name, 96)}))
     .groupBy('categoryId')
     .value());
Ejemplo n.º 7
0
 return this._listCompleted(config).then(function(completed) {
   var val = _.chain(completed).map(function(value) {
     return value.split('_')[0];
   }).max().value();
   return (val === -Infinity ? 'none' : val);
 });
Ejemplo n.º 8
0
    }, function(err, cells) {
      
      // transformar la hoja Excel en charlas
      var talks = [];
      _.forEach(cells.cells, function(row) {
        //console.log(row);
        var track = getValue(row['16']);
        if (track) {
          var title = getValue(row['1']);
          talks.push({
            'id': title.toLowerCase().trim().replace(/[^ a-zA-Z0-9\-_]+/g, '').replace(/ +/g, '-'),
            'slides': getValue(row['2']),
            'video': getValue(row['3']),
            'interview': getValue(row['4']),
            'author': getValue(row['5']),
            'language': getValue(row['6']),
            'tags': getSplittedValue(row['7']),
            'languages': getSplittedValue(row['8']),
            'slotType': getValue(row['9']),
            'description': getValue(row['10']).replace(/(\n *)+/g, '</p><p>'),
            'avatar': getValue(row['11']),
            'level': getValue(row['12']),
            'bio': getValue(row['13']).replace(/(\n *)+/g, '</p><p>'),
            'title': title,
            //'avatar2': getValue(row['19']), demasiado lío
            'date': getValue(row['15']),
            'track': track,
            'time': getValue(row['17']),
          })
        }
      });

      // sort the talks for the list view
      talks = _.sortBy(talks, function(talk) {
        return talk.date + '-' + talk.time + '-' + talk.track;
      })

      _.each(talks, function(talk) {
        if (talk.avatar) {
          var name = talk.id;
          if (name.length > FILENAME_MAX_SIZE) {
            name.substring(0, FILENAME_MAX_SIZE);
          }
          downloader.download({
            file: {
              url: talk.avatar,
              name: name
            },
            originalFilename: 'src/img/talks/orig/' + name + '{{extension}}',
            processedFilename: 'src/img/talks/processed/' + name + '.png',
            vectorToPng: 'inkscape --export-png="{{originalFilename}}" --export-height=' + AVATAR_SIZE + ' --export-width=' + AVATAR_SIZE + ' "{{processedFilename}}"',
            toPng: 'convert "{{originalFilename}}" -geometry ' + AVATAR_SIZE + 'x' + AVATAR_SIZE + ' "{{processedFilename}}"'
          }); 
          talk.avatar = '/img/talks/processed/' + name + '.png';
        }
      })

      var agendaHtml = _.template(
        '<ul class="row unstyled small-block-grid-1 medium-block-grid-2">' +
          '<% _.forEach(talks, function(talk) { %>' +
            '<li>' +
              '<article class="talk">' +
              '<% if (talk.avatar) { %>' +
                '<img class="th toright" src="{{talk.avatar}}">' +
              '<% } %>' + 
              '<h1>{{talk.title}}</h1>' +
              '<p>{{talk.description}}' +
                '<br><small>' +
                  'Author: {{talk.author}}' +
                  '<br>Tags:' +
                    '<% _.forEach(talk.tags, function(tag) { %>' +
                      ' <span class="radius label">{{tag}}</span>' +
                    '<% }); %>' +
                  '<br>Programming languages:' +
                    '<% _.forEach(talk.languages, function(lang) { %>' +
                      ' <span class="secondary round label">{{lang}}</span>' +
                    '<% }); %>' +
                  '<br>Date: {{talk.date}} at {{talk.time}}' +
                  '<br>Track: {{talk.track}}' +
                  '<br>Level: {{talk.level}}' +
                '</small>' +
              '</p>' +
              '</article>' +
            '</li>' +
          '<% }); %>' +
        '</ul>', {
          talks: _.chain(talks).filter(function(talk) {
            return talk.date == '2014-11-21';
          }).sortBy('title').value()
        }
      );
      // save the HTML with agenda of talks
      console.log("Writing list of talks to src/_includes/talks.html")
      fs.writeFile(
        'src/_includes/talks.html', 
        agendaHtml
      );
      // save the json with the array of talks
      console.log("Writing list of talks to src/js/talks/data.js")
      fs.writeFile(
        'src/js/talks/data.js', 
        '(function() { \'use strict\'; module.exports = ' + JSON.stringify(talks) + ';})()'
      );
      fs.writeFile(
        'src/talks.json', 
        JSON.stringify(talks)
      );
    });
  autoScaling.describeTags(params, function(err, data) {
    if (err) {
      return cb(err);
    }

    var names = _.chain(data.Tags)
                 .filter({ResourceType: 'auto-scaling-group'})
                 .pluck('ResourceId')
                 .value()

    if (names.length === 0) {
      // there is no autoscaling group
      return cb();
    }

    var params = {
      AutoScalingGroupNames: names
    };

    autoScaling.describeAutoScalingGroups(params, function(err, data) {
      if (err) {
        return cb(err);
      }

      data.AutoScalingGroups.forEach(function (autoScalingGroup) {
        var nameTag = _.find(autoScalingGroup.Tags, function(tag) {return tag.Key === 'Name'; });
        var id = nameTag.Value;
        var defName = nameTag.Value.split('-')[0];
        var instances = _.chain(autoScalingGroup.Instances).pluck('InstanceId').map(function(instance) {
          var found = _.find(result.topology.containers, function(cont) {
            return cont.nativeId === instance;
          });

          return found;
        }).without(undefined).value();

        var group = _.chain(instances).map(function(instance) {
          return instance.specific.securityGroups;
        }).flatten().pluck('GroupName').find(function(group) {
          return result.topology.containers[group];
        }).value();

        var elb = _.find(autoScalingGroup.LoadBalancerNames, function(elb) {
          return result.topology.containers[elb];
        });

        // the parent is either the ELB or the Security Group.
        var containedBy = elb || group;

        if (!result.topology.containers[containedBy]) {
          return cb(new Error('parent ' + containedBy + ' missing'));
        }

        // at this point we have already looked up both the security groups
        // and the elbs, so it is safe to assume the parent is there
        result.topology.containers[containedBy].contains.push(id);

        result.containerDefinitions.push({
          name: defName,
          id: id,
          type: 'aws-autoscaling',
          specific: autoScalingGroup
        });

        containers[id] = {
          id: id,
          containedBy: containedBy,
          containerDefinitionId: defName,
          type: 'aws-autoscaling',
          contains: _.pluck(instances, 'id'),
          specific: autoScalingGroup,
          nativeId: autoScalingGroup.AutoScalingGroupName
        };

        instances.forEach(function (container) {
          container.type = 'blank-container';
          container.containedBy = id;
        });
      });

      cb();
    });
  });
Ejemplo n.º 10
0
Board.prototype.filterSquares = function filterSquares(predicate) {
  return _.chain(this.listSquares())
    .select(function(candidate) { return predicate(candidate); })
    .map(function(square) { return square.position; })
    .value();
};
Ejemplo n.º 11
0
      });

      var board;
      if(state.isMyTurn) {
        board = state.shootingBoard;
        board.shots.push(shot);
        if(result.shipWasDestroyed) {
          board.ships.push(new model.Ship({
            id: result.ship.id,
            cells: result.ship.positions.map((position) => {
              return new model.ShipCell({x: position.x, y: position.y})
            })
          }));

          var adjacentCells = BoardUtils.getAdjacentCells(result.ship.positions);
          var adjacentShots = _.chain(adjacentCells)
          .filter((adjacent) => {
            return _.any(board.shots, (takenShot) => {
              return !(takenShot.position.x == adjacent.x && takenShot.position.y == adjacent.y);
            })
          })
          .map((adj) => { return new model.Shot({
            position: {x: adj.x, y: adj.y},
            isHit: false,
            isDestroyed: false,
            isAdjacentToShip: true
          })})
          .value();
          board.shots = board.shots.concat(adjacentShots);
        }
      }
Ejemplo n.º 12
0
 .then(function(results){
   return _.chain(results).sortBy('complexity').reverse().value();
 }),
Ejemplo n.º 13
0
 it( 'should return an empty object for non-object "object" argument values', function() {
   expect( _.chain( null ).pickDeep( [ 'a' ] ).value() ).to.deep.equal( {} );
 });
Ejemplo n.º 14
0
    describe( '_.chain(...).pickDeep', function() {
      var _chainedObj = _.chain( deepObj );

      beforeEach(function() {
        // Assert pre-conditions
        expect( _chainedObj ).to.have.property( 'pickDeep' );
        expect( _chainedObj.pickDeep ).to.be.a( 'function' );
        expect( _chainedObj.pickDeep ).to.not.equal( pickDeep );
      });

      afterEach(function() {
        // Assert post-conditions
        expect( _chainedObj ).to.have.property( 'pickDeep' );
        expect( _chainedObj.pickDeep ).to.be.a( 'function' );
        expect( _chainedObj.pickDeep ).to.not.equal( pickDeep );
      });


      it( 'should return an empty object for non-object "object" argument values', function() {
        expect( _.chain( null ).pickDeep( [ 'a' ] ).value() ).to.deep.equal( {} );
      });

      it( 'should not alter the original object', function() {
        expect( deepObj ).to.deep.equal( clonedDeepObj );
        expect( _chainedObj.value() ).to.deep.equal( clonedDeepObj );
        expect( _chainedObj.pickDeep( [ 'a.b.c' ] ).value() ).to.deep.equal( abcPickedObj );
        expect( _chainedObj.value() ).to.deep.equal( clonedDeepObj );
        expect( deepObj ).to.deep.equal( clonedDeepObj );
      });

      it( 'should allow for no "props" argument', function() {
        expect( _chainedObj.pickDeep().value() ).to.deep.equal( {} );
      });

      it( 'should allow for a single string "props" argument', function() {
        expect( _chainedObj.pickDeep( 'a.b.c' ).value() ).to.deep.equal( abcPickedObj );
      });

      it( 'should allow for multiple string "props..." arguments', function() {
        expect( _chainedObj.pickDeep( 'a.b.c', 'a.b.d', 'a.b.e', 'a.m' ).value() ).to.deep.equal( abcdemPickedObj );
      });

      it( 'should allow for a single array "props" argument containing a single item', function() {
        expect( _chainedObj.pickDeep( [ 'a.b.c' ] ).value() ).to.deep.equal( abcPickedObj );
      });

      it( 'should allow for a single array "props" argument containing multiple items', function() {
        expect( _chainedObj.pickDeep( [ 'a.b.c', 'a.b.d', 'a.b.e', 'a.m' ] ).value() ).to.deep.equal( abcdemPickedObj );
      });

      it( 'should allow for multiple array "props..." arguments, each containing a single item', function() {
        expect( _chainedObj.pickDeep( [ 'a.b.c' ], [ 'a.b.d' ], [ 'a.b.e' ], [ 'a.m' ] ).value() ).to.deep.equal( abcdemPickedObj );
      });

      it( 'should allow for multiple array "props..." arguments, each containing multiple items', function() {
        expect( _chainedObj.pickDeep( [ 'a.b.c', 'a.b.d' ], [ 'a.b.e', 'a.m' ] ).value() ).to.deep.equal( abcdemPickedObj );
      });

      it( 'should allow for a combination of string and array "props..." arguments', function() {
        expect( _chainedObj.pickDeep( 'a.b.c', [ 'a.b.d', 'a.b.e' ], 'a.m' ).value() ).to.deep.equal( abcdemPickedObj );
      });

      it( 'should gracefully ignored unmatched paths in the "props" argument', function() {
        expect( _chainedObj.pickDeep( [ 'x.y.z' ] ).value() ).to.deep.equal( {} );
        expect( _chainedObj.pickDeep( [ 'a.b.c', 'x.y.z' ] ).value() ).to.deep.equal( abcPickedObj );
        expect( _chainedObj.pickDeep( [ 'a.b.c', 'a.b.d', 'a.b.e', 'a.m', 'x.y.z', 'a.q.u.a' ] ).value() ).to.deep.equal( abcdemPickedObj );
      });

    });
Ejemplo n.º 15
0
 .sidefilter((item) => item.isAvailable, (items) => _.chain(items)
     // Transforms the original list (pre-filter)
     // Thus changing only the items in that list that were filtered
     .map((item) => item.purchase())
Ejemplo n.º 16
0
/** @jsx React.DOM */

var React = require('react');
var _ = require('lodash');
require('./DataGrid.css');

var DataGrid = React.createClass({
  render() {
    var data = this.props.data || [[]];
    var max = _.chain(data).flatten().max().value();
    var high = max * 0.75;
    var low = max * 0.25;
    var columnCount = data[0].length;
    var rowCount = data.length;
    var columnHeaders = _.range(columnCount);
    var rows = _.map(data, function(row, index) {
      var cells = _.map(row, function(value, index) {
        var status = value > high ? 'high' : value < low ? 'low' : '';
        return <td className={status} key={index}>{value}</td>;
      });
      return (
        <tr key={index}>
          <td><strong>Row {index + 1}</strong></td>
          {cells}
        </tr>
      );
    });
    var headers = _.map(columnHeaders, function(header, index) {
      return <th key={index}>Column {header + 1}</th>;
    });
    return (
    constructor($element) {
      const byMonth = chain(this.tickets)
        .sortBy('Ticket Created Date')
        .groupBy('date')
        .value()
      const tickets = values(byMonth)
      const last = keys(byMonth).sort().reverse()[0]

      const svg = d3.select($element[0]).append('svg')

      const chart = svg.append('g')
        .classed('chart', true)
        .attr('transform', `translate(${margin.left}, ${margin.top})`)

      let { width, height } = svg.node().getBoundingClientRect()
      width = width - margin.left - margin.right
      height = height - margin.top - margin.bottom

      // x
      forEach(tickets, (tickets) => {
        tickets.last = tickets[0].date === last
        tickets.date = moment(tickets[0].date).endOf('day')
        tickets.x = d3.time.scale()
          .domain([moment(tickets.date).subtract(38, 'days'), tickets.date])
          .range([0, width])
          .clamp(true)
        forEach(tickets, (d, i) => {
          d.x = tickets.x
          d.n = i + 1
        })
      })
      const x = tickets[0][0].x
      const xAxis = d3.svg.axis()
        .scale(x)
        .tickFormat(d => Math.round(moment.duration(d - x.domain()[1]).asDays()))
      chart.append('g')
        .classed('x axis', true)
        .attr('transform', `translate(0, ${height})`)
        .call(xAxis)

      // y
      const y = d3.scale.linear()
        .domain([0, d3.max(map(tickets, 'length'))])
        .range([height, 0])
        .nice()
      const yAxis = d3.svg.axis()
        .scale(y)
        .orient('left')
        .ticks(4)
      chart.append('g')
        .classed('y axis', true)
        .call(yAxis)

      // line
      const line = d3.svg.line()
        .x(d => d.x(d['Ticket Created Date']))
        .y(d => y(d.n))
      const opacity = d3.scale.linear()
        .domain([tickets[0].date, tickets[tickets.length-1].date])
        .range([0.5, 1])

      const lines = chart.selectAll('path.line').data(tickets)
      lines
        .enter().append('path')
          .classed('line', true)
          .attr('opacity', d => opacity(d.date))
          .attr('d', line)

      // label
      chart.selectAll('text.label').data(tickets)
        .enter().append('text')
          .classed('label', true)
          .attr('dx', '3px')
          .attr('dy', '.35em')
          .attr('opacity', d => opacity(d.date))
          .attr('transform', (d) => {
            const last = Math.min(moment(d[d.length-1]['Ticket Created Date']), d.date)
            return `translate(${d.x(last)}, ${y(d.length)})`
          })
          .text(d => `${d[0]['Event Month']} (${d.length})`)

      // voronoi
      const voronoi = d3.geom.voronoi()
        .x(d => d.x(d['Ticket Created Date']))
        .y(d => y(d.n))
      const voronoiGroup = chart.append('g')
        .classed('voronoi', true)
      voronoiGroup.selectAll('path')
        .data(voronoi(flatten(tickets)))
        .enter().append('path')
          .attr('d', d => `M${d.join('L')}Z`)
          .datum(d => d.point)
          .on('mouseover', p => lines.classed('current', d => d.x === p.x))

      chart.on('mouseout', () => lines.classed('current', d => d.last))
      chart.on('mouseout')()
    }
Ejemplo n.º 18
0
function CodeManager(){
	EventEmitter.call(this);
	var self = this,
		codeDomains = _.chain(app.getDomains('code-domain'))
			.sortBy('label')
			.value();

	var $element = $(tmpl({
		domains: codeDomains,
	}));

	var $domainSelect = $element.find('.js-select-domain'),
		$codeList = $element.find('.js-codes');


	$domainSelect.on('change', function(){
		_load();
	});

	$element.find('.scroll-wrapper')
		.css('width', window.innerWidth)
		.css('height', window.innerHeight-(96+44));

	var scroll = new Scroll($element.find('.scroll-wrapper')[0], {
			mouseWheel: true,
			scrollbars: true,
		});

	$codeList.on('click', '.js-item', function(){
		if (_.isEmpty(_currentEntities)) return;

		var $this = $(this),
			$item = $this.closest('.item'),
			_id = $item.data('_id');

		var dialog = new EditExistingDialog({
				domain: self.currentDomain,
				entity: _.find(_currentEntities, function(e){return e._id == _id;}),
			});

		dialog.on('edited', function(data){
			dialog.hide();

			self.entityManager.save(data)
				.then(function(){
					_load();
				})
				.catch(function(err){
					console.error(err);
				});
		});

		dialog.on('closed', function(){
			dialog.remove();
		});

		dialog.show();
	});

	$codeList.on('click', '.js-delete', function(ev){
		ev.stopPropagation();

		if (!window.confirm('Are you sure?')) return;

		var $this = $(this),
			$item = $this.closest('.item'),
			_id = $item.data('_id'),
			_rev = $item.data('_rev');

		self.entityManager.remove({_id: _id, _rev: _rev})
			.then(function(){
				$item.fadeOut(function(){
					$item.remove();
				});
			})
			.catch(function(err){
				console.error(err);
			});
	});

	$element.find('.js-btn-add')
		.click(function(ev){
			ev.preventDefault();

			var createNewDialog = new CreateNewDialog({
					domain: self.currentDomain,
				});
				createNewDialog.zIndex(10001);

			createNewDialog.on('created', function(data){
				createNewDialog.hide();
				modal.show();

				self.entityManager.save(data)
					.then(function(){
						_load();
					})
					.catch(function(err){
						console.error(err);
					});
			});

			createNewDialog.on('closed', function(){
				createNewDialog.remove();
			});

			createNewDialog.show();
		});

	var modal = new Modal({
		title: 'Coded field manager',
		$content: $element,
		hideOkay: true,
	});

	modal.on('closed', function(){
		self.emit('closed');
	});
	
	self.zIndex = function( _newZ ){ 
		modal.modalElement.css('z-index', _newZ);
	};
	self.show = function(){ 
		modal.show();
		_load();
	};

	Object.defineProperty(self, 'currentDomain', {
			get: function(){ 
				if (!$domainSelect) return null;

				var selectedDomainName = $domainSelect.val();
				return _.find(codeDomains, function(d){ return d.name == selectedDomainName; });
			},
		});

	Object.defineProperty(self, 'entityManager', {
			get: function(){ 
				if (!self.currentDomain) return null;

				return self.currentDomain.getService('entity-manager');
			},
		});

	Object.defineProperty(self, 'descriptionManager', {
			get: function(){ 
				if (!self.currentDomain) return null;

				return self.currentDomain.getService('description-manager');
			},
		});

	function _createListItemElement(viewModel){
		return listItemTemplate(viewModel);
	}

	var _currentEntities;
	function _load(){
		$codeList.empty()
			.append('Loading...');

		return self.entityManager.getAll()
			.then(function(entities){
				$codeList.empty();

				if (_.isEmpty(entities)){
					$codeList.append('There are no ' + self.currentDomain.label.toLowerCase() + ' codes.');
				}

				_currentEntities = entities;

				_.chain(entities)
					.map(function(entity){
						return {
								_id: entity._id,
								_rev: entity._rev,
								label: self.descriptionManager.getShortDescription(entity),
							};
					})
					.sortBy('label')
					.map(_createListItemElement)
					.value()
					.forEach(function(el){
						$codeList.append(el);
					});

				setTimeout(function(){
					scroll.refresh();
				},100);
			})
			.done();
	}
}
Ejemplo n.º 19
0
function cards(hand) {
    return _.chain(hand)
        .chunk(2)
        .map(chunk => chunk.join(''))
        .value();
}
Ejemplo n.º 20
0
      }
    }
  },

  getDefaultProps() {
    return {
      members: []
    }
  },

  setDescription(ev, value) {
    this.setState({ description: value })
  },

  setAssignedTo(value, member) {
    let memberName = _.chain(member).pluck('label').first().value()

    this.setState({
      assigned_to: value,
      assigneeName: memberName
    })
  },

  updateTags(tags) {
    this.setState({ tags })
  },

  changeType(type) {
    var descriptionTemplate = (type === 'defect') ? IssueTemplates.defect : ''
    this.setDescription(null, descriptionTemplate)
Ejemplo n.º 21
0
 function mapReduce(tags, stylesheets){
     return _.chain(tags)
         .map(function(tag){ return ' @media ' + tag + '{' + stringify(stylesheets[tag], options) + '}'; })
         .reduce(function(left, right){return left + right;})
         .value();
 }
Ejemplo n.º 22
0
const Repo = require('./lib/repo')
const requireDir = require('require-dir')
const path = require('path')
const chain = require('lodash').chain
const repoObject = requireDir(path.join(__dirname, '/repos'))

module.exports = chain(Object.keys(repoObject))
  .map(basename => {
    const repoData = repoObject[basename]
    repoData.filename = `${basename}.json`
    return new Repo(repoData)
  })
  .filter(repo => repo.valid)
  .uniqBy('fullName')
  .sort((a, b) => b.forksCount - a.forksCount)
  .value()
Ejemplo n.º 23
0
// Gets all the domain ends/starts that occur in a list of scales.
function getAllPoints(scales) {
  return _.chain(scales)
    .map(d => d.domain)
    .flatten()
    .value();
}
Ejemplo n.º 24
0
		inject: 'body'
	}
	, "search": {
		title: 'Search',
		template: path.join(PAGES, 'search.ejs'),
		js: path.join(PAGES, 'search.js'),
		css: path.join(PAGES, 'search.css'),
		filename: "search.html",
		entries: [
			COMMON_JS_CHUNK_NAME
		],
		inject: 'body'
	}
};

_.chain(pages)
	.each((page = {}, pageName = "")=> {
		if (page.js) config.entry[pageName] = page.js;
		if (page.template) {
			let entries = _.concat(page.entries||[], [pageName]);
			let params = _.chain(page)
				.omit(['js', 'css'])
				.extend({
					entries: entries,
					chunks: entries,
					chunksSortMode: 'none',
				})
				.value();
			config.plugins.push(
				new HtmlWebpackPlugin(params)
			);
Ejemplo n.º 25
0
function getDomainStart(scales) {
  return _.chain(getAllPoints(scales))
    .min()
    .value();
}
Ejemplo n.º 26
0
        baseRoom.items.forEach((room, i) => {
            let itemPath = path.join(dir, i.toString());
            fs.ensureDirSync(itemPath);

            if (!room.hasFiles) {
                buildRooms(room, itemPath, depth, attachments);
            } else {
                const roomsFiles = room.parsedFiles.map(file => {
                    file.destination = path.join(itemPath, 'files', file.parse.base);
                    file.content = fs.readFileSync(file.file, 'utf8');
                    file.mode = file.parse.ext.replace('.', '');
                    fs.copySync(file.file, file.destination);
                    return file;
                });

                // room attachments
                attachments = _.chain(attachments)
                    .clone()
                    .concat(room.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file))))
                    .uniq()
                    .value();

                const css_paths = _.chain(attachments)
                    .concat(roomsFiles.map(file => path.relative(targetDir, file.destination)))
                    .filter(file => _.endsWith(file, '.css'))
                    .map(file => normalizePath(file, false))
                    .value();

                const js_paths = _.chain(attachments)
                    .concat(roomsFiles.map(file => path.relative(targetDir, file.destination)))
                    .filter(file => _.endsWith(file, '.js'))
                    .map(file => normalizePath(file, false))
                    .value();

                // iframe.html
                fs.writeFileSync(
                    path.join(itemPath, 'iframe.html'),
                    handlebars.compile(iframe)({
                        depth,
                        css_paths,
                        js_paths,
                        html: roomsFiles[0],
                    })
                );

                // index.html
                fs.writeFileSync(
                    path.join(itemPath, 'index.html'),
                    handlebars.compile(index)({
                        depth,
                        roomsFiles,
                        settings,
                        root,
                        room,
                        css_paths,
                        js_paths,
                        hasCSS: css_paths.length > 0,
                        hasJS: js_paths.length > 0,
                    })
                );
            }
        });
Ejemplo n.º 27
0
  grunt.registerMultiTask('swigstatic', 'generate from templates', function() {
    var options = this.options({
      cache: false,
      autoEscape: true,
      varControls: ['{{', '}}'],
      tagControls: ['{%', '%}'],
      cmtControls: ['{#', '#}'],
      context:{},
      contents:''
    });
    var locals = _.chain({})
                  .merge(contextResult(options.context))
                  .merge(contextResult(this.data.context))
                  .value();
    swig.setDefaults({
      cache: options.cache,
      locals: locals,
      autoescape: options.autoEscape,
      varControls: options.varControls,
      tagControls: options.tagControls,
      cmtControls: options.cmtControls
    });
    handleFiles(this.files);
    if(options.contents){
      generateContent(options.contents,this.data.files[0].dest)
    }
    function generateContent(root,destDir){
      var layouts = grunt.file.expand({filter:'isFile'},path.join(root,'./*.html'))

      layouts.forEach(function(i){
        var moduleName = path.basename(i,'.html')
          , markdownFiles = grunt.file.expand({filter:'isFile'},path.join(root,moduleName,'./*.{md,markdown}'))
        markdownFiles.forEach(function(filepath){
          var content;
          try{
            content = grunt.file.read(filepath)
          }catch(err){
            content = ''
            grunt.log.warn('Source file "' + filepath + '" not created.');
          }
          var result = md2html.toHTMLTree(content,'Maruku')
          var refs = {}
          if(result&&result[1]){
            refs = result[1]
          }
          var relativePath = filepath.replace(root,'./').replace(/\.(md|markdown)/,'.html')
          var relativeDir = path.dirname(relativePath)
          grunt.file.expand([path.join(root,relativeDir,'./*'),'!'+path.join(root,relativeDir,'./*.{md,markdown}')]).forEach(function(otherPath){
            grunt.file.copy(otherPath,path.join(destDir,otherPath.replace(root,'./')))
          });
          renderFile(path.join(destDir,relativePath), i, _.assign({},refs,{
            markdown:function(){
              return md2html.renderJsonML(result)
            }
          }));
        })
      })
    }

    function contextResult(ctx){
      var context = {}
      if(_.isPlainObject(ctx)){
        return ctx
      }else if(_.isString(ctx)){
        try{
          context = grunt.file.readJSON(ctx)
        }catch(err){
          grunt.fail.fatal(err)
        }
      }else{
        grunt.log.warn(this.nameArgs + '\'s context is not found.');
      }
      return context
    }
    function handleFiles(files) {
      files.forEach(function(f) {
        f.src.filter(srcExists).forEach(function(filepath) {
          var context
            , contextPathJSON = filepath.substring(0,filepath.lastIndexOf('.'))+'.json'
            , contextPathJs = filepath.substring(0,filepath.lastIndexOf('.'))+'.js';
          try{
            context = grunt.file.readJSON(contextPathJSON)
          }catch(err){
            context = {}
            try{
              context = require(contextPathJs)
            }catch(err){
              context = {}
            }
            // grunt.log.warn('Source file "' + contextPathJSON + '" not found.');
          }
          renderFile(f.dest, filepath, context);
        });
      });
    };

    function srcExists(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    };
    function renderFile(outfile, filepath, context) {
      grunt.file.write(outfile, swig.renderFile(filepath, context));
      grunt.log.ok('File "' + outfile + '" created.');
    }
  });
Ejemplo n.º 28
0
var _ = require('lodash');


var storeItems = [];
var me = {};


let purchased = (_.chain(storeItems)
    // Only Grab favourites
    .filter((item) => item.isFavorite)

    // Also we dont want the tools
    .reject((item) => item.category === 'tool')

    // Grab first item with the best quality of each
    .sortBy('quality')
    .groupBy('color_id')
    .map((group) => group[0])

    // Now purchase them
    .sidechain((items) => (_.chain(items)
        // The ones we can't purchase, put out an order instead
        .filter((item) => ! item.isAvailable)
        .map((item) => item.request())

        // Print the receipt for ones we could request
        .filter((purchase) => ! purchase.has_failed)
        .each((purchase) => me.print_reciept(purchase))
    ))
    .filter((item) => item.isAvailable)
    .map((item) => me.purchase(item))
module.exports = function (templateDirectories, outputFile, options) {
    options || (options = {});

    var internalNamespace = 'templatizer';

    _.defaults(options, {
        dontTransformMixins: false,
        dontRemoveMixins: false,
        amdDependencies: [],
        inlineJadeRuntime: true,
        jade: {},
        namespace: '' // No namespace means 'window'
    });

    if (typeof templateDirectories === "string") {
        templateDirectories = glob.sync(templateDirectories);
    }

    var amdModuleDependencies = '';
    var amdDependencies = '';

    if(_.isArray(options.amdDependencies) && !_.isEmpty(options.amdDependencies)) {
    	amdModuleDependencies = "'" + options.amdDependencies.join("','") + "'";
    	amdDependencies = options.amdDependencies.toString();
    } 

    var namespace = _.isString(options.namespace) ? options.namespace : '';
    var folders = [];
    var templates = [];
    var _readTemplates = [];
    var isWindows = process.platform === 'win32';
    var pathSep = path.sep || (isWindows ? '\\' : '/');
    var pathSepRegExp = /\/|\\/g;

    // Split our namespace on '.' and use bracket syntax
    if (namespace) {
        namespace = bracketedName(namespace.split('.'));
    }

    // Find jade runtime and create minified code
    // where it is assigned to the variable jade
    var placesToLook = [
        __dirname + '/node_modules/jade/lib/runtime.js',
        __dirname + '/jaderuntime.js'
    ];
    var jadeRuntime = fs.readFileSync(_.find(placesToLook, fs.existsSync)).toString();
    var wrappedJade = uglifyjs.minify('var jade = (function(){var exports={};' + jadeRuntime + 'return exports;})();', {fromString: true}).code;

    var outputTemplate = fs.readFileSync(__dirname + '/output_template.js').toString();
    var output = '';

    var jadeCompileOptions = {
        client: true,
        compileDebug: false,
        pretty: false
    };
    _.extend(jadeCompileOptions, options.jade);

    templateDirectories = _.chain(templateDirectories)
   .map(function (templateDirectory) {
        if(path.extname(templateDirectory).length > 1) {
            // Remove filename and ext
            return path.dirname(templateDirectory).replace(pathSepRegExp, pathSep);
        }
        return templateDirectory.replace(pathSepRegExp, pathSep);
    })
   .uniq()
   .each(function (templateDirectory) {
        if (!fs.existsSync(templateDirectory)) {
            throw new Error('Template directory ' + templateDirectory + ' does not exist.');
        }

        walkdir.sync(templateDirectory).forEach(function (file) {
            var item = file.replace(path.resolve(templateDirectory), '').slice(1);
            // Skip hidden files
            if (item.charAt(0) === '.' || item.indexOf(pathSep + '.') !== -1) {
              return;
            }
            if (path.extname(item) === '' && path.basename(item).charAt(0) !== '.') {
                if (folders.indexOf(item) === -1) folders.push(item);
            } else if (path.extname(item) === '.jade') {
                // Throw an err if we are about to override a template
                if (_readTemplates.indexOf(item) > -1) {
                    throw new Error(item + ' from ' + templateDirectory + pathSep + item + ' already exists in ' + templates[_readTemplates.indexOf(item)]);
                }
                _readTemplates.push(item);
                templates.push(templateDirectory + pathSep + item);
            }
        });
    })
   .value();

   folders = _.sortBy(folders, function (folder) {
       var arr = folder.split(pathSep);
       return arr.length;
   });

    output += folders.map(function (folder) {
        return internalNamespace + bracketedName(folder.split(pathSep)) + ' = {};';
    }).join('\n') + '\n';

    templates.forEach(function (item) {
        var name = path.basename(item, '.jade');
        var dirString = function () {
            var itemTemplateDir = _.find(templateDirectories, function (templateDirectory) {
                return item.indexOf(templateDirectory + pathSep) === 0;
            });
            var dirname = path.dirname(item).replace(itemTemplateDir, '');
            if (dirname === '.') return name;
            dirname += '.' + name;
            return dirname.substring(1).replace(pathSepRegExp, '.');
        }();

        if (options.dontRemoveMixins) {
            jadeCompileOptions.compiler = DynamicMixinsCompiler;
        }

        jadeCompileOptions.filename = item;
        var template = beautify(jade.compileClient(fs.readFileSync(item, 'utf-8'), jadeCompileOptions).toString());

        template = renameJadeFn(template, dirString);
        template = simplifyTemplate(template);

        var mixins = [];
        if (!options.dontTransformMixins) {
            var astResult = transformMixins({
                template: template,
                name: name,
                dir: dirString,
                rootName: internalNamespace
            });
            mixins = astResult.mixins;
            template = astResult.template;
        }

        output += namedTemplateFn({
            dir: dirString,
            rootName: internalNamespace,
            fn: template
        });

        output += mixins.join('\n');
    });

    if(!options.inlineJadeRuntime)
    	wrappedJade = '';
    
    var indentOutput = output.split('\n').map(function (l) { return l ? '    ' + l : l; }).join('\n');
    var finalOutput = outputTemplate
        .replace(/\{\{namespace\}\}/g, namespace)
        .replace(/\{\{internalNamespace\}\}/g, internalNamespace)
        .replace('{{jade}}', wrappedJade)
        .replace('{{code}}', indentOutput)
        .replace('{{amdModuleDependencies}}', amdModuleDependencies)
        .replace('{{amdDependencies}}', amdDependencies);

    if (outputFile) fs.writeFileSync(outputFile, finalOutput);

    return finalOutput;
};
Ejemplo n.º 30
0
module.exports = function (app) {
  app.insight.track('yoyo', 'clearGlobalConfig');

  var defaultChoices = [
    {
      name: 'Take me back home, Yo!',
      value: 'home'
    }
  ];

  var generatorList = _.chain(globalConfig.getAll()).map(function (val, key) {
    var prettyName = '';
    var sort = 0;

    // Remove version from generator name
    var name = key.split(':')[0];
    var generator = app.generators[name];

    if (generator) {
      prettyName = generator.prettyName;
      sort = -app.conf.get('generatorRunCount')[namespaceToName(generator.namespace)] || 0;
    } else {
      prettyName = name.replace(/^generator-/, '') + chalk.red(' (not installed anymore)');
      sort = 0;
    }

    return {
      name: prettyName,
      sort: sort,
      value: key
    };
  }).compact().sortBy(function (generatorName) {
    return generatorName.sort;
  }).value();

  if (generatorList.length > 0) {
    generatorList.push(new inquirer.Separator());
    defaultChoices.unshift({
      name: 'Clear all',
      value: '*'
    });
  }

  inquirer.prompt([{
    name: 'whatNext',
    type: 'list',
    message: 'Which store would you like to clear?',
    choices: _.flatten([
      generatorList,
      defaultChoices
    ])
  }], function (answer) {
    app.insight.track('yoyo', 'clearGlobalConfig', answer);

    if (answer.whatNext === 'home') {
      app.navigate('home');
      return;
    }

    _clearGeneratorConfig(app, answer.whatNext);
  });
};