text:
var FlyBy = FlyBy || {};

//begin private closure
(function() {
    'use strict';

    this.Engine = famous.core.Engine;
    this.Modifier = famous.core.Modifier;
    this.Transform = famous.core.Transform;
    this.Surface = famous.core.Surface;
    this.Lightbox = famous.views.Lightbox;

    // Set up the main container
    this.context = FlyBy.Engine.createContext();
    this.context.setPerspective(1000);
    this.context.add(new this.Surface({
        size: [undefined, undefined],
        properties: {
            backgroundColor: "#333",
            zIndex: -10
        }
    }))

    this.Page = function Page() {
        var page = this;
        // If the user is NOT using the 'new' keyword
        if (!(page instanceof Page)) {
            return new Page();
        }

        page.view = new FlyBy.Lightbox();
        page.view.resetOptions = function(){
          this.setOptions(Lightbox.DEFAULT_OPTIONS);
        }

        page.routeTo = function(){
          FlyBy.context.add(page.view);
        }
    }
}).call(FlyBy);


text:
const DrawCard = require('../../drawcard.js');

class ADragonIsNoSlave extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Give -2 STR',
            phase: 'challenge',
            target: {
                cardCondition: card => card.location === 'play area' && card.getType() === 'character' && card.attachments.length === 0,
                gameAction: 'decreaseStrength'
            },
            handler: context => {
                this.untilEndOfPhase(ability => ({
                    match: context.target,
                    effect: ability.effects.modifyStrength(-2)
                }));

                this.game.addMessage('{0} uses {1} to give {2} -2 STR until the end of the phase',
                    this.controller, this, context.target);
            }
        });

        this.reaction({
            location: 'discard pile',
            when: {
                afterChallenge: event => event.challenge.winner === this.controller && this.hasParticipatingDragonOrDany()
            },
            ignoreEventCosts: true,
            cost: ability.costs.payGold(1),
            handler: () => {
                this.game.addMessage('{0} pays 1 gold to move {1} back to their hand', this.controller, this);
                this.controller.moveCard(this, 'hand');
            }
        });
    }

    hasParticipatingDragonOrDany() {
        let cards = this.controller.filterCardsInPlay(card => {
            return (card.isParticipating() &&
                    (card.hasTrait('Dragon') || card.name === 'Daenerys Targaryen') &&
                    card.getType() === 'character');
        });

        return cards.length >= 1;
    }
}

ADragonIsNoSlave.code = '06034';

module.exports = ADragonIsNoSlave;

redpajama_set_name: RedPajamaGithub


text:
var tempName;
var testG;
function addTableRow(name, typeF) {
    var tableRef = document.getElementById('layerTable').getElementsByTagName('tbody')[0];
    var newRow   = tableRef.insertRow(tableRef.rows.length);

    var temp=0;
    for (var i=0; i<mapLayers.length; i++) {
        if (mapLayers[i].name == name) {
            temp = i;
        }
    }
    var isTemp = mapLayers[temp].isTemp;
    var hasQueryText = mapLayers[temp].query;
    var hasEndpoint = mapLayers[temp].endpoint;
    var hasURI = mapLayers[temp].uri;

    //Create Show/Hide checkbox
    var newCell  = newRow.insertCell(0);
    var element = document.createElement("input");
    element.type = "checkbox";
    element.checked = true;
    element.id = "shBox" + name;
    element.onclick = function () {
        var box = document.getElementById("shBox"+name);
	    var temp = null;
		map.getLayers().forEach(function(layer) {
	    	if (layer.get('title') == name) {
	    		temp = layer;
	    	}
	    });

	    if (box.checked) {
	        temp.setVisible(true);
	    }
	    else{
	        temp.setVisible(false);
	    }

    };
    newCell.appendChild(element);
    /*if (hasURI == 'null'){
    	element.disabled = true;
    }*/

    //Add Layer Name
    newCell  = newRow.insertCell(1);
    var layerName  = document.createTextNode(name);
    newCell.appendChild(layerName);

    ////////////////////////////////////////////////////////
    //Create function buttons
    newCell  = newRow.insertCell(2);
    var groupButtons = document.createElement("div");
    groupButtons.setAttribute("id", "buttonsG");
    groupButtons.setAttribute("class", "btn-group btn-group-sm");
    groupButtons.setAttribute("role", "group");
    groupButtons.setAttribute("aria-label", "...");

    //Zoom
    element = document.createElement("button");
    element.type = "button";
    element.title = "Zoom to layer";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.onclick = function () {
        map.getLayers().forEach(function(layer) {
        	if (layer.get('title') == name) {
        		switch(typeF) {
	        		case 'kml':
	        			map.getView().fit(layer.getSource().getSource().getExtent(), map.getSize());
	        			break;
	        		case 'json':
	        			map.getView().fit(layer.getSource().getSource().getExtent(), map.getSize());
	        			break;
	        		case 'geojson':
	        			map.getView().fit(layer.getSource().getSource().getExtent(), map.getSize());
	        			break;
	        		case 'topojson':
	        			map.getView().fit(layer.getSource().getSource().getExtent(), map.getSize());
	        			break;
	        		case 'geotiff':
	        			var parse = mapLayers[temp].imageBbox.split(',');
	        			var extent = [Number(parse[2]), Number(parse[3]), Number(parse[4]), Number(parse[5])];
	        			map.getView().fit(extent, map.getSize());
	        			break;
	        		case 'wms':
	        			map.getView().fit(mapLayers[temp].imageBbox, map.getSize());
	        			break;
	        		case 'changeset':
	        			map.getView().fit(layer.getSource().getSource().getExtent(), map.getSize());
	        			break;
        		}
        	}
        });
    };
	groupButtons.appendChild(element);
    /*if (hasURI == 'null'){
    	element.disabled = true;
    }*/

    //Layer info button
    element = document.createElement("button");
    element.type = "button";
    element.title = "Layer information";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.setAttribute("data-toggle", "modal");
    element.setAttribute("data-target", "#layerInformationModal");
    element.onclick = function () {
    	var layerPosition = -1;
    	for (var i=0; i<mapLayers.length; i++) {
            if (mapLayers[i].name == name) {
            	layerPosition = i;
            	break;
            }
        }
    	document.getElementById('infoLayerName').innerHTML = mapLayers[layerPosition].name;
    	document.getElementById('infoLayerURI').innerHTML = mapLayers[layerPosition].uri;
    	document.getElementById('infoLayerIsTemp').innerHTML = mapLayers[layerPosition].isTemp;
    	document.getElementById('infoLayerType').innerHTML = mapLayers[layerPosition].type;
    	if (mapLayers[layerPosition].query != "") {
    		document.getElementById('infoLayerQueryDD').style.display = 'block';
    		document.getElementById('infoLayerQuery').value = mapLayers[layerPosition].query;
    	}
    	else {
    		document.getElementById('infoLayerQueryDD').style.display = 'none';
    	}
    	document.getElementById('infoLayerEndpoint').innerHTML = mapLayers[layerPosition].endpoint;
    	document.getElementById('infoLayerFillColor').innerHTML = mapLayers[layerPosition].fillColor;
    	document.getElementById('infoLayerStrokeColor').innerHTML = mapLayers[layerPosition].strokeColor;
    	document.getElementById('infoLayerIconURL').innerHTML = mapLayers[layerPosition].icon;
    	document.getElementById('infoLayerIconSize').innerHTML = mapLayers[layerPosition].iconSize;
    	if (mapLayers[layerPosition].mapId != 0) {
    		document.getElementById('infoLayerMapId').innerHTML = mapLayers[layerPosition].mapId;
    	}
    	else {
    		document.getElementById('infoLayerMapId').innerHTML = null;
    	}
    };
    groupButtons.appendChild(element);
    /*if (typeF === "user") {
    	element.disabled = true;
    }*/

    //Edit query - Temporal WMS
    if (typeF.substring(0,3) == "wms" && isTemp) {
    	//Temporal WMS interface
    	element = document.createElement("button");
	    element.type = "button";
	    element.title = "Update WMS TIME";
	    element.innerHTML = '';
	    element.setAttribute("class", "btn btn-xs btn-default");
	    element.onclick = function () {
	    	//Add functionality
	    	var timeStampWMS = mapLayers[temp].type.split(',')[3];
	    	document.getElementById('WMSid').innerHTML = 'WMS layer: '+name;
	    	document.getElementById('currentTimeWMS').innerHTML = 'TIME: '+timeStampWMS;
	    	document.getElementById('timePanelWMS').style.display = 'block';

	    	if (animateTimeline == 1) {
		    	animateTimePanel();
	    	}
	    	if (animateStats == 1) {
		    	animateStatsPanel();
	    	}

	    	tempName = name;
	    };
    }
	else {
		//Update query interface
		element = document.createElement("button");
	    element.type = "button";
	    element.title = "View/Edit query";
	    element.innerHTML = '';
	    element.setAttribute("class", "btn btn-xs btn-default");
	    element.setAttribute("data-toggle", "modal");
	    element.setAttribute("data-target", "#modalUpdateQuery");
	    element.onclick = function () {
	    	//Add functionality
	    	document.getElementById('endpointUrlQueryUpdate').value = hasEndpoint;
	    	document.getElementById('textQueryUpdate').value = hasQueryText;
	    	document.getElementById('layerNameQueryUpdate').value = name;
	    	if (isTemp) {
	    		document.getElementById('isTemporalQueryUpdate').checked = true;
	    	}
	    	else {
	    		document.getElementById('isTemporalQueryUpdate').checked = false;
	    	}
	    	tempName = name;
	    };
	}
    groupButtons.appendChild(element);
    if (hasQueryText == null || hasQueryText == '') {
    	element.disabled = true;
    }
    if (typeF.substring(0,3) == "wms" && isTemp) {
    	element.disabled = false;
    }

    //Global Styles
    element = document.createElement("button");
    element.type = "button";
    element.title = "Change global style";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.setAttribute("data-toggle", "modal");
    element.setAttribute("data-target", "#stylesKMLmodal");
    element.onclick = function (position) {
    	var position=0;
        var table = document.getElementById('layerTable');
        for (var i=0; i<table.rows.length; i++) {
            if (table.rows[i].cells[1].innerHTML == name) {
                position = i;
            }
        }
        showStylesForm(position);
    };
    groupButtons.appendChild(element);
    if ( !((typeF == "kml") || (typeF == "gml") || (typeF == "geojson") || (typeF == "topojson") || (typeF == "changeset")) ) {
    	element.disabled = true;
    }

    //Feature Styles
    element = document.createElement("button");
    element.type = "button";
    element.title = "Change a feature's style";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.setAttribute("data-toggle", "modal");
    element.setAttribute("data-target", "#stylesFeatureModal");
    element.onclick = function (position) {
    	var position=0;
        var table = document.getElementById('layerTable');
        for (var i=0; i<table.rows.length; i++) {
            if (table.rows[i].cells[1].innerHTML == name) {
                position = i;
            }
        }
        showStylesForm(position);
        createModalBody(mapLayers[position].features);
    };
    groupButtons.appendChild(element);
    if ( !((typeF === "kml") || (typeF === "gml") || (typeF === "geojson") || (typeF === "topojson")) ) {
    	element.disabled = true;
    }

    //Filter
    element = document.createElement("button");
    element.type = "button";
    element.title = "Spatial filter";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.onclick = function () {
        setFilters(name);
    };
    groupButtons.appendChild(element);
    if ( !((typeF === "kml") || (typeF === "gml") || (typeF === "geojson") || (typeF === "topojson") || (typeF == "changeset")) ) {
    	element.disabled = true;
    }

    //Z-Buffer(move on top)
    element = document.createElement("button");
    element.type = "button";
    element.title = "Move layer on top in map view";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.onclick = function () {
        map.getLayers().forEach(function(layer) {
        	if (layer.get('title') == name) {
                layer.setZIndex(1);
        	}
        	else {
        		layer.setZIndex(0);
        	}
        });
        featureOverlay.setZIndex(5);
    };
    groupButtons.appendChild(element);
    /*if (hasURI == 'null') {
    	element.disabled = true;
    }*/

    //Download file (HTML5: Works in Firefox, Chrome, Android, Crome for Android)
    element = document.createElement("button");
    element.type = "button";
    element.id = 'downloadLayerButton'+name;
    element.title = "Download layer";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-xs btn-default");
    element.onclick = function () {
    	var layerPosition = -1;
    	for (var i=0; i<mapLayers.length; i++) {
            if (mapLayers[i].name == name) {
            	layerPosition = i;
            	break;
            }
        }

        var file = document.createElement('a');
        file.href = mapLayers[layerPosition].uri;
        switch (mapLayers[layerPosition].type) {
        	case 'kml':
        		file.download = mapLayers[layerPosition].name + '.kml';
        		break;
        	case 'gml':
        		file.download = mapLayers[layerPosition].name + '.gml';
        		break;
        	case 'geojson':
        		file.download = mapLayers[layerPosition].name + '.geojson';
        		break;
        	case 'topojson':
        		file.download = mapLayers[layerPosition].name + '.json';
        		break;
        	default:
        		file.download = mapLayers[layerPosition].name;
        }
        file.click();
    };
    groupButtons.appendChild(element);
    if (typeF.substring(0,3) == "wms" || hasURI == 'dragAndDrop') {
    	element.disabled = true;
    }

    //Delete
    element = document.createElement("button");
    element.type = "button";
    element.title = "Delete layer";
    element.innerHTML = '';
    element.setAttribute("class", "btn btn-danger btn-xs");
    element.setAttribute("data-toggle", "modal");
    element.setAttribute("data-target", "#confirmDelete");
    element.onclick = function () {
        tempName = name;
    };
    groupButtons.appendChild(element);

    newCell.appendChild(groupButtons);
}
////////////////////////////

/**
 * Delete a layer after the user confirms it
 */
function deleteFinal() {
    var tableRef = document.getElementById('layerTable').getElementsByTagName('tbody')[0];

    //Remove row from table
    var position=0;
    var table = document.getElementById('layerTable');
    for (var i=0; i<table.rows.length; i++) {
        if (table.rows[i].cells[1].innerHTML == tempName) {
            position = i;
        }
    }

    document.getElementById('alertMsgDelLayer').style.display = 'block';
    setTimeout(function() {$('#alertMsgDelLayer').fadeOut('slow');}, fadeTime);

    deleteLayer(tableRef, position, mapLayers[position].isTemp, tempName);
}

/**
 * Delete Layer from map
 */
function deleteLayer(tableRef, position, isTemp, name) {
	//Renew tables
    tableRef.deleteRow(position);

	//Delete the layer from the map
	map.getLayers().forEach(function(layer) {
    	if (layer.get('title') == name) {
    		map.removeLayer(layer);
    	}
    });

	//Delete the layer's tabs from color panel
	removeFromColorPanel(name, position);

    mapLayers.splice(position, 1);

    //If the layer is temporal delete the features from the temporalFeatures table
    if (isTemp) {
    	for (var i=0; i<temporalFeatures.length; i++) {
    		if (temporalFeatures[i].layerName == name) {
    			temporalFeatures[i].dirty = true;
    		}
    	}
    	deleteTimelineEvents(name);
    }

    //Show renewed last modification date and number of layers
    document.getElementById('infoNumOfLayers').innerHTML = mapLayers.length;

    resetStatsInfo(name);

    //CLose popup and clear selected features
    mapSelectInterraction.getFeatures().clear();
    clearPopup();
}


text:
if command -v docker &>/dev/null; then
    alias dstopall='sudo docker stop $(sudo docker ps -aq)'
    alias dprunevol='sudo docker volume prune'
    alias dprunesys='sudo docker system prune -a'
    alias ddelimages='sudo docker rmi $(docker images -q)'
    alias derase='dstopcont ; drmcont ; ddelimages ; dvolprune ; dsysprune'
    alias dprune='ddelimages ; dprunevol ; dprunesys'
    alias dps='sudo docker ps -a'
    alias dpss='sudo docker ps -a --format "table {{.Names}}\t{{.State}}\t{{.Status}}\t{{.Image}}" | (sed -u 1q; sort)'
    alias ddf='sudo docker system df'
    alias dlogs='sudo docker logs -tf --tail="50" '
    alias dexec='sudo docker exec -ti'
    alias dips="sudo docker ps -q | xargs -n 1 docker inspect --format '{{json .}}' | jq -rs 'map(.Name,.NetworkSettings.Networks[].IPAddress) | .[]'"
    dip() {
        sudo docker inspect --format '{{json .}}' "$1" | jq -rs 'map(.NetworkSettings.Networks[].IPAddress) | .[]'
    }
fi


text:
//
//  VTSecondViewController.m
//  VerticalTransition
//
//  Created by yuko fujii on 2014/05/14.
//  Copyright (c) 2014年 yucha. All rights reserved.
//

#import "VTSecondViewController.h"

@interface VTSecondViewController ()

@end

@implementation VTSecondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)back:(id)sender {
    [self performSegueWithIdentifier:@"returnHome" sender:self];
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"returnHome"]){
        CATransition* transition = [CATransition animation];
        transition.type = kCATransitionPush;
        transition.subtype = kCATransitionFromBottom;
        transition.duration = 2.0f;
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
const messages = require('../../lib/messages');
const mongoose = require('mongoose');
const Layer = mongoose.model('Layer');
const Content = mongoose.model('Content');
const User = mongoose.model('User');
const _ = require('underscore');
const async = require('async');

/**
 * Load
 */
exports.load = function (req, res, next, id) {
  Layer.load(id, function (err, layer) {
    if (err) {
      return res.json(400, messages.error(req.i18n.t('layer.load.error')));
    } else if (!layer) {
      return res.json(400, messages.error(req.i18n.t('layer.load.not_found')));
    } else {
      req.layer = layer;
      next();
    }
  });
};

/**
 * List
 */

exports.index = function (req, res) {
  const options = {
    perPage: req.perPage,
    page: req.page,
    criteria: { visibility: 'Visible' }
  };

  if (req.isAuthenticated() && req.user.role === 'admin') {
    delete options.criteria;
  }

  // get visible layers for a user
  if (req.param('userId')) {
    options.criteria = {
      $and: [{ creator: req.param('userId') }, { visibility: 'Visible' }]
    };
  }

  if (req.param('search')) {
    options.criteria = {
      $and: [
        options.criteria,
        { title: { $regex: req.param('search'), $options: 'i' } }
      ]
    };
  }

  Layer.list(options, function (err, layers) {
    if (err) {
      return res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
    }
    Layer.count(options.criteria).exec(function (err, count) {
      if (!err) {
        res.json({ options: options, layersTotal: count, layers: layers });
      } else {
        res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
      }
    });
  });
};

/**
 * Show
 */

exports.show = function (req, res) {
  var layer = req.layer.toObject();

  var features = [];

  // This step is needed to populate features with related contents
  // as they are not part of feature model.
  async.each(
    layer.features,
    function (feature, callback) {
      Content.find({ features: { $in: [feature._id] } })
        .select('_id')
        .exec(function (err, contents) {
          if (err) callback(err);
          else {
            if (contents) {
              feature.contents = _.map(contents, function (ct) {
                return ct._id;
              });
            } else feature.contents = [];
            features.push(feature);
            callback();
          }
        });
    },
    function (err) {
      if (err) res.json(400, messages.error(req.i18n.t('layer.show.error')));
      layer.features = features;
      res.json(layer);
    }
  );
};

/**
 * Create a layer
 */

exports.create = function (req, res) {
  var layer = new Layer();

  var type = req.body.type;

  if (!type) {
    return res.json(400, messages.error(req.i18n.t('layer.create.missing')));
  } else if (type === 'TileLayer') {
    layer.url = req.body.url;
    layer.properties = req.body.properties;
  } else if (type === 'FeatureLayer') {
    layer.features = req.body.features;
    layer.contents = req.body.contents;

    if (req.body.isDraft === false) layer.isDraft = req.body.isDraft;
  }

  layer.type = type;
  layer.title = req.body.title;
  layer.description = req.body.description;
  layer.creator = req.user;
  layer.maps = req.body.maps;
  layer.visibility = req.body.visibility;

  layer.save(function (err) {
    if (!err) {
      res.json({
        layer: layer,
        messages: messages.success(req.i18n.t('layer.create.success')).messages
      });
    } else {
      res.json(400, { messages: messages.mongooseError(req.i18n, err) });
    }
  });
};

/**
 * Update layer
 */

exports.update = function (req, res) {
  var layer = req.layer;

  // do not update features or contents at this route
  delete req.body['features'];
  delete req.body['contents'];
  delete req.body['__v'];

  if (req.layer === 'TileLayer') {
    return res.json(
      400,
      messages.error(req.i18n.t('layer.update.tilelayer.error'))
    );
  }

  layer = _.extend(layer, req.body);

  layer.save(function (err) {
    if (!err) {
      res.json({
        layer: layer,
        messages: messages.success(req.i18n.t('layer.update.success')).messages
      });
    } else res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
  });
};

/**
 * Delete layer
 */

exports.destroy = function (req, res) {
  var layer = req.layer;
  layer.remove(function (err) {
    if (err) {
      res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
    } else {
      res.json(messages.success(req.i18n.t('layer.destroy.success')));
    }
  });
};

/**
 * Add a feature in layer
 */

exports.addFeature = function (req, res) {
  var feature = req.feature;

  var layer = req.layer;

  // associate layer to feature, if not already
  if (!_.contains(layer.features, feature._id)) {
    layer.features.push(feature);
  }

  feature.save(function (err) {
    res.json(400, messages.mongooseErrors(req.i18n.t, err, 'feature'));
    layer.save(function (err) {
      if (err) res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
      else res.json(feature);
    });
  });
};

/**
 * Remove feature from layer
 */

exports.removeFeature = function (req, res) {
  var feature = req.feature;

  var layer = req.layer;

  var saveLayer = function (err) {
    if (err) res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
    layer.features = _.filter(layer.features, function (f) {
      return !f._id.equals(feature._id);
    });
    layer.save(function (err) {
      if (err) res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
      else res.json(feature);
    });
  };

  feature.remove(saveLayer);
};

/**
 * Add a contributor to layer
 */

exports.addContributor = function (req, res) {
  var contributorEmail = req.body.email;

  var layer = req.layer;

  if (contributorEmail === req.user.email) {
    res.json(
      400,
      messages.error(req.i18n.t('layer.contributor.add.error.already_exists'))
    );
  } else {
    User.findOne({ email: contributorEmail }, function (err, user) {
      if (err) {
        res.json(400, messages.mongooseErrors(req.i18n.t, err, 'user'));
      } else if (!user) {
        res.json(
          400,
          messages.error(req.i18n.t('layer.contributor.add.error.dont_exists'))
        );
      } else {
        layer.contributors.addToSet(user);
        layer.save(function (err) {
          if (err) {
            res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
          } else {
            Layer.findById(layer._id)
              .populate('contributors', 'name username email')
              .exec(function (err, updatedLayer) {
                if (err) {
                  res.json(
                    400,
                    messages.mongooseErrors(req.i18n.t, err, 'layer')
                  );
                }

                var data = {
                  layer: updatedLayer,
                  creator: req.user,
                  contributor: user
                };

                req.app.locals.mailer.sendEmail(
                  'inform_contributor_permission',
                  user.email,
                  data,
                  req.i18n,
                  function (err) {
                    if (err) {
                      res.json(
                        400,
                        messages.error(
                          req.i18n.t('layer.contributor.add.error.email')
                        )
                      );
                    } else {
                      res.json({
                        layer: updatedLayer,
                        messages: messages.success(
                          req.i18n.t('layer.contributor.add.success')
                        ).messages
                      });
                    }
                  }
                );
              });
          }
        });
      }
    });
  }
};

/**
 * Remove feature from layer
 */

exports.removeContributor = function (req, res) {
  var contributorId = req.query.contributorId;

  var layer = req.layer;

  let contributorCount = layer.contributors.length;

  layer.contributors.pull({ _id: contributorId });

  if (contributorCount === layer.contributors.lentgh) {
    res.json(
      400,
      messages.error(req.i18n.t('layer.contributor.remove.error.invalid_id'))
    );
  } else {
    layer.save(function (err) {
      if (err) {
        res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer'));
      } else {
        Layer.findById(layer._id)
          .populate('contributors', 'name username email')
          .exec(function (err, updatedLayer) {
            if (err) { res.json(400, messages.mongooseErrors(req.i18n.t, err, 'layer')); }

            res.json({
              layer: updatedLayer,
              messages: messages.success(
                req.i18n.t('layer.contributor.remove.success')
              ).messages
            });
          });
      }
    });
  }
};


text:
var request = require('request');
var md5 = require('MD5');

function Huobi(key, secret) {
	this.key = key;
	this.secret = secret;
}

Huobi.prototype._request = function(params, callback) {
	params['access_key'] = this.key;
	params['created'] = Math.floor(Date.now() / 1000); // in seconds
	params['sign'] = sign(params, this.secret);

	var options = {
		url: 'https://api.huobi.com/apiv2.php',
		form: params
	};

	request.post(options, function(error, response, body) {
		var data = JSON.parse(body);
		if (data['code']) {
			data['errormessage'] = errorMessage(data['code']);
		}

		callback(data, error);
	});
};

Huobi.prototype.getAccountInfo = function(callback) {
	var params = {
		method: 'get_account_info'
	};

	this._request(params, callback);
};

Huobi.prototype.getOrders = function(coinType, callback) {
	var params = {
		method: 'get_orders',
		coin_type: coinType
	};

	this._request(params, callback);
};

Huobi.prototype.orderInfo = function(coinType, id, callback) {
	var params = {
		method: 'order_info',
		coin_type: coinType,
		id: id
	};

	this._request(params, callback);
};

Huobi.prototype.buy = function(coinType, price, amount, callback) {
	var params = {
		method: 'buy',
		coin_type: coinType,
		price: price,
		amount: amount
	};

	this._request(params, callback);
};

Huobi.prototype.sell = function(coinType, price, amount, callback) {
	var params = {
		method: 'sell',
		coin_type: coinType,
		price: price,
		amount: amount
	};

	this._request(params, callback);
};

Huobi.prototype.buyMarket = function(coinType, amount, callback) {
	var params = {
		method: 'buy_market',
		coin_type: coinType,
		amount: amount
	};

	this._request(params, callback);
};

Huobi.prototype.sellMarket = function(coinType, amount, callback) {
	var params = {
		method: 'buy_market',
		coin_type: coinType,
		amount: amount
	};

	this._request(params, callback);
};

Huobi.prototype.cancelOrder = function(coinType, id, callback) {
	var params = {
		method: 'cancel_order',
		coin_type: coinType,
		id: id
	};

	this._request(params, callback);
};

Huobi.prototype.modifyOrder = function(coinType, id, price, amount, callback) {
	var params = {
		method: 'modify_order',
		coin_type: coinType,
		id: id,
		price: price,
		amount: amount
	};

	this._request(params, callback);
};

Huobi.prototype.getNewDealOrders = function(coinType, callback) {
	var params = {
		method: 'get_new_deal_orders',
		coin_type: coinType,
	};

	this._request(params, callback);
};

Huobi.prototype.getOrderIdByTradeId = function(coinType, tradeId, callback) {
	var params = {
		method: 'get_order_id_by_trade_id',
		coin_type: coinType,
		trade_id: tradeId
	};

	this._request(params, callback);
};

function sign(params, secret) {
	return md5(stringifyForSign(params) + '&secret_key='+ secret).toLowerCase();
}

function stringifyForSign(obj) {
	var arr = [],
	i,
	formattedObject = '';

	for (i in obj) {
		if (obj.hasOwnProperty(i)) {
			arr.push(i);
		}
	}
	arr.sort();
	for (i = 0; i < arr.length; i++) {
		if (i != 0) {
			formattedObject += '&';
		}
		formattedObject += arr[i] + '=' + obj[arr[i]];
	}
	return formattedObject;
}

function errorMessage(code) {
	var codes = {
		1:  'Server error',
		2:  'Not enough CNY',
		3:  'Restart failed',
		4:  'Trade over',
		10: 'Not enough BTC',
		11:	'Not enough LTC',
		18:	'Incorrect payment password',
		26:	'Order is not exist',
		41:	'Filled order, unable to modify',
		42:	'Order has been cancelled, unable to modify',
		44:	'Price is too low',
		45:	'Price is too high',
		46:	'Minimum amount is 0.001',
		47:	'Exceed the limit amount',
		55:	'10% higher than market price is not allowed',
		56:	'10% lower than market price is not allowed',
		64:	'Invalid request',
		65:	'Invalid method',
		66:	'Invalid access key',
		67:	'Invalid private key',
		68:	'Invalid price',
		69:	'Invalid amount',
		70:	'Invalid POST time',
		71:	'Overflowed requests',
		87:	'Buying price cannot exceed 1% of market price when transaction amount is less than 0.1 BTC.',
		88:	'Selling price cannot be lower 1% of market price when transaction amount is less than 0.1 BTC.',
		89:	'Buying price cannot exceed 1% of market price when transaction amount is less than 0.1 BTC.',
		90:	'Selling price cannot be lower 1% of market price when transaction amount is less than 0.1 BTC.',
		91:	'Invalid type',
		92:	'Buy price cannot be higher 10% than market price.',
		93:	'Sell price cannot be lower 10% than market price.',
		97:	'Please enter payment password.',
		107:'Order is exist.'
	}
	if (!codes[code]) {
		return 'Huobi error code: ' + code + 'is not supported';
	}

	return codes[code];
}

module.exports = Huobi;


text:
app = node.run_state[:current_app]

include_recipe "unicorn"

node.default[:unicorn][:worker_timeout] = 60
node.default[:unicorn][:preload_app] = false
node.default[:unicorn][:worker_processes] = [node[:cpu][:total].to_i * 4, 8].min
node.default[:unicorn][:preload_app] = false
node.default[:unicorn][:before_fork] = 'sleep 1'
node.default[:unicorn][:port] = '8080'
node.set[:unicorn][:options] = { :tcp_nodelay => true, :backlog => 100 }

unicorn_config "/etc/unicorn/#{app['id']}.rb" do
  listen({ node[:unicorn][:port] => node[:unicorn][:options] })
  working_directory ::File.join(app['deploy_to'], 'current')
  worker_timeout node[:unicorn][:worker_timeout]
  preload_app node[:unicorn][:preload_app]
  worker_processes node[:unicorn][:worker_processes]
  before_fork node[:unicorn][:before_fork]
end

runit_service app['id'] do
  template_name 'unicorn'
  cookbook 'application'
  options(
    :app => app,
    :rails_env => node.run_state[:rails_env] || node.chef_environment,
    :smells_like_rack => ::File.exists?(::File.join(app['deploy_to'], "current", "config.ru"))
  )
  run_restart false
end

if ::File.exists?(::File.join(app['deploy_to'], "current"))
  d = resources(:deploy_revision => app['id'])
  d.restart_command do
    execute "/etc/init.d/#{app['id']} hup"
  end
end


text:
namespace CoreFtp
{
    using System.Linq;

    public static class FtpClientFeaturesExtensions
    {
        public static bool UsesMlsd( this FtpClient operand )
        {
            return ( operand.Features != null ) && operand.Features.Any( x => x == "MLSD" );
        }

        public static bool UsesEpsv( this FtpClient operand )
        {
            return ( operand.Features != null ) && operand.Features.Any( x => x == "EPSV" );
        }

        public static bool UsesPasv( this FtpClient operand )
        {
            return ( operand.Features != null ) && operand.Features.Any( x => x == "PASV" );
        }
    }
}


text:
layout: post
theme: XiXiuTi
series:
  url: angular
  title: Angular
title: Component Styles
excerpt: "How Component Styles work in Angular Application?"
modified: 2019-06-30T18:00:00-00:00
categories: articles
tags: [CSS, Angular]
image:
  vendor: gstatic
  feature: /prettyearth/assets/full/2090.jpg
  credit: Google Earth
  creditlink: https://earthview.withgoogle.com/weisswasser-germany-2090
comments: true
share: true
references:
  - id: 1
    title: "Angular - Component Styles"
    url: "https://angular.io/guide/component-styles"
  - id: 2
    title: "Angular :host, :host-context, ::ng-deep - Angular View Encapsulation"
    url: "https://blog.angular-university.io/angular-host-context/"

---

* TOC
{:toc}

https://ultimatecourses.com/blog/emulated-native-shadow-dom-angular-2-view-encapsulation#Global_CSS

## Problem

在 Angular 应用程序开发中会遇到怎么设置组件样式的问题, 我想在某个组件中设置另外某个组件的样式, 而且不像要此样式对其他组件中的此组件有影响, 应该怎么设置 CSS 样式呐?

## Solution

> Angular can bundle component styles with components, enabling a more modular design than regular stylesheets.

什么是 a more modular design ?

### CSS Modular Design

styling modularity feature

`:host`

`:host-context`

`/deep/`

### View encapsulation

* ShadowDom
* Native
* Emulated
* None

https://angular.io/guide/styleguide


text:
typedef enum _ASIPostFormat {
    ASIMultipartFormDataPostFormat = 0,
    ASIURLEncodedPostFormat = 1

} ASIPostFormat;

@interface ASIFormDataRequest : ASIHTTPRequest <NSCopying> {

	// Parameters that will be POSTed to the url
	NSMutableDictionary *postData;

	// Files that will be POSTed to the url
	NSMutableDictionary *fileData;

	ASIPostFormat postFormat;

	NSStringEncoding stringEncoding;

#if DEBUG_FORM_DATA_REQUEST
	// Will store a string version of the request body that will be printed to the console when ASIHTTPREQUEST_DEBUG is set in GCC_PREPROCESSOR_DEFINITIONS
	NSString *debugBodyString;
#endif

}

#pragma mark utilities
- (NSString*)encodeURL:(NSString *)string;

#pragma mark setup request

// Add a POST variable to the request
- (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key;

// Add the contents of a local file to the request
- (void)setFile:(NSString *)filePath forKey:(NSString *)key;

// Same as above, but you can specify the content-type and file name
- (void)setFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;

// Add the contents of an NSData object to the request
- (void)setData:(NSData *)data forKey:(NSString *)key;

// Same as above, but you can specify the content-type and file name
- (void)setData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;

@property (assign) ASIPostFormat postFormat;
@property (assign) NSStringEncoding stringEncoding;
@end


text:
// Copyright © 2011 - Present RealDimensions Software, LLC
//
// 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.

namespace chocolatey.infrastructure.app.services
{
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using configuration;
    using results;

    /// <summary>
    ///   The packaging service
    /// </summary>
    public interface IChocolateyPackageService
    {

        /// <summary>
        ///   Ensures the application that controls a source is installed
        /// </summary>
        /// <param name="config">The configuration.</param>
        void ensure_source_app_installed(ChocolateyConfiguration config);

        /// <summary>
        ///   Retrieves the count of items that meet the search criteria.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        int count_run(ChocolateyConfiguration config);

        /// <summary>
        ///   Run list in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void list_noop(ChocolateyConfiguration config);

        /// <summary>
        ///   Lists/searches for packages that meet a search criteria
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns></returns>
        IEnumerable<PackageResult> list_run(ChocolateyConfiguration config);

        /// <summary>
        ///   Run pack in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void pack_noop(ChocolateyConfiguration config);

        /// <summary>
        ///   Compiles a package
        /// </summary>
        /// <param name="config">The configuration.</param>
        void pack_run(ChocolateyConfiguration config);

        /// <summary>
        ///   Run push in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void push_noop(ChocolateyConfiguration config);

        /// <summary>
        ///   Pushes packages to remote feeds.
        /// </summary>
        /// <param name="config">The configuration.</param>
        void push_run(ChocolateyConfiguration config);

        /// <summary>
        ///   Run install in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void install_noop(ChocolateyConfiguration config);

        /// <summary>
        ///   Installs packages
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>results of installs</returns>
        ConcurrentDictionary<string, PackageResult> install_run(ChocolateyConfiguration config);

        /// <summary>
        ///  Run outdated in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void outdated_noop(ChocolateyConfiguration config);

        /// <summary>
        /// Determines all packages that are out of date
        /// </summary>
        /// <param name="config">The configuration.</param>
        void outdated_run(ChocolateyConfiguration config);

        /// <summary>
        ///   Run upgrade in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void upgrade_noop(ChocolateyConfiguration config);

        /// <summary>
        ///   Upgrades packages
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>results of upgrades</returns>
        ConcurrentDictionary<string, PackageResult> upgrade_run(ChocolateyConfiguration config);

        /// <summary>
        ///   Run uninstall in noop mode
        /// </summary>
        /// <param name="config">The configuration.</param>
        void uninstall_noop(ChocolateyConfiguration config);

        /// <summary>
        ///   Uninstalls packages
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>results of upgrades</returns>
        ConcurrentDictionary<string, PackageResult> uninstall_run(ChocolateyConfiguration config);
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Fixer\LanguageConstruct;

use PhpCsFixer\Tests\Test\AbstractFixerTestCase;

/**
 * @internal
 *
 * @covers \PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer
 */
final class DeclareParenthesesFixerTest extends AbstractFixerTestCase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix(string $expected, ?string $input = null): void
    {
        $this->doTest($expected, $input);
    }

    public function provideFixCases(): iterable
    {
        yield 'spaces around parentheses' => [
            '<?php declare(strict_types = 1);',
            '<?php declare ( strict_types = 1 );',
        ];

        yield 'newlines (\n) around parentheses' => [
            '<?php declare(strict_types = 1);',
            '<?php declare
            (
                strict_types = 1
            );',
        ];

        yield 'newlines (\r\n) around parentheses' => [
            '<?php declare(strict_types = 1);',
            "<?php declare\r
            (\r
                strict_types = 1\r
            );",
        ];
    }
}


text:
<?php

namespace Acme\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Acme\UserBundle\Entity\Sellbusiness
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Sellbusiness
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var float $quantity
     *
     * @ORM\Column(name="quantity", type="float")
     */
    private $quantity;

    /**
     * @var integer $price
     *
     * @ORM\Column(name="price", type="integer")
     */
    private $price;

    /**
     * @var string $origin
     *
     * @ORM\Column(name="origin", type="string", length=255)
     */
    private $origin;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set quantity
     *
     * @param float $quantity
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
    }

    /**
     * Get quantity
     *
     * @return float
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * Set price
     *
     * @param integer $price
     */
    public function setPrice($price)
    {
        $this->price = $price;
    }

    /**
     * Get price
     *
     * @return integer
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set origin
     *
     * @param string $origin
     */
    public function setOrigin($origin)
    {
        $this->origin = $origin;
    }

    /**
     * Get origin
     *
     * @return string
     */
    public function getOrigin()
    {
        return $this->origin;
    }
	/**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="sellbusiness")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

    /**
     * Set user
     *
     * @param Acme\UserBundle\Entity\User $user
     */
    public function setUser(\Acme\UserBundle\Entity\User $user)
    {
        $this->user = $user;
    }

    /**
     * Get user
     *
     * @return Acme\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
	/**
     * @ORM\ManyToOne(targetEntity="Business", inversedBy="sellbusiness")
     * @ORM\JoinColumn(name="business_id", referencedColumnName="id")
     */
    protected $business;

    /**
     * Set business
     *
     * @param Acme\UserBundle\Entity\Business $business
     */
    public function setBusiness(\Acme\UserBundle\Entity\Business $business)
    {
        $this->business = $business;
    }

    /**
     * Get business
     *
     * @return Acme\UserBundle\Entity\Business
     */
    public function getBusiness()
    {
        return $this->business;
    }
	 /**
     * @var string $approved
     *
     * @ORM\Column(name="approved", type="boolean", nullable=true)
     */
    private $approved;

    /**
     * Set approved
     *
     * @param boolean $approved
     */
    public function setApproved($approved)
    {
        $this->approved = $approved;
    }

    /**
     * Get approved
     *
     * @return boolean
     */
    public function getApproved()
    {
        return $this->approved;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ApiPortVS.Contracts
{
    public interface IOutputWindowWriter
    {
        Task ShowWindowAsync();

        Task ClearWindowAsync();

        void WriteLine();

        void WriteLine(string contents);

        void WriteLine(string format, params object[] arg);
    }
}


text:
layout: default
title: Changelog
---


text:
class HarvestEvent < ActiveRecord::Base

  belongs_to :resource
  has_many :data_objects_harvest_events
  has_many :data_objects, through: :data_objects_harvest_events
  has_many :harvest_events_hierarchy_entries
  has_and_belongs_to_many :hierarchy_entries

  validates_inclusion_of :publish, in: [false], unless: :publish_is_allowed?

  scope :incomplete, -> { where(completed_at: nil) }

  def self.last_incomplete_resource
    return nil if incomplete.count < 1
    incomplete.includes(:resource).last.resource
  end

  # harvest event ids for the last harvest event of every resource
  def self.latest_ids
    @latest_ids ||= HarvestEvent.maximum('id', group: :resource_id).values
  end

  def self.last_published
    last_published=HarvestEvent.find(:all, conditions: "published_at != 'null'", limit: 1, order: 'published_at desc')
    return (last_published.blank? ? nil : last_published[0])
  end

  def self.data_object_ids_from_harvest(harvest_event_id)
    query = "Select dohe.data_object_id
    From harvest_events he
    Join data_objects_harvest_events dohe ON he.id = dohe.harvest_event_id
    Where he.id = #{harvest_event_id}"
    rset = self.find_by_sql [query]
    arr=[]
    for fld in rset
      arr << fld["data_object_id"]
    end
    return arr
  end

  def content_partner
    resource.content_partner
  end

  def curated_data_objects(params = {})
    year = params[:year] || nil
    month = params[:month] || nil

    unless year || month
      year = Time.now.year if year.nil?
      month = Time.now.month if month.nil?
    end

    year = Time.now.year if year.nil?
    month = 0 if month.nil?
    lower_date_range = "#{year}-#{month}-00"
    if month.to_i == 0
      upper_date = Time.local(year, 1) + 1.year
      upper_date_range = "#{upper_date.year}-#{upper_date.month}-00"
    else
      upper_date = Time.local(year, month) + 1.month
      upper_date_range = "#{upper_date.year}-#{upper_date.month}-00"
    end

    date_condition = ""
    if lower_date_range
      date_condition = "AND curator_activity_logs.updated_at BETWEEN '#{lower_date_range}' AND '#{upper_date_range}'"
    end

    curator_activity_logs = CuratorActivityLog.find(:all,
      joins: "JOIN #{DataObjectsHarvestEvent.full_table_name} dohe ON (curator_activity_logs.data_object_guid=dohe.guid)",
      conditions: "curator_activity_logs.activity_id IN (#{Activity.trusted.id}, #{Activity.untrusted.id}, #{Activity.hide.id}, #{Activity.show.id}) AND curator_activity_logs.changeable_object_type_id IN (#{ChangeableObjectType.data_object_scope.join(',')}) AND dohe.harvest_event_id = #{id} #{date_condition}",
      select: 'id')

    curator_activity_logs = CuratorActivityLog.find_all_by_id(curator_activity_logs.collect{ |ah| ah.id },
      include: [ :user, :comment, :activity, :changeable_object_type, :data_object  ],
      select: {
        users: [ :id, :given_name, :family_name ],
        comments: [ :id, :user_id, :body ],
        data_objects: [ :id, :object_cache_url, :source_url, :data_type_id, :published, :created_at ] })

    data_objects = curator_activity_logs.collect(&:data_object)
    DataObject.replace_with_latest_versions!(data_objects, check_only_published: true, language_id: Language.english.id)
    includes = [ { data_objects_hierarchy_entries: [ { hierarchy_entry: [ :name, :hierarchy, :taxon_concept ] }, :vetted, :visibility ] } ]
    includes << { all_curated_data_objects_hierarchy_entries: [ { hierarchy_entry: [ :name, :hierarchy, :taxon_concept ] }, :vetted, :visibility, :user ] }
    DataObject.preload_associations(data_objects, includes)
    DataObject.preload_associations(data_objects, :users_data_object)
    curator_activity_logs.each do |cal|
      if d = data_objects.detect{ |o| cal.data_object.guid == o.guid }
        cal.data_object = d
      end
    end

    curator_activity_logs.sort_by{ |ah| Invert(ah.id) }
  end

  def publish_is_allowed?
    self.published_at.blank? && !self.completed_at.blank? && self == self.resource.latest_harvest_event
  end

  def publish_pending?
    self.published_at.blank? && self.publish?
  end

  def destroy_everything
    Rails.logger.error("** Destroying HarvestEvent #{id}")
    Rails.logger.error("   #{data_objects.count} DataObjects...")
    data_objects.each do |dato|
      dato.destroy_everything
      dato.destroy
    end
    DataObjectsHarvestEvent.where(harvest_event_id: id).destroy_all
    hierarchy_entries.each do |entry|
      entry.destroy_everything
      name = Name.find(entry.name_id)
      hierarchy = Hierarchy.find(entry.hierarchy_id)
      entry.destroy
      entry.taxon_concept.destroy if
        entry.taxon_concept.hierarchy_entries.blank?
      name.destroy if name.hierarchy_entries.blank?
      hierarchy.destroy if hierarchy.hierarchy_entries.blank?
    end
    # This next operation can fail because of table locks...
    begin
      HarvestEventsHierarchyEntry.delete_all(["harvest_event_id = ?", id])
    rescue ActiveRecord::StatementInvalid => e
      # This is not *fatal*, it's just unfortunate. Probably because we're harvesting, but waiting for harvests to finish is not possible.
      Rails.logger.error("** Unable to delete from HarvestEventsHierarchyEntry where harvest_event_id = #{id} (#{e.message})")
    end
    Rails.logger.error("** Destroyed HarvestEvent #{id}")
  end

end


text:
module Fastlane
  module Actions
    module SharedValues
      IPA_OUTPUT_PATH = :IPA_OUTPUT_PATH
      DSYM_OUTPUT_PATH = :DSYM_OUTPUT_PATH
    end

    class GymAction < Action
      def self.run(values)
        require 'gym'

        should_use_legacy_api = values[:use_legacy_build_api] || Gym::Xcode.pre_7?

        if values[:provisioning_profile_path].to_s.length.zero? && should_use_legacy_api
          sigh_path = Actions.lane_context[SharedValues::SIGH_PROFILE_PATH] || ENV["SIGH_PROFILE_PATH"]
          values[:provisioning_profile_path] = File.expand_path(sigh_path) if sigh_path
        end

        values[:export_method] ||= Actions.lane_context[SharedValues::SIGH_PROFILE_TYPE]

        if Actions.lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING]
          # Since Xcode 9 you need to explicitly provide the provisioning profile per app target
          # If the user is smart and uses match and gym together with fastlane, we can do all
          # the heavy lifting for them
          values[:export_options] ||= {}
          values[:export_options][:provisioningProfiles] = Actions.lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING]
        end

        absolute_ipa_path = File.expand_path(Gym::Manager.new.work(values))
        absolute_dsym_path = absolute_ipa_path.gsub(".ipa", ".app.dSYM.zip")

        # This might be the mac app path, so we don't want to set it here
        # https://github.com/fastlane/fastlane/issues/5757
        if absolute_ipa_path.include?(".ipa")
          Actions.lane_context[SharedValues::IPA_OUTPUT_PATH] = absolute_ipa_path
          ENV[SharedValues::IPA_OUTPUT_PATH.to_s] = absolute_ipa_path # for deliver
        end

        Actions.lane_context[SharedValues::DSYM_OUTPUT_PATH] = absolute_dsym_path if File.exist?(absolute_dsym_path)
        Actions.lane_context[SharedValues::XCODEBUILD_ARCHIVE] = Gym::BuildCommandGenerator.archive_path
        ENV[SharedValues::DSYM_OUTPUT_PATH.to_s] = absolute_dsym_path if File.exist?(absolute_dsym_path)

        return absolute_ipa_path
      end

      def self.description
        "Easily build and sign your app using _gym_"
      end

      def self.details
        "More information: https://fastlane.tools/gym"
      end

      def self.return_value
        "The absolute path to the generated ipa file"
      end

      def self.author
        "KrauseFx"
      end

      def self.available_options
        require 'gym'
        Gym::Options.available_options
      end

      def self.is_supported?(platform)
        [:ios, :mac].include? platform
      end

      def self.example_code
        [
          'gym(scheme: "MyApp", workspace: "MyApp.xcworkspace")',
          'gym(
            workspace: "MyApp.xcworkspace",
            configuration: "Debug",
            scheme: "MyApp",
            silent: true,
            clean: true,
            output_directory: "path/to/dir", # Destination directory. Defaults to current directory.
            output_name: "my-app.ipa",       # specify the name of the .ipa file to generate (including file extension)
            sdk: "10.0"                      # use SDK as the name or path of the base SDK when building the project.
          )'
        ]
      end

      def self.category
        :building
      end
    end
  end
end


text:
package snapshot

import (
	gocontext "context"

	"github.com/boltdb/bolt"
	eventsapi "github.com/containerd/containerd/api/services/events/v1"
	snapshotapi "github.com/containerd/containerd/api/services/snapshot/v1"
	"github.com/containerd/containerd/api/types"
	"github.com/containerd/containerd/errdefs"
	"github.com/containerd/containerd/events"
	"github.com/containerd/containerd/log"
	"github.com/containerd/containerd/metadata"
	"github.com/containerd/containerd/mount"
	"github.com/containerd/containerd/plugin"
	"github.com/containerd/containerd/snapshot"
	protoempty "github.com/golang/protobuf/ptypes/empty"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

type config struct {
	// Default is the default snapshotter to use for the service
	Default string `toml:"default,omitempty"`
}

func init() {
	plugin.Register(&plugin.Registration{
		Type: plugin.GRPCPlugin,
		ID:   "snapshots",
		Requires: []plugin.PluginType{
			plugin.SnapshotPlugin,
			plugin.MetadataPlugin,
		},
		Config: &config{
			Default: defaultSnapshotter,
		},
		Init: newService,
	})
}

var empty = &protoempty.Empty{}

type service struct {
	snapshotter snapshot.Snapshotter
	emitter     events.Poster
}

func newService(ic *plugin.InitContext) (interface{}, error) {
	evts := events.GetPoster(ic.Context)
	snapshotters, err := ic.GetAll(plugin.SnapshotPlugin)
	if err != nil {
		return nil, err
	}
	cfg := ic.Config.(*config)

	sn, ok := snapshotters[cfg.Default]
	if !ok {
		return nil, errors.Errorf("default snapshotter not loaded: %s", cfg.Default)
	}

	md, err := ic.Get(plugin.MetadataPlugin)
	if err != nil {
		return nil, err
	}

	return &service{
		snapshotter: metadata.NewSnapshotter(md.(*bolt.DB), cfg.Default, sn.(snapshot.Snapshotter)),
		emitter:     evts,
	}, nil
}

func (s *service) Register(gs *grpc.Server) error {
	snapshotapi.RegisterSnapshotsServer(gs, s)
	return nil
}

func (s *service) Prepare(ctx context.Context, pr *snapshotapi.PrepareSnapshotRequest) (*snapshotapi.PrepareSnapshotResponse, error) {
	log.G(ctx).WithField("parent", pr.Parent).WithField("key", pr.Key).Debugf("Preparing snapshot")
	// TODO: Apply namespace
	// TODO: Lookup snapshot id from metadata store
	mounts, err := s.snapshotter.Prepare(ctx, pr.Key, pr.Parent)
	if err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	if err := s.emit(ctx, "/snapshot/prepare", &eventsapi.SnapshotPrepare{
		Key:    pr.Key,
		Parent: pr.Parent,
	}); err != nil {
		return nil, err
	}
	return &snapshotapi.PrepareSnapshotResponse{
		Mounts: fromMounts(mounts),
	}, nil
}

func (s *service) View(ctx context.Context, pr *snapshotapi.ViewSnapshotRequest) (*snapshotapi.ViewSnapshotResponse, error) {
	log.G(ctx).WithField("parent", pr.Parent).WithField("key", pr.Key).Debugf("Preparing view snapshot")
	// TODO: Apply namespace
	// TODO: Lookup snapshot id from metadata store
	mounts, err := s.snapshotter.View(ctx, pr.Key, pr.Parent)
	if err != nil {
		return nil, errdefs.ToGRPC(err)
	}
	return &snapshotapi.ViewSnapshotResponse{
		Mounts: fromMounts(mounts),
	}, nil
}

func (s *service) Mounts(ctx context.Context, mr *snapshotapi.MountsRequest) (*snapshotapi.MountsResponse, error) {
	log.G(ctx).WithField("key", mr.Key).Debugf("Getting snapshot mounts")
	// TODO: Apply namespace
	// TODO: Lookup snapshot id from metadata store
	mounts, err := s.snapshotter.Mounts(ctx, mr.Key)
	if err != nil {
		return nil, errdefs.ToGRPC(err)
	}
	return &snapshotapi.MountsResponse{
		Mounts: fromMounts(mounts),
	}, nil
}

func (s *service) Commit(ctx context.Context, cr *snapshotapi.CommitSnapshotRequest) (*protoempty.Empty, error) {
	log.G(ctx).WithField("key", cr.Key).WithField("name", cr.Name).Debugf("Committing snapshot")
	// TODO: Apply namespace
	// TODO: Lookup snapshot id from metadata store
	if err := s.snapshotter.Commit(ctx, cr.Name, cr.Key); err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	if err := s.emit(ctx, "/snapshot/commit", &eventsapi.SnapshotCommit{
		Key:  cr.Key,
		Name: cr.Name,
	}); err != nil {
		return nil, err
	}
	return empty, nil
}

func (s *service) Remove(ctx context.Context, rr *snapshotapi.RemoveSnapshotRequest) (*protoempty.Empty, error) {
	log.G(ctx).WithField("key", rr.Key).Debugf("Removing snapshot")
	// TODO: Apply namespace
	// TODO: Lookup snapshot id from metadata store
	if err := s.snapshotter.Remove(ctx, rr.Key); err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	if err := s.emit(ctx, "/snapshot/remove", &eventsapi.SnapshotRemove{
		Key: rr.Key,
	}); err != nil {
		return nil, err
	}
	return empty, nil
}

func (s *service) Stat(ctx context.Context, sr *snapshotapi.StatSnapshotRequest) (*snapshotapi.StatSnapshotResponse, error) {
	log.G(ctx).WithField("key", sr.Key).Debugf("Statting snapshot")
	// TODO: Apply namespace
	info, err := s.snapshotter.Stat(ctx, sr.Key)
	if err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	return &snapshotapi.StatSnapshotResponse{Info: fromInfo(info)}, nil
}

func (s *service) List(sr *snapshotapi.ListSnapshotsRequest, ss snapshotapi.Snapshots_ListServer) error {
	// TODO: Apply namespace
	var (
		buffer    []snapshotapi.Info
		sendBlock = func(block []snapshotapi.Info) error {
			return ss.Send(&snapshotapi.ListSnapshotsResponse{
				Info: block,
			})
		}
	)
	err := s.snapshotter.Walk(ss.Context(), func(ctx gocontext.Context, info snapshot.Info) error {
		buffer = append(buffer, fromInfo(info))

		if len(buffer) >= 100 {
			if err := sendBlock(buffer); err != nil {
				return err
			}

			buffer = buffer[:0]
		}

		return nil
	})
	if err != nil {
		return err
	}
	if len(buffer) > 0 {
		// Send remaining infos
		if err := sendBlock(buffer); err != nil {
			return err
		}
	}

	return nil
}

func (s *service) Usage(ctx context.Context, ur *snapshotapi.UsageRequest) (*snapshotapi.UsageResponse, error) {
	// TODO: Apply namespace
	usage, err := s.snapshotter.Usage(ctx, ur.Key)
	if err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	return fromUsage(usage), nil
}

func fromKind(kind snapshot.Kind) snapshotapi.Kind {
	if kind == snapshot.KindActive {
		return snapshotapi.KindActive
	}
	return snapshotapi.KindCommitted
}

func fromInfo(info snapshot.Info) snapshotapi.Info {
	return snapshotapi.Info{
		Name:     info.Name,
		Parent:   info.Parent,
		Kind:     fromKind(info.Kind),
		Readonly: info.Readonly,
	}
}

func fromUsage(usage snapshot.Usage) *snapshotapi.UsageResponse {
	return &snapshotapi.UsageResponse{
		Inodes: usage.Inodes,
		Size_:  usage.Size,
	}
}

func fromMounts(mounts []mount.Mount) []*types.Mount {
	out := make([]*types.Mount, len(mounts))
	for i, m := range mounts {
		out[i] = &types.Mount{
			Type:    m.Type,
			Source:  m.Source,
			Options: m.Options,
		}
	}
	return out
}

func (s *service) emit(ctx context.Context, topic string, evt interface{}) error {
	emitterCtx := events.WithTopic(ctx, topic)
	if err := s.emitter.Post(emitterCtx, evt); err != nil {
		return err
	}

	return nil
}


text:
SignalOwner::SignalOwner()
{
	m_signal = new Signal(this);
}

SignalOwner::~SignalOwner()
{
	m_signal->removeOwner();
}

void SignalOwner::onSignal(const NamedMessage& msg)
{
	m_signal->onSignal(msg);
}

void SignalOwner::addSubscriber(SignalReceiver* receiver, IReceiverFunc* func)
{
	receiver->addSignal(m_signal, func);
}


text:
var assert = require('assert');
var common = require('../../common');

var table = 'nested_test';

common.getTestConnection(function (err, connection) {
  assert.ifError(err);

  common.useTestDb(connection);

  connection.query([
    'CREATE TEMPORARY TABLE ?? (',
    '`id` int(11) unsigned NOT NULL AUTO_INCREMENT,',
    '`title` varchar(255),',
    'PRIMARY KEY (`id`)',
    ') ENGINE=InnoDB DEFAULT CHARSET=utf8'
  ].join('\n'), [table], assert.ifError);

  connection.query('INSERT INTO ?? SET ?', [table, {title: 'test'}], assert.ifError);

  connection.query({nestTables: true, sql: 'SELECT * FROM ??', values: [table]}, function (err, rows) {
    assert.ifError(err);
    assert.equal(rows.length, 1);
    assert.equal(rows[0].nested_test.id, 1);
    assert.equal(rows[0].nested_test.title, 'test');
  });

  connection.query({nestTables: '_', sql: 'SELECT * FROM ??', values: [table]}, function (err, rows) {
    assert.ifError(err);
    assert.equal(rows.length, 1);
    assert.equal(rows[0].nested_test_id, 1);
    assert.equal(rows[0].nested_test_title, 'test');
  });

  connection.end(assert.ifError);
});


text:
<?php

use Faker\Generator as Faker;
use Faker\Factory as FakerFactory;

$factory->define(App\Missive\Domain\Models\Contact::class, function (Faker $faker) {
    $faker = FakerFactory::create('en_PH');
    return [
        'mobile' => $faker->mobileNumber,
        'handle' => $faker->name,
    ];
});


text:
package storage

import (
	"time"

	"github.com/cockroachdb/cockroach/client"
	"github.com/cockroachdb/cockroach/config"
	"github.com/cockroachdb/cockroach/gossip"
	"github.com/cockroachdb/cockroach/keys"
	"github.com/cockroachdb/cockroach/proto"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/log"
)

const (
	// rangeGCQueueMaxSize is the max size of the gc queue.
	rangeGCQueueMaxSize = 100

	// rangeGCQueueTimerDuration is the duration between GCs of queued ranges.
	rangeGCQueueTimerDuration = 10 * time.Second

	// RangeGCQueueInactivityThreshold is the inactivity duration after which
	// a range will be considered for garbage collection. Exported for testing.
	RangeGCQueueInactivityThreshold = 10 * 24 * time.Hour // 10 days
)

// rangeGCQueue manages a queue of ranges to be considered for garbage
// collections. The GC process asynchronously removes local data for
// ranges that have been rebalanced away from this store.
type rangeGCQueue struct {
	*baseQueue
	db *client.DB
}

// newRangeGCQueue returns a new instance of rangeGCQueue.
func newRangeGCQueue(db *client.DB, gossip *gossip.Gossip) *rangeGCQueue {
	q := &rangeGCQueue{
		db: db,
	}
	q.baseQueue = newBaseQueue("rangeGC", q, gossip, rangeGCQueueMaxSize)
	return q
}

func (q *rangeGCQueue) needsLeaderLease() bool {
	return false
}

func (q *rangeGCQueue) acceptsUnsplitRanges() bool {
	return true
}

// shouldQueue determines whether a range should be queued for GC, and
// if so at what priority. Ranges which have been inactive for longer
// than rangeGCQueueInactivityThreshold are considered for possible GC
// at equal priority.
func (q *rangeGCQueue) shouldQueue(now proto.Timestamp, rng *Replica,
	_ *config.SystemConfig) (bool, float64) {

	if l := rng.getLease(); l.Expiration.Add(RangeGCQueueInactivityThreshold.Nanoseconds(), 0).Less(now) {
		return true, 0
	}
	return false, 0
}

// process performs a consistent lookup on the range descriptor to see if we are
// still a member of the range.
func (q *rangeGCQueue) process(now proto.Timestamp, rng *Replica, _ *config.SystemConfig) error {
	desc := rng.Desc()

	// Calls to RangeLookup typically use inconsistent reads, but we
	// want to do a consistent read here. This is important when we are
	// considering one of the metadata ranges: we must not do an
	// inconsistent lookup in our own copy of the range.
	b := &client.Batch{}
	b.InternalAddRequest(&proto.RangeLookupRequest{
		RequestHeader: proto.RequestHeader{
			Key: keys.RangeMetaKey(desc.StartKey),
		},
		MaxRanges: 1,
	})
	br, err := q.db.RunWithResponse(b)
	if err != nil {
		return err
	}
	reply := br.Responses[0].GetInner().(*proto.RangeLookupResponse)

	if len(reply.Ranges) != 1 {
		return util.Errorf("expected 1 range descriptor, got %d", len(reply.Ranges))
	}

	replyDesc := reply.Ranges[0]
	currentMember := false
	if me := rng.GetReplica(); me != nil {
		for _, rep := range replyDesc.Replicas {
			if rep.StoreID == me.StoreID {
				currentMember = true
				break
			}
		}
	}

	if !currentMember {
		// We are no longer a member of this range; clean up our local data.
		if log.V(1) {
			log.Infof("destroying local data from range %d", desc.RangeID)
		}
		if err := rng.rm.RemoveReplica(rng); err != nil {
			return err
		}
		// TODO(bdarnell): update Destroy to leave tombstones for removed ranges (#768)
		// TODO(bdarnell): add some sort of locking to prevent the range
		// from being recreated while the underlying data is being destroyed.
		if err := rng.Destroy(); err != nil {
			return err
		}
	} else if desc.RangeID != desc.RangeID {
		// If we get a different  range ID back, then the range has been merged
		// away. But currentMember is true, so we are still a member of the
		// subsuming range. Shut down raft processing for the former range
		// and delete any remaining metadata, but do not delete the data.
		if log.V(1) {
			log.Infof("removing merged range %d", desc.RangeID)
		}
		if err := rng.rm.RemoveReplica(rng); err != nil {
			return err
		}

		// TODO(bdarnell): remove raft logs and other metadata (while leaving a
		// tombstone). Add tests for GC of merged ranges.
	} else {
		// This range is a current member of the raft group. Acquire the lease
		// to avoid processing this range again before the next inactivity threshold.
		if err := rng.requestLeaderLease(now); err != nil {
			if _, ok := err.(*proto.LeaseRejectedError); !ok {
				if log.V(1) {
					log.Infof("unable to acquire lease from valid range %s: %s", rng, err)
				}
			}
		}
	}

	return nil
}

func (q *rangeGCQueue) timer() time.Duration {
	return rangeGCQueueTimerDuration
}


text:
module TrackerApi
  module Endpoints
    class Stories
      attr_accessor :client

      def initialize(client)
        @client = client
      end

      def get(project_id, params={})
        data = client.paginate("/projects/#{project_id}/stories", params: params)
        raise Errors::UnexpectedData, 'Array of stories expected' unless data.is_a? Array

        data.map do |story|
          Resources::Story.new({ client: client, project_id: project_id }.merge(story))
        end
      end
    end
  end
end


text:
export var greet = function () {
    return 'Hello World!';
};

export var bye = function () {
    return 'See ya!';
};


text:
#include <Eigen/Core>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/common/transforms.h>
#include <cmath>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("           -trans dx,dy,dz           = the translation (default: ");
  print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
  print_info ("           -quat w,x,y,z             = rotation as quaternion\n");
  print_info ("           -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
  print_info ("           -matrix v1,v2,...,v8,v9   = a 3x3 affine transform\n");
  print_info ("           -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
  print_info ("   Note: If a rotation is not specified, it will default to no rotation.\n");
  print_info ("         If redundant or conflicting transforms are specified, then:\n");
  print_info ("           -axisangle will override -quat\n");
  print_info ("           -matrix (3x3) will take override -axisangle and -quat\n");
  print_info ("           -matrix (4x4) will take override all other arguments\n");

}

void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
  print_info ("[done, "); print_value ("%g", t); print_info (" ms : ");
  print_value ("%d", w*h); print_info (" points]\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);

  printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);

  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

template <typename PointT>
void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
                           Eigen::Matrix4f &tform)
{
  transformPointCloud (input, output, tform);
}

template <>
void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
                           Eigen::Matrix4f &tform)
{
  transformPointCloudWithNormals (input, output, tform);
}

template <>
void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
                                              PointCloud<PointXYZRGBNormal> & output,
                                              Eigen::Matrix4f &tform)
{
  transformPointCloudWithNormals (input, output, tform);
}

template <typename PointT>
void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
                            Eigen::Matrix4f &tform)
{
  PointCloud<PointT> cloud;
  fromROSMsg (input, cloud);
  transformPointCloudHelper (cloud, cloud, tform);
  toROSMsg (cloud, output);
}

void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
                      Eigen::Matrix4f &tform)
{
  // Check for 'rgb' and 'normals' fields
  bool has_rgb = false;
  bool has_normals = false;
  for (size_t i = 0; i < input.fields.size (); ++i)
  {
    if (input.fields[i].name == "rgb")
      has_rgb = true;
    if (input.fields[i].name == "normals")
      has_normals = true;
  }

  // Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
  if (!has_rgb && !has_normals)
    transformPointCloud2AsType<PointXYZ> (input, output, tform);
  else if (has_rgb && !has_normals)
    transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
  else if (!has_rgb && has_normals)
    transformPointCloud2AsType<PointNormal> (input, output, tform);
  else // (has_rgb && has_normals)
    transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
                Eigen::Matrix4f &tform)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Transforming ");

  transformPointCloud2 (*input, output, tform);

  printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);

}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output);

  printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Initialize the transformation matrix
  Eigen::Matrix4f tform;
  tform.setIdentity ();

  // Command line parsing
  float dx, dy, dz;
  std::vector<float> values;

  if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
  {
    tform (0, 3) = dx;
    tform (1, 3) = dy;
    tform (2, 3) = dz;
  }

  if (parse_x_arguments (argc, argv, "-quat", values) > -1)
  {
    if (values.size () == 4)
    {
      const float& x = values[0];
      const float& y = values[1];
      const float& z = values[2];
      const float& w = values[3];
      tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
    }
  }

  if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
  {
    if (values.size () == 4)
    {
      const float& ax = values[0];
      const float& ay = values[1];
      const float& az = values[2];
      const float& theta = values[3];
      tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
    }
  }

  if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
  {
    if (values.size () == 9 || values.size () == 16)
    {
      int n = values.size () == 9 ? 3 : 4;
      for (int r = 0; r < n; ++r)
        for (int c = 0; c < n; ++c)
          tform (r, c) = values[n*r+c];
    }
    else
    {
      print_error ("Wrong number of values given (%zu): ", values.size ());
      print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
    }
  }

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Apply the transform
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, tform);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}


text:
console.log('FlintSharing luanched!');

const appInfo = {
    appUrl: 'https://openflint.github.io/flint-sharing/receiver/screen_receiver.html',
    useIpc: true,
    maxInactive: -1
};

var devices = {};
var sharing = false;

var dlist = document.getElementById("dlist");

var share = document.getElementById("share");
share.onclick = function () {
    if (sharing) {
        alert('Already sharing!!!');
        return;
    }

    sharing = true;

    var options = dlist.options;
    var device = null;

    for (var i = 0; i < options.length; i++) {
        var option = options[i];
        if (option.selected) {
            device = {
                "value": option.value,
                "text": option.textContent
            };
            break;
        }
    }

    if (!device) {
        alert("Please select a device");
    } else {
        console.log('select device: ', device.value, ', text = ', device.text);

        var _stream = null;
        var senderManager = new FlintSenderManager({
            appId: '~a3ad1b9e-6883-11e4-b116-123b93f75cba',
            urlBase: devices[device.value].urlBase,
            host: devices[device.value].host,
            useHeartbeat: true
        });

        getScreenId(function (error, sourceId, screen_constraints) {
            // Firefox
            if (!!navigator.mozGetUserMedia) {
                screen_constraints = {
                    "audio": false,
                    "video": {
                        "mozMediaSource": "window",
                        "mediaSource": "window",
                        "maxWidth": 1920,
                        "maxHeight": 1080,
                        "minAspectRatio": 1.77
                    }
                };
            }

            navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
            navigator.getUserMedia(screen_constraints, function (stream) {
                console.log("Received screen stream.");
                _stream = stream;
                senderManager.launch(appInfo, function (result, token) {
                    if (result) {
                        console.log('Application is launched ! OK!!! -> ' + token);
                        senderManager.callReceiverMediaPeer(stream);
                        senderManager.on('appstate', function (_, state, additionaldata) {
                            if (state == 'stopped') {
                                sharing = false;
                                stream.stop();
                                console.log('Receiver application is stopped!!!');
                            }
                        });
                    }
                    else {
                        console.log('Application is launched ! failed!!!');
                    }
                });
            }, function (error) {
                console.error('get media error: ', error);
            });
        });

        var stopBtn = document.getElementById("stop");
        stopBtn.onclick = function () {
            if (!sharing) {
                alert('Not sharing!!!');
                return;
            }
            sharing = false;
            if (_stream != null) {
                _stream.stop();
            }
            senderManager.stop(appInfo);
        }
    }
};

console.log('FlintSharing send command: scan');
self.port.emit("scan");

self.port.on('devicefound', function (device) {
    console.log('find new device: ', device.deviceName);
    var uniqueId = device.uniqueId;
    dlist.innerHTML += '<option id="' + uniqueId + '" value="' + uniqueId + '">' + device.deviceName + '</option>';
    devices[uniqueId] = device;
});

self.port.on('devicelost', function (device) {
    console.log('lost device: ', device.deviceName);
});


text:
package models;

import java.util.ArrayList;

import play.libs.Json;
import utils.JSONConstants;

import com.fasterxml.jackson.databind.node.ObjectNode;
/**
 * Encapsulates a revision of a repository. Contains its files, along with the revision commit contents.
 *
 */
public class RepositoryRevision {
	private long elapsedTime;

	private ArrayList<RepositoryFile> repositoryFiles;

	private String lastCommit, lastCommitMessage, lastCommitAuthor;

	/**
	 * @return the elapsedTime
	 */
	public long getElapsedTime() {
		return elapsedTime;
	}

	/**
	 * @return the lastCommit
	 */
	public String getLastCommit() {
		return lastCommit;
	}

	/**
	 * @return the lastCommitAuthor
	 */
	public String getLastCommitAuthor() {
		return lastCommitAuthor;
	}

	/**
	 * @return the lastCommitMessage
	 */
	public String getLastCommitMessage() {
		return lastCommitMessage;
	}

	/**
	 * @return the repositoryFiles
	 */
	public ArrayList<RepositoryFile> getRepositoryFiles() {
		return repositoryFiles;
	}

	/**
	 * @param elapsedTime
	 *            the elapsedTime to set
	 */
	public void setElapsedTime(long elapsedTime) {
		this.elapsedTime = elapsedTime;
	}

	/**
	 * @param lastCommit
	 *            the lastCommit to set
	 */
	public void setLastCommit(String lastCommit) {
		this.lastCommit = lastCommit;
	}

	/**
	 * @param lastCommitAuthor
	 *            the lastCommitAuthor to set
	 */
	public void setLastCommitAuthor(String lastCommitAuthor) {
		this.lastCommitAuthor = lastCommitAuthor;
	}

	/**
	 * @param lastCommitMessage
	 *            the lastCommitMessage to set
	 */
	public void setLastCommitMessage(String lastCommitMessage) {
		this.lastCommitMessage = lastCommitMessage;
	}

	/**
	 * @param repositoryFiles
	 *            the repositoryFiles to set
	 */
	public void setRepositoryFiles(ArrayList<RepositoryFile> repositoryFiles) {
		this.repositoryFiles = repositoryFiles;
	}

	public void addRepositoryFile(RepositoryFile repositoryFile){
		if(this.repositoryFiles==null){
			this.repositoryFiles=new ArrayList<RepositoryFile>();
		}
		this.repositoryFiles.add(repositoryFile);
	}

	/**
	 * Writes the content of repository Head to JSON
	 *
	 * @param head
	 * @return
	 */
	public ObjectNode toJSON() {
		ObjectNode headJSON = Json.newObject();
		for (RepositoryFile repoFile : this.getRepositoryFiles()) {
			ObjectNode fileObjectNode = headJSON.putArray(JSONConstants.FILES)
					.addObject();

			fileObjectNode.put(JSONConstants.FILE_URL, repoFile.getFileURL());
			fileObjectNode.put(JSONConstants.FILE_CONTENT,
					repoFile.getFileContent());
		}
		headJSON.put(JSONConstants.ELAPSED_TIME, this.getElapsedTime());
		headJSON.put(JSONConstants.LAST_COMMIT, this.getLastCommit());
		headJSON.put(JSONConstants.LAST_COMMIT_MESSAGE,
				this.getLastCommitMessage());
		headJSON.put(JSONConstants.LAST_COMMIT_AUTHOR,
				this.getLastCommitAuthor());
		return headJSON;
	}

}


text:
require 'backup/files'

module Backup
  class Uploads < Files
    attr_reader :progress

    def initialize(progress)
      @progress = progress

      super('uploads', Rails.root.join('public/uploads'))
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.streamanalytics.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.streamanalytics.models.AuthenticationMode;
import com.azure.resourcemanager.streamanalytics.models.OAuthBasedDataSourceProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The properties that are associated with an Azure Data Lake Store. */
@Fluent
public final class AzureDataLakeStoreOutputDataSourceProperties extends OAuthBasedDataSourceProperties {
    @JsonIgnore
    private final ClientLogger logger = new ClientLogger(AzureDataLakeStoreOutputDataSourceProperties.class);

    /*
     * The name of the Azure Data Lake Store account. Required on PUT
     * (CreateOrReplace) requests.
     */
    @JsonProperty(value = "accountName")
    private String accountName;

    /*
     * The tenant id of the user used to obtain the refresh token. Required on
     * PUT (CreateOrReplace) requests.
     */
    @JsonProperty(value = "tenantId")
    private String tenantId;

    /*
     * The location of the file to which the output should be written to.
     * Required on PUT (CreateOrReplace) requests.
     */
    @JsonProperty(value = "filePathPrefix")
    private String filePathPrefix;

    /*
     * The date format. Wherever {date} appears in filePathPrefix, the value of
     * this property is used as the date format instead.
     */
    @JsonProperty(value = "dateFormat")
    private String dateFormat;

    /*
     * The time format. Wherever {time} appears in filePathPrefix, the value of
     * this property is used as the time format instead.
     */
    @JsonProperty(value = "timeFormat")
    private String timeFormat;

    /*
     * Authentication Mode.
     */
    @JsonProperty(value = "authenticationMode")
    private AuthenticationMode authenticationMode;

    /**
     * Get the accountName property: The name of the Azure Data Lake Store account. Required on PUT (CreateOrReplace)
     * requests.
     *
     * @return the accountName value.
     */
    public String accountName() {
        return this.accountName;
    }

    /**
     * Set the accountName property: The name of the Azure Data Lake Store account. Required on PUT (CreateOrReplace)
     * requests.
     *
     * @param accountName the accountName value to set.
     * @return the AzureDataLakeStoreOutputDataSourceProperties object itself.
     */
    public AzureDataLakeStoreOutputDataSourceProperties withAccountName(String accountName) {
        this.accountName = accountName;
        return this;
    }

    /**
     * Get the tenantId property: The tenant id of the user used to obtain the refresh token. Required on PUT
     * (CreateOrReplace) requests.
     *
     * @return the tenantId value.
     */
    public String tenantId() {
        return this.tenantId;
    }

    /**
     * Set the tenantId property: The tenant id of the user used to obtain the refresh token. Required on PUT
     * (CreateOrReplace) requests.
     *
     * @param tenantId the tenantId value to set.
     * @return the AzureDataLakeStoreOutputDataSourceProperties object itself.
     */
    public AzureDataLakeStoreOutputDataSourceProperties withTenantId(String tenantId) {
        this.tenantId = tenantId;
        return this;
    }

    /**
     * Get the filePathPrefix property: The location of the file to which the output should be written to. Required on
     * PUT (CreateOrReplace) requests.
     *
     * @return the filePathPrefix value.
     */
    public String filePathPrefix() {
        return this.filePathPrefix;
    }

    /**
     * Set the filePathPrefix property: The location of the file to which the output should be written to. Required on
     * PUT (CreateOrReplace) requests.
     *
     * @param filePathPrefix the filePathPrefix value to set.
     * @return the AzureDataLakeStoreOutputDataSourceProperties object itself.
     */
    public AzureDataLakeStoreOutputDataSourceProperties withFilePathPrefix(String filePathPrefix) {
        this.filePathPrefix = filePathPrefix;
        return this;
    }

    /**
     * Get the dateFormat property: The date format. Wherever {date} appears in filePathPrefix, the value of this
     * property is used as the date format instead.
     *
     * @return the dateFormat value.
     */
    public String dateFormat() {
        return this.dateFormat;
    }

    /**
     * Set the dateFormat property: The date format. Wherever {date} appears in filePathPrefix, the value of this
     * property is used as the date format instead.
     *
     * @param dateFormat the dateFormat value to set.
     * @return the AzureDataLakeStoreOutputDataSourceProperties object itself.
     */
    public AzureDataLakeStoreOutputDataSourceProperties withDateFormat(String dateFormat) {
        this.dateFormat = dateFormat;
        return this;
    }

    /**
     * Get the timeFormat property: The time format. Wherever {time} appears in filePathPrefix, the value of this
     * property is used as the time format instead.
     *
     * @return the timeFormat value.
     */
    public String timeFormat() {
        return this.timeFormat;
    }

    /**
     * Set the timeFormat property: The time format. Wherever {time} appears in filePathPrefix, the value of this
     * property is used as the time format instead.
     *
     * @param timeFormat the timeFormat value to set.
     * @return the AzureDataLakeStoreOutputDataSourceProperties object itself.
     */
    public AzureDataLakeStoreOutputDataSourceProperties withTimeFormat(String timeFormat) {
        this.timeFormat = timeFormat;
        return this;
    }

    /**
     * Get the authenticationMode property: Authentication Mode.
     *
     * @return the authenticationMode value.
     */
    public AuthenticationMode authenticationMode() {
        return this.authenticationMode;
    }

    /**
     * Set the authenticationMode property: Authentication Mode.
     *
     * @param authenticationMode the authenticationMode value to set.
     * @return the AzureDataLakeStoreOutputDataSourceProperties object itself.
     */
    public AzureDataLakeStoreOutputDataSourceProperties withAuthenticationMode(AuthenticationMode authenticationMode) {
        this.authenticationMode = authenticationMode;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public AzureDataLakeStoreOutputDataSourceProperties withRefreshToken(String refreshToken) {
        super.withRefreshToken(refreshToken);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public AzureDataLakeStoreOutputDataSourceProperties withTokenUserPrincipalName(String tokenUserPrincipalName) {
        super.withTokenUserPrincipalName(tokenUserPrincipalName);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public AzureDataLakeStoreOutputDataSourceProperties withTokenUserDisplayName(String tokenUserDisplayName) {
        super.withTokenUserDisplayName(tokenUserDisplayName);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
    }
}


text:
namespace blink {

PaintInvalidationState::PaintInvalidationState(const RenderView& renderView)
    : m_clipped(false)
    , m_cachedOffsetsEnabled(true)
    , m_forceCheckForPaintInvalidation(false)
    , m_paintInvalidationContainer(*renderView.containerForPaintInvalidation())
{
    bool establishesPaintInvalidationContainer = renderView == m_paintInvalidationContainer;
    if (!establishesPaintInvalidationContainer) {
        if (!renderView.supportsPaintInvalidationStateCachedOffsets()) {
            m_cachedOffsetsEnabled = false;
            return;
        }
        FloatPoint point = renderView.localToContainerPoint(FloatPoint(), &m_paintInvalidationContainer, TraverseDocumentBoundaries);
        m_paintOffset = LayoutSize(point.x(), point.y());
    }
    m_clipRect = renderView.viewRect();
    m_clipRect.move(m_paintOffset);
    m_clipped = true;
}

PaintInvalidationState::PaintInvalidationState(const PaintInvalidationState& next, RenderLayerModelObject& renderer, const RenderLayerModelObject& paintInvalidationContainer)
    : m_clipped(false)
    , m_cachedOffsetsEnabled(true)
    , m_forceCheckForPaintInvalidation(next.m_forceCheckForPaintInvalidation)
    , m_paintInvalidationContainer(paintInvalidationContainer)
{
    // FIXME: SVG could probably benefit from a stack-based optimization like html does. crbug.com/391054
    bool establishesPaintInvalidationContainer = renderer == m_paintInvalidationContainer;
    bool fixed = renderer.style()->position() == FixedPosition;

    if (establishesPaintInvalidationContainer) {
        // When we hit a new paint invalidation container, we don't need to
        // continue forcing a check for paint invalidation because movement
        // from our parents will just move the whole invalidation container.
        m_forceCheckForPaintInvalidation = false;
    } else {
        if (!renderer.supportsPaintInvalidationStateCachedOffsets() || !next.m_cachedOffsetsEnabled) {
            m_cachedOffsetsEnabled = false;
        } else {
            if (fixed) {
                FloatPoint fixedOffset = renderer.localToContainerPoint(FloatPoint(), &m_paintInvalidationContainer, TraverseDocumentBoundaries);
                m_paintOffset = LayoutSize(fixedOffset.x(), fixedOffset.y());
            } else {
                LayoutSize offset = renderer.isBox() && !renderer.isTableRow() ? toRenderBox(renderer).locationOffset() : LayoutSize();
                m_paintOffset = next.m_paintOffset + offset;
            }

            if (renderer.isOutOfFlowPositioned() && !fixed) {
                if (RenderObject* container = renderer.container()) {
                    if (container->style()->hasInFlowPosition() && container->isRenderInline())
                        m_paintOffset += toRenderInline(container)->offsetForInFlowPositionedInline(toRenderBox(renderer));
                }
            }

            if (renderer.style()->hasInFlowPosition() && renderer.hasLayer())
                m_paintOffset += renderer.layer()->offsetForInFlowPosition();
        }

        m_clipped = !fixed && next.m_clipped;
        if (m_clipped)
            m_clipRect = next.m_clipRect;
    }

    applyClipIfNeeded(renderer);

    // FIXME: <http://bugs.webkit.org/show_bug.cgi?id=13443> Apply control clip if present.
}

void PaintInvalidationState::applyClipIfNeeded(const RenderObject& renderer)
{
    if (!renderer.hasOverflowClip())
        return;

    const RenderBox& box = toRenderBox(renderer);

    // Do not clip scroll layer contents because the compositor expects the whole layer
    // to be always invalidated in-time.
    if (box.usesCompositedScrolling()) {
        ASSERT(!m_clipped); // The box should establish paint invalidation container, so no m_clipped inherited.
    } else {
        LayoutRect clipRect(toPoint(m_paintOffset), box.layer()->size());
        if (m_clipped) {
            m_clipRect.intersect(clipRect);
        } else {
            m_clipRect = clipRect;
            m_clipped = true;
        }
    }

    m_paintOffset -= box.scrolledContentOffset();
}

} // namespace blink


text:
//namespace OnlineStore
//{
//    public class Product
//    {
//        public Product(string name, double price, string product)
//        {
//            this.Name = name;
//            this.Price = price;
//            this.Producer = product;
//        }

//        public string Name { get; set; }

//        public double Price { get; set; }

//        public string Producer { get; set; }

//        public override string ToString()
//        {
//            return string.Format("{{{0};{1};{2}}}", this.Name, this.Producer, this.Price.ToString("F2"));
//        }
//    }
//}