text:
var version="9.2.1";
var active_contextmenu=true;
if (loading_bar) {
if (!(/MSIE (\d+\.\d+);/.test(navigator.userAgent))){
    window.addEventListener('DOMContentLoaded', function() {
        $("body").queryLoader2({ 'backgroundColor':'none','minimumTime':100,'percentage':true});
    });
}else{
    $(document).ready(function () {
        $("body").queryLoader2({ 'backgroundColor':'none','minimumTime':100,'percentage':true});
    });
}
}
$(document).ready(function(){
    if (active_contextmenu) {
	$.contextMenu({
	    selector: 'figure:not(.back-directory), .list-view2 figure:not(.back-directory) ',
	    autoHide:true,
	    build: function($trigger) {
		$trigger.addClass('selected');
		var options = {
		  callback: function(key, options) {
		    switch (key) {
			case "copy_url":
			    var m ="";
			    m+=$('#base_url').val()+$('#cur_dir').val();
			    add=$trigger.find('a.link').attr('data-file');
			    if (add!="" && add!=null) {
				m+=add;
			    }
			    bootbox.alert('URL:

<input type="text" style="height:30px; width:100%;" value="'+m+'" />');
			    break;
			case "unzip":
			    var m=$('#sub_folder').val()+$('#fldr_value').val()+$trigger.find('a.link').attr('data-file');
			    $.ajax({
				type: "POST",
				url: "ajax_calls.php?action=extract",
				data: { path: m }
			    }).done(function( msg ) {
				if (msg!="")
				    bootbox.alert(msg);
				else
				    window.location.href = $('#refresh').attr('href') + '&' + new Date().getTime();
			    });
			    break;
			case "edit_img":
			    var filename=$trigger.attr('data-name');
			    var full_path=$('#base_url_true').val()+$('#cur_dir').val()+filename;
			    $('#aviary_img').attr('data-name',filename);
			    $('#aviary_img').attr('src',full_path).load(launchEditor('aviary_img', full_path));

			    break;
			case "duplicate":
			    var old_name=$trigger.find('h4').text().trim();
			    bootbox.prompt($('#lang_duplicate').val(),$('#cancel').val(),$('#ok').val(), function(name) {
				if (name !== null){
				    name=clean_filename(name);
				    if (name!=old_name) {
					var _this=$trigger.find('.rename-file');
					execute_action('duplicate_file',_this.attr('data-path'),_this.attr('data-thumb'),name,_this,'apply_file_duplicate');
				    }
				}
			    },old_name);
			    break;
		    }
		  },
		  items: {}
		};
		if (($trigger.find('.img-precontainer-mini .filetype').hasClass('png') ||
		    $trigger.find('.img-precontainer-mini .filetype').hasClass('jpg') ||
		    $trigger.find('.img-precontainer-mini .filetype').hasClass('jpeg')) && image_editor )
		    options.items.edit_img = {name: $('#lang_edit_image').val(),icon:"edit_img", disabled:false };
		options.items.copy_url = {name: $('#lang_show_url').val(),icon:"url", disabled:false };
		if ($trigger.find('.img-precontainer-mini .filetype').hasClass('zip') ||
		    $trigger.find('.img-precontainer-mini .filetype').hasClass('tar') ||
		    $trigger.find('.img-precontainer-mini .filetype').hasClass('gz') ) {
		    options.items.unzip = {name: $('#lang_extract').val(),icon:"extract", disabled:false };
		}
		if (!$trigger.hasClass('directory') && $('#duplicate').val()==1) {
		    options.items.duplicate = {name: $('#lang_duplicate').val(),icon:"duplicate", disabled:false };
		}
		options.items.sep = '----';
		options.items.info = {name: ""+$('#lang_file_info').val()+"", disabled:true };
		options.items.name = {name: $trigger.attr('data-name'),icon:'label', disabled:true };
		if ($trigger.attr('data-type')=="img") {
		  options.items.dimension = {name: $trigger.find('.img-dimension').html(),icon:"dimension", disabled:true };
		}
		options.items.size = {name: $trigger.find('.file-size').html(),icon:"size", disabled:true };
		options.items.date = {name: $trigger.find('.file-date').html(),icon:"date", disabled:true };

		return options;
	      },
	      events: {
		hide: function(opt){
		  $('figure').removeClass('selected');
		}
	    }
	});

	$(document).on('contextmenu', function(e) {
	    if (!$(e.target).is("figure"))
	       return false;
	});
    }

    $('#full-img').on('click',function(){
	    $('#previewLightbox').lightbox('hide');
    });

    $('ul.grid').on('click','.modalAV', function(e) {
	_this=$(this);
        e.preventDefault();

        $('#previewAV').removeData("modal");
        $('#previewAV').modal({
            backdrop: 'static',
            keyboard: false
        });
	if (_this.hasClass('audio')) {
	    $(".body-preview").css('height','80px');
	}else{
	    $(".body-preview").css('height','345px');
	}

        $.ajax({
            url: _this.attr('data-url'),
            success: function(data) {

		$(".body-preview").html(data);
	    }
        });
    });

    $('input[name=radio-sort]').on('click',function(){
        var li=$(this).attr('data-item');
	$('.filters label').removeClass("btn-inverse");
	$('.filters label').find('i').removeClass('icon-white');
	$('#filter-input').val('');
	$('#'+li).addClass("btn-inverse");
	$('#'+li).find('i').addClass('icon-white');
        if(li=='ff-item-type-all'){
	    $('.grid li').show(300);
	}else{
            if($(this).is(':checked')){
                $('.grid li').not('.'+li).hide(300);
                $('.grid li.'+li).show(300);
            }
        }
    });

    var delay = (function(){
	var timer = 0;
	return function(callback, ms){
	    clearTimeout (timer);
	    timer = setTimeout(callback, ms);
	};
    })();

    if (parseInt($('#file_number').val()) > parseInt($('#file_number_limit_js').val())) var js_script=false;
    else var js_script=true;

    $('#filter-input').on('keyup',function(){
	$('.filters label').removeClass("btn-inverse");
	$('.filters label').find('i').removeClass('icon-white');
	$('#ff-item-type-all').addClass("btn-inverse");
	$('#ff-item-type-all').find('i').addClass('icon-white');
	var val=clean_filename($(this).val());
	$(this).val(val);
	delay(function(){
	    if (js_script) {
		$('ul.grid li').each(function(){
		    var _this = $(this);
		    if (val!="" && _this.attr('data-name').toString().toLowerCase().indexOf(val.toLowerCase())==-1) {
			_this.hide(100);
		    }else{
			_this.show(100);
		    }
		});
	    }
	}, 300 );
    }).keypress(function(e) {
	if(e.which == 13) {
	    $('#filter').trigger('click');
	}
    });

    $('#filter').on('click',function(){
	var val=clean_filename($('#filter-input').val());
	window.location.href=$('#current_url').val()+"&filter="+val;
    });

    $('#info').on('click',function(){
	bootbox.alert('

RESPONSIVE filemanager v.'+version+'
responsivefilemanager.com

Copyright © Tecrail - Alberto Peripolli. All rights reserved.

License

This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 Unported License.
');
	});

    $('#uploader-btn').on('click',function(){
	    var path=$('#sub_folder').val()+$('#fldr_value').val()+"/";
	    path=path.substring(0, path.length - 1);

	    $('#iframe-container').html($('', {
		name: 'JUpload',
		id:   'uploader_frame',
		src: "uploader/index.php?path="+path,
		frameborder: 0,
		width: "100%",
		height: 360
	    }));
	});
    $('.upload-btn').on('click',function(){
	    $('.uploader').show(500);
    });

    var sortDescending=$('#descending').val()=== 'true';
    $('.sorter').on('click',function(){
	_this=$(this);

	sortDescending=!sortDescending;
	if (js_script) {
	    $.ajax({
		url: "ajax_calls.php?action=sort&sort_by="+_this.attr('data-sort')+"&descending="+sortDescending
	    }).done(function( msg ) {

	    });
	    sortUnorderedList('ul.grid',sortDescending,"."+_this.attr('data-sort'));
	    $(' a.sorter').removeClass('descending').removeClass('ascending');
	    if (sortDescending)
		$('.sort-'+_this.attr('data-sort')).addClass("descending");
	    else
		$('.sort-'+_this.attr('data-sort')).addClass("ascending");
	}else{
	    window.location.href=$('#current_url').val()+"&sort_by="+_this.attr('data-sort')+"&descending="+sortDescending;
	}
    });

    $('.close-uploader').on('click',function(){
	    $('.uploader').hide(500);
	    window.location.href = $('#refresh').attr('href') + '&' + new Date().getTime();
    });

    $('ul.grid').on('click','.preview',function(){
	var _this = $(this);
	$('#full-img').attr('src',_this.attr('data-url'));
	if(_this.hasClass('disabled')==false){
	    show_animation();
	}
	return true;
    });

    $('ul.grid').on('click','.rename-file',function(){
	var _this = $(this);

	var file_container=_this.parent().parent().parent();
	var file_title=file_container.find('h4');
	var old_name=$.trim(file_title.text());
	bootbox.prompt($('#rename').val(),$('#cancel').val(),$('#ok').val(), function(name) {
	    if (name !== null){
		name=clean_filename(name);
		if (name!=old_name) {
		    execute_action('rename_file',_this.attr('data-path'),_this.attr('data-thumb'),name,file_container,'apply_file_rename');
		}
	    }
	},old_name);
    });

    $('ul.grid').on('click','.rename-folder',function(){
	var _this = $(this);

	var file_container=_this.parent().parent().parent();
	var file_title=file_container.find('h4');
	var old_name=$.trim(file_title.text());
	bootbox.prompt($('#rename').val(),$('#cancel').val(),$('#ok').val(), function(name) {
	    if (name !== null){
		name=clean_filename(name).replace('.','');
		if (name!=old_name) {
		    execute_action('rename_folder',_this.attr('data-path'),_this.attr('data-thumb'),name,file_container,'apply_folder_rename');
		}
	    }
	},old_name);
    });

    $('ul.grid').on('click','.delete-file',function(){
	var _this = $(this);
	bootbox.confirm(_this.attr('data-confirm'),$('#cancel').val(),$('#ok').val(), function(result) {
	    if (result==true) {
		execute_action('delete_file',_this.attr('data-path'),_this.attr('data-thumb'),'','','');
		_this.parent().parent().parent().parent().remove();
	    }
	});
    });

    $('ul.grid').on('click','.delete-folder',function(){
	var _this = $(this);

	bootbox.confirm(_this.attr('data-confirm'),$('#cancel').val(),$('#ok').val(), function(result) {
	    if (result==true) {
		execute_action('delete_folder',_this.attr('data-path'),_this.attr('data-thumb'),'','','');
		_this.parent().parent().parent().remove();
	    }
	});
    });

    $('.new-folder').on('click',function(){
	bootbox.prompt($('#insert_folder_name').val(),$('#cancel').val(),$('#ok').val(), function(name) {
	    if (name !== null) {
		name=clean_filename(name).replace('.','');
		var folder_path=$('#sub_folder').val()+$('#fldr_value').val()+ name;
		var folder_path_thumb=$('#cur_dir_thumb').val()+ name;
		$.ajax({
			  type: "POST",
			  url: "execute.php?action=create_folder",
			  data: {path: folder_path, path_thumb: folder_path_thumb}
			}).done(function( msg ) {
			setTimeout(function(){window.location.href = $('#refresh').attr('href') + '&' + new Date().getTime();},300);

		});
	    }
	},$('#new_folder').val());
    });

    $('.view-controller button').on('click',function(){
	    var _this = $(this);

	    $('.view-controller button').removeClass('btn-inverse');
	    $('.view-controller i').removeClass('icon-white');
	    _this.addClass('btn-inverse');
	    _this.find('i').addClass('icon-white');

	     $.ajax({
		url: "ajax_calls.php?action=view&type="+_this.attr('data-value')
	    }).done(function( msg ) {
		if (msg!="") {
		    bootbox.alert(msg);
		}
	    });
	    if (typeof  $('ul.grid')[0] !== "undefined" &&  $('ul.grid')[0])
		$('ul.grid')[0].className = $('ul.grid')[0].className.replace(/\blist-view.*?\b/g, '');
	    if (typeof $('.sorter-container')[0] !== "undefined" && $('.sorter-container')[0])
		$('.sorter-container')[0].className = $('.sorter-container')[0].className.replace(/\blist-view.*?\b/g, '');

	    var value=_this.attr('data-value');
	    $('#view').val(value);
	    $('ul.grid').addClass('list-view'+value);
	    $('.sorter-container').addClass('list-view'+value);
	    if (_this.attr('data-value')>=1){
		fix_colums(14);
	    }
	    else{
		$('ul.grid li').css( "width",126);
		$('ul.grid figure').css( "width",122);
	    }
	});

	if (!Modernizr.touch) {
	    $('.tip').tooltip({placement: "bottom"});
	    $('.tip-left').tooltip({placement: "left"});
	    $('.tip-right').tooltip({placement: "right"});
	    $('body').addClass('no-touch');
	}else{

	    $('#help').show();

	    //Enable swiping...
	    $(".box:not(.no-effect)").swipe( {
		    //Generic swipe handler for all directions
		    swipeLeft:swipe_reaction,
		    swipeRight:swipe_reaction,
		    //Default is 75px, set to 0 for demo so any distance triggers swipe
	       threshold:30
	    });
	}

	if(!Modernizr.csstransforms) { // Test if CSS transform are supported

		$('figure').bind('mouseover',function(){
			if ($('#view').val()==0) {
				$(this).find('.box:not(.no-effect)').animate({top: "-30px"} ,{queue:false,duration:300});
			}
		});

		$('figure').mouseout(function(){
			if ($('#view').val()==0) {
				$(this).find('.box:not(.no-effect)').animate({top: "0px"} ,{queue:false,duration:300});
			}
		});

	}

	$(window).resize(function(){fix_colums(28); });
	fix_colums(14);

	$('ul.grid').on('click','.link',function(){
		var _this = $(this);

		window[_this.attr('data-function')](_this.attr('data-file'),_this.attr('data-field_id'));
	});

});

function fix_colums(adding) {

    var width=$('.breadcrumb').width()+adding;
    $('.uploader').css('width',width);
    if($('#view').val()>0){
	if ($('#view').val()==1) {
	    $('ul.grid li, ul.grid figure').css( "width", '100%');
	}else{
	    var col=Math.floor(width/380);
	    if (col==0){
		col=1;
		$('h4').css('font-size',12);
	    }
	    width=Math.floor((width/col)-3);
	    $('ul.grid li, ul.grid figure').css( "width", width);
	}
	$('#help').hide();
    }else{if(Modernizr.touch) {
	    $('#help').show();
    }}
}

function swipe_reaction(event, direction, distance, duration, fingerCount) {
	var _this = $(this);

    if ($('#view').val()==0) {
		if (_this.attr('toggle')==1) {
			_this.attr('toggle',0);
			_this.animate({top: "0px"} ,{queue:false,duration:300});
		}else{
			_this.attr('toggle',1);
			_this.animate({top: "-30px"} ,{queue:false,duration:300});
		}

    }
}

function apply(file,external){
    if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent;
    var path = $('#cur_dir').val();
    //path = path.replace('\\', '/');
    var base_url = $('#base_url').val();
    var alt_name=file.substr(0, file.lastIndexOf('.'));
    var ext=file.split('.').pop();
    ext=ext.toLowerCase();
    var fill='';
    if($.inArray(ext, ext_img) > -1){
        fill='';
    }else{
	fill=''+alt_name+'';
    }

    parent.tinymce.activeEditor.insertContent(fill);
    parent.tinymce.activeEditor.windowManager.close();
}

function apply_link(file,external){
    if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent;
    var path = $('#cur_dir').val();
    path = path.replace('\\', '/');
    var base_url = $('#base_url').val();
    if (external!=""){
	var target = $('#'+external,window_parent.document);
	$(target).val(base_url+path+file);
	close_window();
    }
    else
	apply_any(base_url+path, file);
}

function apply_img(file,external){
    if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent;
    var path = $('#cur_dir').val();
    path = path.replace('\\', '/');
    var base_url = $('#base_url').val();

    if (external!=""){
	var target = $('#'+external, window_parent.document);
	$(target).val(base_url+path+file);
	close_window();
    }
    else
        apply_any(base_url+path, file);
}

function apply_video(file,external){
    if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent;
    var path = $('#cur_dir').val();
    path = path.replace('\\', '/');
    var base_url = $('#base_url').val();
    if (external!=""){
	var target = $('#'+external,window_parent.document);
	$(target).val(base_url+base_url+path+file);
	close_window();
    }
    else
	apply_any(path, file);
}

function apply_none(file,external){
	var _this=$('li[data-name="'+file+'"]').find('.preview');

	$('#full-img').attr('src',_this.attr('data-url'));
	if(_this.hasClass('disabled')==false){
	    show_animation();
	    $('#previewLightbox').lightbox();
	}
	return;
}

function apply_any(path, file) {
	path = path.replace('\\', '/');
	parent.tinymce.activeEditor.windowManager.getParams().setUrl(path+file);
	parent.tinymce.activeEditor.windowManager.close();
	return false;
}

function close_window() {
   if ($('#popup').val()==1) window.close();
   else{
	if ( typeof parent.jQuery !== "undefined" && parent.jQuery) {
	    parent.jQuery.fancybox.close();
	}else{
	    parent.$.fancybox.close();
	}
   }
}

function apply_file_duplicate(container,name){
    var li_container=container.parent().parent().parent().parent();
    li_container.after("
"+li_container.html()+"
");
    apply_file_rename(li_container.next(),name);
}

function apply_file_rename(container,name) {
    container.find('h4').find('a').text(name);
    //select link
    var link=container.find('a.link');
    var file=link.attr('data-file');
    var old_name=file.substring(file.lastIndexOf('/') + 1);
    var extension=file.substring(file.lastIndexOf('.') + 1);
    link.each(function(){
	$(this).attr('data-file',name+"."+extension);
	});

    //preview link
    var link2=container.find('a.preview');
    var file= link2.attr('data-url');
    if (typeof file !=="undefined" && file) {
	link2.attr('data-url',file.replace(old_name,name+"."+extension));
    }

    //li data-name
    container.parent().attr('data-name',name+"."+extension);
    container.attr('data-name',name+"."+extension);

    //download link
    container.find('.name_download').val(name+"."+extension);

    //rename link && delete link
    var link3=container.find('a.rename-file');
    var link4=container.find('a.delete-file');
    var path_old=link3.attr('data-path');
    var path_thumb=link3.attr('data-thumb');
    var new_path=path_old.replace(old_name,name+"."+extension);
    var new_thumb=path_thumb.replace(old_name,name+"."+extension);
    link3.attr('data-path',new_path);
    link3.attr('data-thumb',new_thumb);
    link4.attr('data-path',new_path);
    link4.attr('data-thumb',new_thumb);
}

function apply_folder_rename(container,name) {
    var old_name=container.find('h4').find('a').text();
    container.find('h4').find('a').text(name);

    //select link
    var link=container.find('.folder-link');
    var url=link.attr('href');
    var fldr=$('#fldr_value').val();
    link.attr('href',url.replace('fldr='+fldr+old_name,'fldr='+fldr+name));

    //rename link && delete link
    var link2=container.find('a.delete-folder');
    var link3=container.find('a.rename-folder');
    var path_old=link3.attr('data-path');
    var thumb_old=link3.attr('data-thumb');
    var index = path_old.lastIndexOf('/');
    var new_path = path_old.substr(0, index + 1)+name;
    link2.attr('data-path',new_path);
    link3.attr('data-path',new_path);
    var index = thumb_old.lastIndexOf('/');
    var new_path = thumb_old.substr(0, index + 1)+name;
    link2.attr('data-thumb',new_path);
    link3.attr('data-thumb',new_path);

}

function replace_last(str,find,replace) {
	var re= new RegExp(find+"$");
	return str.replace(re, replace);
}

function replaceDiacritics(s)
{
    var s;

    var diacritics =[
        /[\300-\306]/g, /[\340-\346]/g,  // A, a
        /[\310-\313]/g, /[\350-\353]/g,  // E, e
        /[\314-\317]/g, /[\354-\357]/g,  // I, i
        /[\322-\330]/g, /[\362-\370]/g,  // O, o
        /[\331-\334]/g, /[\371-\374]/g,  // U, u
        /[\321]/g, /[\361]/g, // N, n
        /[\307]/g, /[\347]/g, // C, c
    ];

    var chars = ['A','a','E','e','I','i','O','o','U','u','N','n','C','c'];

    for (var i = 0; i < diacritics.length; i++)
    {
        s = s.replace(diacritics[i],chars[i]);
    }

    return s;
}

function clean_filename(stri) {
    if (stri!=null) {
	strii=replaceDiacritics(stri);
	strii=strii.replace(/[^A-Za-z0-9\.\-\[\]\ \_]+/g, '');

	return $.trim(strii);
    }
    return null;
}

function execute_action(action,file1,file2,name,container,function_name){
    if (name!==null) {
	name=clean_filename(name);
	$.ajax({
	    type: "POST",
	    url: "execute.php?action="+action,
	    data: {path: file1, path_thumb: file2, name: name.replace('/','')}
	}).done(function( msg ) {
	    if (msg!="") {
		bootbox.alert(msg);
		return false;
	    }else{
		if (function_name!="") {
		    window[function_name](container,name);
		}
	    }
	    return true;
	});
    }
}

function sortUnorderedList(ul, sortDescending,sort_field) {
    if(typeof ul == "string")
      ul = $(ul);
    var lis_dir = ul.find("li.dir");
    var lis_file = ul.find("li.file");
    var vals_dir = [];
    var values_dir = [];
    var vals_file = [];
    var values_file = [];

    $.each(lis_dir,function(index){
	var _this=$(this);
	var value=_this.find(sort_field).val();
	if ($.isNumeric(value)) {
	    value=parseFloat(value);
	    while (typeof vals_dir[value] !== "undefined" &&  vals_dir[value] ) {
		value=parseFloat(parseFloat(value)+parseFloat(0.001));
	    }
	}else{
	    value=value+"a"+_this.find('h4 a').attr('data-file');
	}
	vals_dir[value]=_this.html();
	values_dir.push(value);
	});

    $.each(lis_file,function(index){
	var _this=$(this);
	var value=_this.find(sort_field).val();
	if ($.isNumeric(value)) {
	    value=parseFloat(value);
	    while (typeof vals_file[value] !== "undefined" &&  vals_file[value] ) {
		value=parseFloat(parseFloat(value)+parseFloat(0.001));
	    }
	}else{
	    value=value+"a"+_this.find('h4 a').attr('data-file');
	}
	vals_file[value]=_this.html();
	values_file.push(value);
	});

    if ($.isNumeric(values_dir[0])) {
	values_dir.sort(function(a,b){return parseFloat(a)-parseFloat(b);});
    }else{
	values_dir.sort();
    }

    if ($.isNumeric(values_file[0])) {
	values_file.sort(function(a,b){return  parseFloat(a)-parseFloat(b); });
    }else{
	values_file.sort();
    }

    if(sortDescending){
	values_dir.reverse();
	values_file.reverse();
    }

    $.each(lis_dir,function(index){
	var _this=$(this);
	_this.html(vals_dir[values_dir[index]]);
    });

    $.each(lis_file,function(index){
	var _this=$(this);
	_this.html(vals_file[values_file[index]]);
    });

}

function show_animation()
{
    $('#loading_container').css('display', 'block');
    $('#loading').css('opacity', '.7');
}

function hide_animation()
{
    $('#loading_container').fadeOut();
}

function launchEditor(id, src) {
    featherEditor.launch({
	image: id,
	url: src,
    });
   return false;
}


text:
require 'rails_helper'

describe V1::PeopleController,  type: :controller do
  describe "POST create" do
    render_views
    it "returns error without person params" do
      post :create
      json_response = JSON.parse(response.body)

      expect(json_response).to have_key('error')
      expect(json_response['error']).to eq("person is required")
    end
  end
  describe "GET show" do
    render_views
    context "with good params" do
      it "returns person object" do
        FactoryGirl.create(:person, uuid: 'the-uuid', email: 'joe@example.com')
        get :show, identifier: 'joe@example.com'
        parsed_response = JSON.parse(response.body)
        expect(parsed_response.slice('uuid', 'activities').values)
          .to eq ['the-uuid', []]
      end
    end
  end

  describe "GET targets" do

    context "with no params" do
      render_views
      it "returns error" do
        get :targets
        json_response = JSON.parse(response.body)
        expect(json_response).to have_key('error')
        expect(json_response['error']).to eq("person is required")
      end
    end

    context "invalid email" do
      render_views
      it "returns error" do
        get :targets, person: { email: 'bad' }
        json_response = JSON.parse(response.body)
        expect(json_response).to have_key('error')
        expect(json_response['error']).to eq("Email is invalid.")
      end
    end

    context "with good email" do
      render_views
      context "with no address" do
        context "with new user" do

          it "returns address required" do
            get :targets, person: { email: Faker::Internet.email }
            json_response = JSON.parse(response.body)
            expect(json_response['address_required']).to eq(true)
          end

          it "doesn't update location" do
            # not sure how to test this now, or if it's necessary

            # expect(LocationConstructor).not_to receive(:new)

            # get :targets, person: { email: 'user@example.com' }
          end

          it "sets target legislators" do
            # TODO In testing, if rendering views, there is a preformance loop when using as_json w/ jbuilder.
            # rep = instance_double("Legislator")
            # expect_any_instance_of(Person).to receive(:target_legislators).
            #   with(json: true).and_return([rep])
            # get :targets, person: { email: 'user@example.com' }
            # json_response = JSON.parse(response.body)
            # expect(json_response['target_legislators'][0]['description']).to eq "Legislator (instance)"
          end
        end

        context "with existing user with address info" do
          it "returns address not required" do
            FactoryGirl.create(:person, :with_district, email: 'user@example.com')
            get :targets, person: { email: 'user@example.com' }

            json_response = JSON.parse(response.body)
            expect(json_response['address_required']).to be false
          end
        end

      end

      context "good address" do

        it "updates location" do
          person  = create(:person)
          state = create(:state)

          get :targets,
            person: { email: person.email, address: 'address', city: 'city',
                      state_abbrev: state.abbrev }

          person.reload
          expect(person.location.attributes).to include('address_1' => 'address',
                                                        'city' => 'city',
                                                        'state_id' => state.id)
        end
      end
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
hostname := nexus

include ../shared/Makefile.vars
include ../shared/Makefile

container:
	sudo docker run -d --name=$(container_name) -p=$(IP):8081:8081 $(tag)
	sleep 10
	sudo docker logs $(container_name)
	echo
	echo "Nexus will be available at http://$(IP):8081"


text:
/**
 * @file setImmediate
 *
 * @author Leo Wang(wangkemiao@baidu.com)
 */

define(function (require) {
    var _ = require('underscore');

    /**
     * setImmediate的封装
     * IE10~11下window.setImmediate如果使用时的this值得不是window,就会抛出异常
     * @class setImmediate
     */
    if (require('./browser').getBrowser() === 'IE' && window.setImmediate) {
        window.setImmediate = _.bind(window.setImmediate, window);
    }
    return _.bind(require('promise/setImmediate'), window);
});


text:
package org.atrzaska.rsi2.mashup.string;

public class RemoveNumbersTransform implements IStringTransform {
    public String applyTransform(String input) {
        String output = input;

        output = output.replace("1", "");
        output = output.replace("2", "");
        output = output.replace("3", "");
        output = output.replace("4", "");
        output = output.replace("5", "");
        output = output.replace("6", "");
        output = output.replace("7", "");
        output = output.replace("8", "");
        output = output.replace("9", "");
        output = output.replace("0", "");

        return output;
    }

}


text:
'use strict';

var invariant = require('fbjs/lib/invariant');

var injected = false;

var ReactComponentEnvironment = {

  /**
   * Optionally injectable environment dependent cleanup hook. (server vs.
   * browser etc). Example: A browser system caches DOM nodes based on component
   * ID and must remove that cache entry when this instance is unmounted.
   */
  unmountIDFromEnvironment: null,

  /**
   * Optionally injectable hook for swapping out mount images in the middle of
   * the tree.
   */
  replaceNodeWithMarkup: null,

  /**
   * Optionally injectable hook for processing a queue of child updates. Will
   * later move into MultiChildComponents.
   */
  processChildrenUpdates: null,

  injection: {
    injectEnvironment: function (environment) {
      !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : void 0;
      ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
      ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup;
      ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
      injected = true;
    }
  }

};

module.exports = ReactComponentEnvironment;


text:
dojo.provide("dojo.flash");

dojo.require("dojo.string.*");
dojo.require("dojo.uri.*");

/**
		The goal of dojo.flash is to make it easy to extend Flash's capabilities
		into an AJAX/DHTML environment. Robust, performant, reliable
		JavaScript/Flash communication is harder than most realize when they
		delve into the topic, especially if you want it
		to work on Internet Explorer, Firefox, and Safari, and to be able to
		push around hundreds of K of information quickly. Dojo.flash makes it
		possible to support these platforms; you have to jump through a few
		hoops to get its capabilites, but if you are a library writer
		who wants to bring Flash's storage or streaming sockets ability into
		DHTML, for example, then dojo.flash is perfect for you.

		Dojo.flash provides an easy object for interacting with the Flash plugin.
		This object provides methods to determine the current version of the Flash
		plugin (dojo.flash.info); execute Flash instance methods
		independent of the Flash version
		being used (dojo.flash.comm); write out the necessary markup to
		dynamically insert a Flash object into the page (dojo.flash.Embed; and
		do dynamic installation and upgrading of the current Flash plugin in
		use (dojo.flash.Install).

		To use dojo.flash, you must first wait until Flash is finished loading
		and initializing before you attempt communication or interaction.
		To know when Flash is finished use dojo.event.connect:

		dojo.event.connect(dojo.flash, "loaded", myInstance, "myCallback");

		Then, while the page is still loading provide the file name
		and the major version of Flash that will be used for Flash/JavaScript
		communication (see "Flash Communication" below for information on the
		different kinds of Flash/JavaScript communication supported and how they
		depend on the version of Flash installed):

		dojo.flash.setSwf({flash6: "src/storage/storage_flash6.swf",
											 flash8: "src/storage/storage_flash8.swf"});

		This will cause dojo.flash to pick the best way of communicating
		between Flash and JavaScript based on the platform.

		If no SWF files are specified, then Flash is not initialized.

		Your Flash must use DojoExternalInterface to expose Flash methods and
		to call JavaScript; see "Flash Communication" below for details.

		setSwf can take an optional 'visible' attribute to control whether
		the Flash object is visible or not on the page; the default is visible:

		dojo.flash.setSwf({flash6: "src/storage/storage_flash6.swf",
											 flash8: "src/storage/storage_flash8.swf",
											 visible: false});

		Once finished, you can query Flash version information:

		dojo.flash.info.version

		Or can communicate with Flash methods that were exposed:

		var results = dojo.flash.comm.sayHello("Some Message");

		Only string values are currently supported for both arguments and
		for return results. Everything will be cast to a string on both
		the JavaScript and Flash sides.

		-------------------
		Flash Communication
		-------------------

		dojo.flash allows Flash/JavaScript communication in
		a way that can pass large amounts of data back and forth reliably and
		very fast. The dojo.flash
		framework encapsulates the specific way in which this communication occurs,
		presenting a common interface to JavaScript irrespective of the underlying
		Flash version.

		There are currently three major ways to do Flash/JavaScript communication
		in the Flash community:

		1) Flash 6+ - Uses Flash methods, such as SetVariable and TCallLabel,
		and the fscommand handler to do communication. Strengths: Very fast,
		mature, and can send extremely large amounts of data; can do
		synchronous method calls. Problems: Does not work on Safari; works on
		Firefox/Mac OS X only if Flash 8 plugin is installed; cryptic to work with.

		2) Flash 8+ - Uses ExternalInterface, which provides a way for Flash
		methods to register themselves for callbacks from JavaScript, and a way
		for Flash to call JavaScript. Strengths: Works on Safari; elegant to
		work with; can do synchronous method calls. Problems: Extremely buggy
		(fails if there are new lines in the data, for example); performance
		degrades drastically in O(n^2) time as data grows; locks up the browser while
		it is communicating; does not work in Internet Explorer if Flash
		object is dynamically added to page with document.writeln, DOM methods,
		or innerHTML.

		3) Flash 6+ - Uses two seperate Flash applets, one that we
		create over and over, passing input data into it using the PARAM tag,
		which then uses a Flash LocalConnection to pass the data to the main Flash
		applet; communication back to Flash is accomplished using a getURL
		call with a javascript protocol handler, such as "javascript:myMethod()".
		Strengths: the most cross browser, cross platform pre-Flash 8 method
		of Flash communication known; works on Safari. Problems: Timing issues;
		clunky and complicated; slow; can only send very small amounts of
		data (several K); all method calls are asynchronous.

		dojo.flash.comm uses only the first two methods. This framework
		was created primarily for dojo.storage, which needs to pass very large
		amounts of data synchronously and reliably across the Flash/JavaScript
		boundary. We use the first method, the Flash 6 method, on all platforms
		that support it, while using the Flash 8 ExternalInterface method
		only on Safari with some special code to help correct ExternalInterface's
		bugs.

		Since dojo.flash needs to have two versions of the Flash
		file it wants to generate, a Flash 6 and a Flash 8 version to gain
		true cross-browser compatibility, several tools are provided to ease
		development on the Flash side.

		In your Flash file, if you want to expose Flash methods that can be
		called, use the DojoExternalInterface class to register methods. This
		class is an exact API clone of the standard ExternalInterface class, but
		can work in Flash 6+ browsers. Under the covers it uses the best
		mechanism to do communication:

		class HelloWorld{
			function HelloWorld(){
				// Initialize the DojoExternalInterface class
				DojoExternalInterface.initialize();

				// Expose your methods
				DojoExternalInterface.addCallback("sayHello", this, this.sayHello);

				// Tell JavaScript that you are ready to have method calls
				DojoExternalInterface.loaded();

				// Call some JavaScript
				var resultsReady = function(results){
					trace("Received the following results from JavaScript: " + results);
				}
				DojoExternalInterface.call("someJavaScriptMethod", resultsReady,
																	 someParameter);
			}

			function sayHello(){ ... }

			static main(){ ... }
		}

		DojoExternalInterface adds two new functions to the ExternalInterface
		API: initialize() and loaded(). initialize() must be called before
		any addCallback() or call() methods are run, and loaded() must be
		called after you are finished adding your callbacks. Calling loaded()
		will fire the dojo.flash.loaded() event, so that JavaScript can know that
		Flash has finished loading and adding its callbacks, and can begin to
		interact with the Flash file.

		To generate your SWF files, use the ant task
		"buildFlash". You must have the open source Motion Twin ActionScript
		compiler (mtasc) installed and in your path to use the "buildFlash"
		ant task; download and install mtasc from http://www.mtasc.org/.

		buildFlash usage:

		ant buildFlash -Ddojo.flash.file=../tests/flash/HelloWorld.as

		where "dojo.flash.file" is the relative path to your Flash
		ActionScript file.

		This will generate two SWF files, one ending in _flash6.swf and the other
		ending in _flash8.swf in the same directory as your ActionScript method:

		HelloWorld_flash6.swf
		HelloWorld_flash8.swf

		Initialize dojo.flash with the filename and Flash communication version to
		use during page load; see the documentation for dojo.flash for details:

		dojo.flash.setSwf({flash6: "tests/flash/HelloWorld_flash6.swf",
											 flash8: "tests/flash/HelloWorld_flash8.swf"});

		Now, your Flash methods can be called from JavaScript as if they are native
		Flash methods, mirrored exactly on the JavaScript side:

		dojo.flash.comm.sayHello();

		Only Strings are supported being passed back and forth currently.

		JavaScript to Flash communication is synchronous; i.e., results are returned
		directly from the method call:

		var results = dojo.flash.comm.sayHello();

		Flash to JavaScript communication is asynchronous due to limitations in
		the underlying technologies; you must use a results callback to handle
		results returned by JavaScript in your Flash AS files:

		var resultsReady = function(results){
			trace("Received the following results from JavaScript: " + results);
		}
		DojoExternalInterface.call("someJavaScriptMethod", resultsReady);

		-------------------
		Notes
		-------------------

		If you have both Flash 6 and Flash 8 versions of your file:

		dojo.flash.setSwf({flash6: "tests/flash/HelloWorld_flash6.swf",
											 flash8: "tests/flash/HelloWorld_flash8.swf"});

		but want to force the browser to use a certain version of Flash for
		all platforms (for testing, for example), use the djConfig
		variable 'forceFlashComm' with the version number to force:

		var djConfig = { forceFlashComm: 6 };

		Two values are currently supported, 6 and 8, for the two styles of
		communication described above. Just because you force dojo.flash
		to use a particular communication style is no guarantee that it will
		work; for example, Flash 8 communication doesn't work in Internet
		Explorer due to bugs in Flash, and Flash 6 communication does not work
		in Safari. It is best to let dojo.flash determine the best communication
		mechanism, and to use the value above only for debugging the dojo.flash
		framework itself.

		Also note that dojo.flash can currently only work with one Flash object
		on the page; it and the API do not yet support multiple Flash objects on
		the same page.

		We use some special tricks to get decent, linear performance
		out of Flash 8's ExternalInterface on Safari; see the blog
		post
		http://codinginparadise.org/weblog/2006/02/how-to-speed-up-flash-8s.html
		for details.

		Your code can detect whether the Flash player is installing or having
		its version revved in two ways. First, if dojo.flash detects that
		Flash installation needs to occur, it sets dojo.flash.info.installing
		to true. Second, you can detect if installation is necessary with the
		following callback:

		dojo.event.connect(dojo.flash, "installing", myInstance, "myCallback");

		You can use this callback to delay further actions that might need Flash;
		when installation is finished the full page will be refreshed and the
		user will be placed back on your page with Flash installed.

		Two utility methods exist if you want to add loading and installing
		listeners without creating dependencies on dojo.event; these are
		'addLoadingListener' and 'addInstallingListener'.

		-------------------
		Todo/Known Issues
		-------------------

		There are several tasks I was not able to do, or did not need to fix
		to get dojo.storage out:

		* When using Flash 8 communication, Flash method calls to JavaScript
		are not working properly; serialization might also be broken for certain
		invalid characters when it is Flash invoking JavaScript methods.
		The Flash side needs to have more sophisticated serialization/
		deserialization mechanisms like JavaScript currently has. The
		test_flash2.html unit tests should also be updated to have much more
		sophisticated Flash to JavaScript unit tests, including large
		amounts of data.

		* On Internet Explorer, after doing a basic install, the page is
		not refreshed or does not detect that Flash is now available. The way
		to fix this is to create a custom small Flash file that is pointed to
		during installation; when it is finished loading, it does a callback
		that says that Flash installation is complete on IE, and we can proceed
		to initialize the dojo.flash subsystem.

		@author Brad Neuberg, bkn3@columbia.edu
*/

dojo.flash = {
	flash6_version: null,
	flash8_version: null,
	ready: false,
	_visible: true,
	_loadedListeners: new Array(),
	_installingListeners: new Array(),

	/** Sets the SWF files and versions we are using. */
	setSwf: function(fileInfo){
		//dojo.debug("setSwf");
		if(fileInfo == null || dojo.lang.isUndefined(fileInfo)){
			return;
		}

		if(fileInfo.flash6 != null && !dojo.lang.isUndefined(fileInfo.flash6)){
			this.flash6_version = fileInfo.flash6;
		}

		if(fileInfo.flash8 != null && !dojo.lang.isUndefined(fileInfo.flash8)){
			this.flash8_version = fileInfo.flash8;
		}

		if(!dojo.lang.isUndefined(fileInfo.visible)){
			this._visible = fileInfo.visible;
		}

		// initialize ourselves
		this._initialize();
	},

	/** Returns whether we are using Flash 6 for communication on this platform. */
	useFlash6: function(){
		if(this.flash6_version == null){
			return false;
		}else if (this.flash6_version != null && dojo.flash.info.commVersion == 6){
			// if we have a flash 6 version of this SWF, and this browser supports
			// communicating using Flash 6 features...
			return true;
		}else{
			return false;
		}
	},

	/** Returns whether we are using Flash 8 for communication on this platform. */
	useFlash8: function(){
		if(this.flash8_version == null){
			return false;
		}else if (this.flash8_version != null && dojo.flash.info.commVersion == 8){
			// if we have a flash 8 version of this SWF, and this browser supports
			// communicating using Flash 8 features...
			return true;
		}else{
			return false;
		}
	},

	/** Adds a listener to know when Flash is finished loading.
			Useful if you don't want a dependency on dojo.event. */
	addLoadedListener: function(listener){
		this._loadedListeners.push(listener);
	},

	/** Adds a listener to know if Flash is being installed.
			Useful if you don't want a dependency on dojo.event. */
	addInstallingListener: function(listener){
		this._installingListeners.push(listener);
	},

	/**
			A callback when the Flash subsystem is finished loading and can be
			worked with. To be notified when Flash is finished loading, connect
			your callback to this method using the following:

			dojo.event.connect(dojo.flash, "loaded", myInstance, "myCallback");
	*/
	loaded: function(){
		//dojo.debug("dojo.flash.loaded");
		dojo.flash.ready = true;
		if(dojo.flash._loadedListeners.length > 0){
			for(var i = 0;i < dojo.flash._loadedListeners.length; i++){
				dojo.flash._loadedListeners[i].call(null);
			}
		}
	},

	/**
			A callback to know if Flash is currently being installed or
			having its version revved. To be notified if Flash is installing, connect
			your callback to this method using the following:

			dojo.event.connect(dojo.flash, "installing", myInstance, "myCallback");
	*/
	installing: function(){
	 //dojo.debug("installing");
	 if(dojo.flash._installingListeners.length > 0){
			for(var i = 0; i < dojo.flash._installingListeners.length; i++){
				dojo.flash._installingListeners[i].call(null);
			}
		}
	},

	/** Initializes dojo.flash. */
	_initialize: function(){
		//dojo.debug("dojo.flash._initialize");
		// see if we need to rev or install Flash on this platform
		var installer = new dojo.flash.Install();
		dojo.flash.installer = installer;

		if(installer.needed() == true){
			installer.install();
		}else{
			//dojo.debug("Writing object out");
			// write the flash object into the page
			dojo.flash.obj = new dojo.flash.Embed(this._visible);
			dojo.flash.obj.write(dojo.flash.info.commVersion);

			// initialize the way we do Flash/JavaScript communication
			dojo.flash.comm = new dojo.flash.Communicator();
		}
	}
};

/**
		A class that helps us determine whether Flash is available,
		it's major and minor versions, and what Flash version features should
		be used for Flash/JavaScript communication. Parts of this code
		are adapted from the automatic Flash plugin detection code autogenerated
		by the Macromedia Flash 8 authoring environment.

		An instance of this class can be accessed on dojo.flash.info after
		the page is finished loading.

		This constructor must be called before the page is finished loading.
*/
dojo.flash.Info = function(){
	// Visual basic helper required to detect Flash Player ActiveX control
	// version information on Internet Explorer
	if(dojo.render.html.ie){
		document.writeln('<script language="VBScript" type="text/vbscript"\>');
		document.writeln('Function VBGetSwfVer(i)');
		document.writeln('  on error resume next');
		document.writeln('  Dim swControl, swVersion');
		document.writeln('  swVersion = 0');
		document.writeln('  set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))');
		document.writeln('  if (IsObject(swControl)) then');
		document.writeln('    swVersion = swControl.GetVariable("$version")');
		document.writeln('  end if');
		document.writeln('  VBGetSwfVer = swVersion');
		document.writeln('End Function');
		document.writeln('</script\>');
	}

	this._detectVersion();
	this._detectCommunicationVersion();
}

dojo.flash.Info.prototype = {
	/** The full version string, such as "8r22". */
	version: -1,

	/**
			The major, minor, and revisions of the plugin. For example, if the
			plugin is 8r22, then the major version is 8, the minor version is 0,
			and the revision is 22.
	*/
	versionMajor: -1,
	versionMinor: -1,
	versionRevision: -1,

	/** Whether this platform has Flash already installed. */
	capable: false,

	/**
			The major version number for how our Flash and JavaScript communicate.
			This can currently be the following values:
			6 - We use a combination of the Flash plugin methods, such as SetVariable
			and TCallLabel, along with fscommands, to do communication.
			8 - We use the ExternalInterface API.
			-1 - For some reason neither method is supported, and no communication
			is possible.
	*/
	commVersion: 6,

	/** Set if we are in the middle of a Flash installation session. */
	installing: false,

	/**
			Asserts that this environment has the given major, minor, and revision
			numbers for the Flash player. Returns true if the player is equal
			or above the given version, false otherwise.

			Example: To test for Flash Player 7r14:

			dojo.flash.info.isVersionOrAbove(7, 0, 14)
	*/
	isVersionOrAbove: function(reqMajorVer, reqMinorVer, reqVer){
		// make the revision a decimal (i.e. transform revision 14 into
		// 0.14
		reqVer = parseFloat("." + reqVer);

		if(this.versionMajor >= reqMajorVer && this.versionMinor >= reqMinorVer
			 && this.versionRevision >= reqVer){
			return true;
		}else{
			return false;
		}
	},

	_detectVersion: function(){
		var versionStr;

		// loop backwards through the versions until we find the newest version
		for(var testVersion = 25; testVersion > 0; testVersion--){
			if(dojo.render.html.ie){
				versionStr = VBGetSwfVer(testVersion);
			}else{
				versionStr = this._JSFlashInfo(testVersion);
			}

			if(versionStr == -1 ){
				this.capable = false;
				return;
			}else if(versionStr != 0){
				var versionArray;
				if(dojo.render.html.ie){
					var tempArray = versionStr.split(" ");
					var tempString = tempArray[1];
					versionArray = tempString.split(",");
				}else{
					versionArray = versionStr.split(".");
				}

				this.versionMajor = versionArray[0];
				this.versionMinor = versionArray[1];
				this.versionRevision = versionArray[2];

				// 7.0r24 == 7.24
				var versionString = this.versionMajor + "." + this.versionRevision;
				this.version = parseFloat(versionString);

				this.capable = true;

				break;
			}
		}
	},

	/**
			JavaScript helper required to detect Flash Player PlugIn version
			information. Internet Explorer uses a corresponding Visual Basic
			version to interact with the Flash ActiveX control.
	*/
	_JSFlashInfo: function(testVersion){
		// NS/Opera version >= 3 check for Flash plugin in plugin array
		if(navigator.plugins != null && navigator.plugins.length > 0){
			if(navigator.plugins["Shockwave Flash 2.0"] ||
				 navigator.plugins["Shockwave Flash"]){
				var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
				var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
				var descArray = flashDescription.split(" ");
				var tempArrayMajor = descArray[2].split(".");
				var versionMajor = tempArrayMajor[0];
				var versionMinor = tempArrayMajor[1];
				if(descArray[3] != ""){
					var tempArrayMinor = descArray[3].split("r");
				}else{
					var tempArrayMinor = descArray[4].split("r");
				}
				var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
				var version = versionMajor + "." + versionMinor + "."
											+ versionRevision;

				return version;
			}
		}

		return -1;
	},

	/**
			Detects the mechanisms that should be used for Flash/JavaScript
			communication, setting 'commVersion' to either 6 or 8. If the value is
			6, we use Flash Plugin 6+ features, such as GetVariable, TCallLabel,
			and fscommand, to do Flash/JavaScript communication; if the value is
			8, we use the ExternalInterface API for communication.
	*/
	_detectCommunicationVersion: function(){
		if(this.capable == false){
			this.commVersion = null;
			return;
		}

		// detect if the user has over-ridden the default flash version
		if (typeof djConfig["forceFlashComm"] != "undefined" &&
				typeof djConfig["forceFlashComm"] != null){
			this.commVersion = djConfig["forceFlashComm"];
			return;
		}

		// we prefer Flash 6 features over Flash 8, because they are much faster
		// and much less buggy

		// at this point, we don't have a flash file to detect features on,
		// so we need to instead look at the browser environment we are in
		if(dojo.render.html.safari == true || dojo.render.html.opera == true){
			this.commVersion = 8;
		}else{
			this.commVersion = 6;
		}
	}
};

/** A class that is used to write out the Flash object into the page. */
dojo.flash.Embed = function(visible){
	this._visible = visible;
}

dojo.flash.Embed.prototype = {
	/**
			The width of this Flash applet. The default is the minimal width
			necessary to show the Flash settings dialog.
	*/
	width: 215,

	/**
			The height of this Flash applet. The default is the minimal height
			necessary to show the Flash settings dialog.
	*/
	height: 138,

	/** The id of the Flash object. */
	id: "flashObject",

	/** Controls whether this is a visible Flash applet or not. */
	_visible: true,

	/**
			Writes the Flash into the page. This must be called before the page
			is finished loading.
			@param flashVer The Flash version to write.
			@param doExpressInstall Whether to write out Express Install
			information. Optional value; defaults to false.
	*/
	write: function(flashVer, doExpressInstall){
		//dojo.debug("write");
		if(dojo.lang.isUndefined(doExpressInstall)){
			doExpressInstall = false;
		}

		// determine our container div's styling
		var containerStyle = new dojo.string.Builder();
		containerStyle.append("width: " + this.width + "px; ");
		containerStyle.append("height: " + this.height + "px; ");
		if(this._visible == false){
			containerStyle.append("position: absolute; ");
			containerStyle.append("z-index: 10000; ");
			containerStyle.append("top: -1000px; ");
			containerStyle.append("left: -1000px; ");
		}
		containerStyle = containerStyle.toString();

		// figure out the SWF file to get and how to write out the correct HTML
		// for this Flash version
		var objectHTML;
		var swfloc;
		// Flash 6
		if(flashVer == 6){
			swfloc = dojo.flash.flash6_version;
			var dojoPath = djConfig.baseRelativePath;
			swfloc = swfloc + "?baseRelativePath=" + escape(dojoPath);

			objectHTML =
						  '<embed id="' + this.id + '" src="' + swfloc + '" '
						+ '    quality="high" bgcolor="#ffffff" '
						+ '    width="' + this.width + '" height="' + this.height + '" '
						+ '    name="' + this.id + '" '
						+ '    align="middle" allowScriptAccess="sameDomain" '
						+ '    type="application/x-shockwave-flash" swLiveConnect="true" '
						+ '    pluginspage="http://www.macromedia.com/go/getflashplayer">';
		}else{ // Flash 8
			swfloc = dojo.flash.flash8_version;
			var swflocObject = swfloc;
			var swflocEmbed = swfloc;
			var dojoPath = djConfig.baseRelativePath;
			if(doExpressInstall){
				// the location to redirect to after installing
				var redirectURL = escape(window.location);
				document.title = document.title.slice(0, 47) + " - Flash Player Installation";
				var docTitle = escape(document.title);
				swflocObject += "?MMredirectURL=" + redirectURL
				                + "&MMplayerType=ActiveX"
				                + "&MMdoctitle=" + docTitle
								+ "&baseRelativePath=" + escape(dojoPath);
				swflocEmbed += "?MMredirectURL=" + redirectURL
								+ "&MMplayerType=PlugIn"
								+ "&baseRelativePath=" + escape(dojoPath);
			}

			objectHTML =
				'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '
				  + 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" '
				  + 'width="' + this.width + '" '
				  + 'height="' + this.height + '" '
				  + 'id="' + this.id + '" '
				  + 'align="middle"> '
				  + '<param name="allowScriptAccess" value="sameDomain" /> '
				  + '<param name="movie" value="' + swflocObject + '" /> '
				  + '<param name="quality" value="high" /> '
				  + '<param name="bgcolor" value="#ffffff" /> '
				  + '<embed src="' + swflocEmbed + '" '
				  + 'quality="high" '
				  + 'bgcolor="#ffffff" '
				  + 'width="' + this.width + '" '
				  + 'height="' + this.height + '" '
				  + 'id="' + this.id + '" '
				  + 'name="' + this.id + '" '
				  + 'swLiveConnect="true" '
				  + 'align="middle" '
				  + 'allowScriptAccess="sameDomain" '
				  + 'type="application/x-shockwave-flash" '+ "&baseRelativePath=" + escape(dojoPath);
				  + 'pluginspage="http://www.macromedia.com/go/getflashplayer" />'
				+ '</object>';
		}

		// now write everything out
		objectHTML = '<div id="' + this.id + 'Container" style="' + containerStyle + '"> '
						+ objectHTML
					 + '</div>';
		document.writeln(objectHTML);
	},

	/** Gets the Flash object DOM node. */
	get: function(){
		//return (dojo.render.html.ie) ? window[this.id] : document[this.id];

		// more robust way to get Flash object; version above can break
		// communication on IE sometimes
		return document.getElementById(this.id);
	},

	/** Sets the visibility of this Flash object. */
	setVisible: function(visible){
		var container = dojo.byId(this.id + "Container");
		if(visible == true){
			container.style.visibility = "visible";
		}else{
			container.style.position = "absolute";
			container.style.x = "-1000px";
			container.style.y = "-1000px";
			container.style.visibility = "hidden";
		}
	},

	/** Centers the flash applet on the page. */
	center: function(){
		// FIXME: replace this with Dojo's centering code rather than our own
		// We want to center the Flash applet vertically and horizontally
		var elementWidth = this.width;
		var elementHeight = this.height;

		// get the browser width and height; the code below
		// works in IE and Firefox in compatibility, non-strict
		// mode
		var browserWidth = document.body.clientWidth;
		var browserHeight = document.body.clientHeight;

		// in Firefox if we are in standards compliant mode
		// (with a strict doctype), then the browser width
		// and height have to be computed from the root level
		// HTML element not the BODY element
		if(!dojo.render.html.ie && document.compatMode == "CSS1Compat"){
			browserWidth = document.body.parentNode.clientWidth;
			browserHeight = document.body.parentNode.clientHeight;
		}else if(dojo.render.html.ie && document.compatMode == "CSS1Compat"){
			// IE 6 in standards compliant mode has to be calculated
			// differently
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
		}else if(dojo.render.html.safari){ // Safari works different
			browserHeight = self.innerHeight;
		}

		// get where we are scrolled to in the document
		// the code below works in FireFox
		var scrolledByWidth = window.scrollX;
		var scrolledByHeight = window.scrollY;
		// compute these values differently for IE;
		// IE has two possibilities; it is either in standards
		// compatibility mode or it is not
		if(typeof scrolledByWidth == "undefined"){
			if(document.compatMode == "CSS1Compat"){ // standards mode
				scrolledByWidth = document.documentElement.scrollLeft;
				scrolledByHeight = document.documentElement.scrollTop;
			}else{ // Pre IE6 non-standards mode
				scrolledByWidth = document.body.scrollLeft;
				scrolledByHeight = document.body.scrollTop;
			}
		}

		// compute the centered position
		var x = scrolledByWidth + (browserWidth - elementWidth) / 2;
		var y = scrolledByHeight + (browserHeight - elementHeight) / 2;

		// set the centered position
		var container = dojo.byId(this.id + "Container");
		container.style.top = y + "px";
		container.style.left = x + "px";
	}
};

/**
		A class that is used to communicate between Flash and JavaScript in
		a way that can pass large amounts of data back and forth reliably,
		very fast, and with synchronous method calls. This class encapsulates the
		specific way in which this communication occurs,
		presenting a common interface to JavaScript irrespective of the underlying
		Flash version.
*/
dojo.flash.Communicator = function(){
	if(dojo.flash.useFlash6()){
		this._writeFlash6();
	}else if (dojo.flash.useFlash8()){
		this._writeFlash8();
	}
}

dojo.flash.Communicator.prototype = {
	_writeFlash6: function(){
		var id = dojo.flash.obj.id;

		// global function needed for Flash 6 callback;
		// we write it out as a script tag because the VBScript hook for IE
		// callbacks does not work properly if this function is evalled() from
		// within the Dojo system
		document.writeln('<script language="JavaScript">');
		document.writeln('  function ' + id + '_DoFSCommand(command, args){ ');
		document.writeln('    dojo.flash.comm._handleFSCommand(command, args); ');
		document.writeln('}');
		document.writeln('</script>');

		// hook for Internet Explorer to receive FSCommands from Flash
		if(dojo.render.html.ie){
			document.writeln('<SCRIPT LANGUAGE=VBScript\> ');
			document.writeln('on error resume next ');
			document.writeln('Sub ' + id + '_FSCommand(ByVal command, ByVal args)');
			document.writeln(' call ' + id + '_DoFSCommand(command, args)');
			document.writeln('end sub');
			document.writeln('</SCRIPT\> ');
		}
	},

	_writeFlash8: function(){
		// nothing needs to be written out for Flash 8 communication;
		// happens automatically
	},

	/** Flash 6 communication. */

	/** Handles fscommand's from Flash to JavaScript. Flash 6 communication. */
	_handleFSCommand: function(command, args){
		//dojo.debug("fscommand, command="+command+", args="+args);
		// Flash 8 on Mac/Firefox precedes all commands with the string "FSCommand:";
		// strip it off if it is present
		if(command != null && !dojo.lang.isUndefined(command)
			&& /^FSCommand:(.*)/.test(command) == true){
			command = command.match(/^FSCommand:(.*)/)[1];
		}

		if(command == "addCallback"){ // add Flash method for JavaScript callback
			this._fscommandAddCallback(command, args);
		}else if(command == "call"){ // Flash to JavaScript method call
			this._fscommandCall(command, args);
		}else if(command == "fscommandReady"){ // see if fscommands are ready
			this._fscommandReady();
		}
	},

	/** Handles registering a callable Flash function. Flash 6 communication. */
	_fscommandAddCallback: function(command, args){
		var functionName = args;

		// do a trick, where we link this function name to our wrapper
		// function, _call, that does the actual JavaScript to Flash call
		var callFunc = function(){
			return dojo.flash.comm._call(functionName, arguments);
		};
		dojo.flash.comm[functionName] = callFunc;

		// indicate that the call was successful
		dojo.flash.obj.get().SetVariable("_succeeded", true);
	},

	/** Handles Flash calling a JavaScript function. Flash 6 communication. */
	_fscommandCall: function(command, args){
		var plugin = dojo.flash.obj.get();
		var functionName = args;

		// get the number of arguments to this method call and build them up
		var numArgs = parseInt(plugin.GetVariable("_numArgs"));
		var flashArgs = new Array();
		for(var i = 0; i < numArgs; i++){
			var currentArg = plugin.GetVariable("_" + i);
			flashArgs.push(currentArg);
		}

		// get the function instance; we technically support more capabilities
		// than ExternalInterface, which can only call global functions; if
		// the method name has a dot in it, such as "dojo.flash.loaded", we
		// eval it so that the method gets run against an instance
		var runMe;
		if(functionName.indexOf(".") == -1){ // global function
			runMe = window[functionName];
		}else{
			// instance function
			runMe = eval(functionName);
		}

		// make the call and get the results
		var results = null;
		if(!dojo.lang.isUndefined(runMe) && runMe != null){
			results = runMe.apply(null, flashArgs);
		}

		// return the results to flash
		plugin.SetVariable("_returnResult", results);
	},

	/** Reports that fscommands are ready to run if executed from Flash. */
	_fscommandReady: function(){
		var plugin = dojo.flash.obj.get();
		plugin.SetVariable("fscommandReady", "true");
	},

	/**
			The actual function that will execute a JavaScript to Flash call; used
			by the Flash 6 communication method.
	*/
	_call: function(functionName, args){
		// we do JavaScript to Flash method calls by setting a Flash variable
		// "_functionName" with the function name; "_numArgs" with the number
		// of arguments; and "_0", "_1", etc for each numbered argument. Flash
		// reads these, executes the function call, and returns the result
		// in "_returnResult"
		var plugin = dojo.flash.obj.get();
		plugin.SetVariable("_functionName", functionName);
		plugin.SetVariable("_numArgs", args.length);
		for(var i = 0; i < args.length; i++){
			// unlike Flash 8's ExternalInterface, Flash 6 has no problem with
			// any special characters _except_ for the null character \0; double
			// encode this so the Flash side never sees it, but we can get it
			// back if the value comes back to JavaScript
			var value = args[i];
			value = value.replace(/\0/g, "\\0");

			plugin.SetVariable("_" + i, value);
		}

		// now tell Flash to execute this method using the Flash Runner
		plugin.TCallLabel("/_flashRunner", "execute");

		// get the results
		var results = plugin.GetVariable("_returnResult");

		// we double encoded all null characters as //0 because Flash breaks
		// if they are present; turn the //0 back into /0
		results = results.replace(/\\0/g, "\0");

		return results;
	},

	/** Flash 8 communication. */

	/**
			Registers the existence of a Flash method that we can call with
			JavaScript, using Flash 8's ExternalInterface.
	*/
	_addExternalInterfaceCallback: function(methodName){
		var wrapperCall = function(){
			// some browsers don't like us changing values in the 'arguments' array, so
			// make a fresh copy of it
			var methodArgs = new Array(arguments.length);
			for(var i = 0; i < arguments.length; i++){
				methodArgs[i] = arguments[i];
			}
			return dojo.flash.comm._execFlash(methodName, methodArgs);
		};

		dojo.flash.comm[methodName] = wrapperCall;
	},

	/**
			Encodes our data to get around ExternalInterface bugs.
			Flash 8 communication.
	*/
	_encodeData: function(data){
		// double encode all entity values, or they will be mis-decoded
		// by Flash when returned
		var entityRE = /\&([^;]*)\;/g;
		data = data.replace(entityRE, "&$1;");

		// entity encode XML-ish characters, or Flash's broken XML serializer
		// breaks
		data = data.replace(/</g, "<");
		data = data.replace(/>/g, ">");

		// transforming \ into \\ doesn't work; just use a custom encoding
		data = data.replace("\\", "&custom_backslash;&custom_backslash;");

		data = data.replace(/\n/g, "\\n");
		data = data.replace(/\r/g, "\\r");
		data = data.replace(/\f/g, "\\f");
		data = data.replace(/\0/g, "\\0"); // null character
		data = data.replace(/\'/g, "\\\'");
		data = data.replace(/\"/g, '\\\"');

		return data;
	},

	/**
			Decodes our data to get around ExternalInterface bugs.
			Flash 8 communication.
	*/
	_decodeData: function(data){
		if(data == null || typeof data == "undefined"){
			return data;
		}

		// certain XMLish characters break Flash's wire serialization for
		// ExternalInterface; these are encoded on the
		// DojoExternalInterface side into a custom encoding, rather than
		// the standard entity encoding, because otherwise we won't be able to
		// differentiate between our own encoding and any entity characters
		// that are being used in the string itself
		data = data.replace(/\&custom_lt\;/g, "<");
		data = data.replace(/\&custom_gt\;/g, ">");

		// Unfortunately, Flash returns us our String with special characters
		// like newlines broken into seperate characters. So if \n represents
		// a new line, Flash returns it as "\" and "n". This means the character
		// is _not_ a newline. This forces us to eval() the string to cause
		// escaped characters to turn into their real special character values.
		data = eval('"' + data + '"');

		return data;
	},

	/**
			Sends our method arguments over to Flash in chunks in order to
			have ExternalInterface's performance not be O(n^2).
			Flash 8 communication.
	*/
	_chunkArgumentData: function(value, argIndex){
		var plugin = dojo.flash.obj.get();

		// cut up the string into pieces, and push over each piece one
		// at a time
		var numSegments = Math.ceil(value.length / 1024);
		for(var i = 0; i < numSegments; i++){
			var startCut = i * 1024;
			var endCut = i * 1024 + 1024;
			if(i == (numSegments - 1)){
				endCut = i * 1024 + value.length;
			}

			var piece = value.substring(startCut, endCut);

			// encode each piece seperately, rather than the entire
			// argument data, because ocassionally a special
			// character, such as an entity like &foobar;, will fall between
			// piece boundaries, and we _don't_ want to encode that value if
			// it falls between boundaries, or else we will end up with incorrect
			// data when we patch the pieces back together on the other side
			piece = this._encodeData(piece);

			// directly use the underlying CallFunction method used by
			// ExternalInterface, which is vastly faster for large strings
			// and lets us bypass some Flash serialization bugs
			plugin.CallFunction('<invoke name="chunkArgumentData" '
														+ 'returntype="javascript">'
														+ '<arguments>'
														+ '<string>' + piece + '</string>'
														+ '<number>' + argIndex + '</number>'
														+ '</arguments>'
														+ '</invoke>');
		}
	},

	/**
			Gets our method return data in chunks for better performance.
			Flash 8 communication.
	*/
	_chunkReturnData: function(){
		var plugin = dojo.flash.obj.get();

		var numSegments = plugin.getReturnLength();
		var resultsArray = new Array();
		for(var i = 0; i < numSegments; i++){
			// directly use the underlying CallFunction method used by
			// ExternalInterface, which is vastly faster for large strings
			var piece =
					plugin.CallFunction('<invoke name="chunkReturnData" '
															+ 'returntype="javascript">'
															+ '<arguments>'
															+ '<number>' + i + '</number>'
															+ '</arguments>'
															+ '</invoke>');

			// remove any leading or trailing JavaScript delimiters, which surround
			// our String when it comes back from Flash since we bypass Flash's
			// deserialization routines by directly calling CallFunction on the
			// plugin
			if(piece == '""' || piece == "''"){
				piece = "";
			}else{
				piece = piece.substring(1, piece.length-1);
			}

			resultsArray.push(piece);
		}
		var results = resultsArray.join("");

		return results;
	},

	/**
			Executes a Flash method; called from the JavaScript wrapper proxy we
			create on dojo.flash.comm.
			Flash 8 communication.
	*/
	_execFlash: function(methodName, methodArgs){
		var plugin = dojo.flash.obj.get();

		// begin Flash method execution
		plugin.startExec();

		// set the number of arguments
		plugin.setNumberArguments(methodArgs.length);

		// chunk and send over each argument
		for(var i = 0; i < methodArgs.length; i++){
			this._chunkArgumentData(methodArgs[i], i);
		}

		// execute the method
		plugin.exec(methodName);

		// get the return result
		var results = this._chunkReturnData();

		// decode the results
		results = this._decodeData(results);

		// reset everything
		plugin.endExec();

		return results;

	}
}

/**
		Figures out the best way to automatically install the Flash plugin
		for this browser and platform. Also determines if installation or
		revving of the current plugin is needed on this platform.
*/
dojo.flash.Install = function(){
}

dojo.flash.Install.prototype = {
	/**
			Determines if installation or revving of the current plugin is
			needed.
	*/
	needed: function(){
		// do we even have flash?
		if(dojo.flash.info.capable == false){
			return true;
		}

		// are we on the Mac? Safari needs Flash version 8 to do Flash 8
		// communication, while Firefox/Mac needs Flash 8 to fix bugs it has
		// with Flash 6 communication
		if(dojo.render.os.mac == true && !dojo.flash.info.isVersionOrAbove(8, 0, 0)){
			return true;
		}

		// other platforms need at least Flash 6 or above
		if(!dojo.flash.info.isVersionOrAbove(6, 0, 0)){
			return true;
		}

		// otherwise we don't need installation
		return false;
	},

	/** Performs installation or revving of the Flash plugin. */
	install: function(){
		//dojo.debug("install");
		// indicate that we are installing
		dojo.flash.info.installing = true;
		dojo.flash.installing();

		if(dojo.flash.info.capable == false){ // we have no Flash at all
			//dojo.debug("Completely new install");
			// write out a simple Flash object to force the browser to prompt
			// the user to install things
			var installObj = new dojo.flash.Embed(false);
			installObj.write(8); // write out HTML for Flash 8 version+
		}else if(dojo.flash.info.isVersionOrAbove(6, 0, 65)){ // Express Install
			//dojo.debug("Express install");
			var installObj = new dojo.flash.Embed(false);
			installObj.write(8, true); // write out HTML for Flash 8 version+
			installObj.setVisible(true);
			installObj.center();
		}else{ // older Flash install than version 6r65
			alert("This content requires a more recent version of the Macromedia "
						+" Flash Player.");
			window.location.href = "http://www.macromedia.com/go/getflashplayer";
		}
	},

	/**
			Called when the Express Install is either finished, failed, or was
			rejected by the user.
	*/
	_onInstallStatus: function(msg){
		if (msg == "Download.Complete"){
			// Installation is complete.
			dojo.flash._initialize();
		}else if(msg == "Download.Cancelled"){
			alert("This content requires a more recent version of the Macromedia "
						+" Flash Player.");
			window.location.href = "http://www.macromedia.com/go/getflashplayer";
		}else if (msg == "Download.Failed"){
			// The end user failed to download the installer due to a network failure
			alert("There was an error downloading the Flash Player update. "
						+ "Please try again later, or visit macromedia.com to download "
						+ "the latest version of the Flash plugin.");
		}
	}
}

// find out if Flash is installed
dojo.flash.info = new dojo.flash.Info();

// vim:ts=4:noet:tw=0:


text:
module BurnPlan
  module TaxStrategy
    class NoTaxStrategy < TaxStrategy
      def initialize

      end

      def pretax_distribution_amount(asset, after_tax_amount)
        after_tax_amount
      end
    end
  end
end


text:
(function(define) {
    'use strict';

    var _performanceStart;

    var _dateNow = (!Date.now) ? function () {
        return new Date().getTime();
    } : Date.now;

    var _perf = typeof window !== 'undefined' && window.performance;

    if (!_perf && typeof process !== 'undefined' && process.hrtime) {
        _performanceStart = process.hrtime();

        _perf = {
            now : function () {
                var now = process.hrtime(_performanceStart);
                return now[0] + now[1] * 1e-9;
            }
        };

    }

    if (!_perf && Date) {
        _performanceStart = _dateNow();

        _perf = {
            now : function () {
                var now = _dateNow();
                return now - _performanceStart;
            }
        };
    }

    var _perfNow = function () { return _perf.now(); };

    define(function () {
        return {
            perf : _perfNow,
            date : _dateNow
        };
    });

})(typeof define === 'function' && define.amd ?
    define :
    function (factory) { 'use strict'; module.exports = factory(require); }
);


text:
import ftplib
import inspect
import itertools
import json
import logging
import os
import re
import time
import urllib.request

import debian.deb822

from . import cfg, util

log = logging.getLogger(__name__)

def split(env):
	parts = env.rsplit('-', 1)
	if parts and '-' in parts[0]:
		parts[0] = ENVS.ALIASES.get(parts[0], parts[0])
	return parts

def match(*specs, installed=None):
	specs = list(filter(None, specs))
	if not specs:
		specs = ['all']

	all = ENVS.copy()
	if installed:
		all += list(installed)

	envs = set()
	for spec in specs:
		if spec == 'all':
			envs.update(all)
		else:
			for e in all:
				if e.startswith(spec) or e.endswith(spec):
					envs.add(e)

	return sorted(envs)

def main_mirror(release, cfg=None):
	for dist, specs in ENVS.MIRRORS.items():
		if release in specs[0]:
			if cfg and cfg.main_mirror(dist, release):
				return cfg.main_mirror(dist, release)

			return specs[1]

	raise UnknownRelease(release)

def packages(release, arch, cfg=None):
	if cfg:
		for dist, specs in ENVS.MIRRORS.items():
			if release in specs[0]:
				return cfg.extra_packages(dist, release, arch)

	return set()

def components(release, sep=' '):
	for dist, specs in ENVS.COMPONENTS.items():
		if release in specs[0]:
			return specs[1].replace(' ', sep)

	raise UnknownRelease(release)

def dist(release):
	for dist, specs in ENVS.COMPONENTS.items():
		if release in specs[0]:
			return dist

	raise UnknownRelease(release)

def sources(release, arch, cfg=None):
	main = main_mirror(release, cfg=cfg)
	comps = components(release)
	d = dist(release)

	srcs = set([
		'deb {} {} {}'.format(main, release, comps).strip(),
		'deb-src {} {} {}'.format(main, release, comps).strip(),
	])

	if cfg and cfg.extra_sources(d, release, arch):
		srcs |= cfg.extra_sources(d, release, arch)

	return '\n'.join(sorted(srcs)) + '\n'

class UnknownRelease(Exception):
	pass

class _Envs(list):
	_ARCHS = ['amd64', 'i386']

	_ALIASES = {}

	_DEBIAN_ALIASES = ['stable', 'testing', 'unstable']

	_DEBIAN = []
	_UBUNTU = []

	_COMPONENTS = {
		'debian': (_DEBIAN, 'main contrib non-free'),
		'ubuntu': (_UBUNTU, 'main restricted universe multiverse'),
	}

	_MIRRORS = {
		'debian': (_DEBIAN, 'http://httpredir.debian.org/debian'),
		'ubuntu': (_UBUNTU, 'http://us.archive.ubuntu.com/ubuntu/'),
	}

	def __init__(self):
		self._loaded = False

		ms = inspect.getmembers(self, lambda a: not inspect.isroutine(a))
		for m in ms:
			n = m[0]
			if n.upper() == n:
				setattr(_Envs, n[1:], property(self._getter(n)))

	def _getter(self, n):
		def fn(self):
			self._load()
			return getattr(self, n)
		return fn

	def _should_refresh(self, path):
		try:
			mod = os.path.getmtime(path)
			return mod <= (time.time() - (86400 * 7))
		except os.error:
			return True

	def _load_debian(self):
		path = os.path.join(cfg.cfg_dir(), 'debian.release')
		if self._should_refresh(path):
			self._refresh_debian(path)

		with open(path, 'r') as f:
			dists = json.load(f)

		for a in self._DEBIAN_ALIASES:
			self._ALIASES['debian-{}'.format(a)] = dists[a]
			self._DEBIAN.append(dists[a])

	def _refresh_debian(self, path):
		log.info('refreshing Debian releases...')

		lines = []
		with ftplib.FTP('ftp.us.debian.org') as ftp:
			ftp.login()
			ftp.cwd('debian/dists/')
			ftp.retrlines('LIST', callback=lambda l: lines.append(l))

		dists = {}
		for l in lines:
			if '->' in l:
				sl = l.split()
				dists[sl[-3]] = sl[-1]

		dists = {a: dists[a] for a in self._DEBIAN_ALIASES}
		with open(path, 'w') as f:
			json.dump(dists, f)

	def _load_ubuntu(self):
		path = os.path.join(cfg.cfg_dir(), 'ubuntu.release')
		if self._should_refresh(path):
			self._refresh_ubuntu(path)

		with open(path, 'r') as f:
			rels = json.load(f)

		self._ALIASES['ubuntu-latest'] = rels['latest']
		self._ALIASES['ubuntu-lts'] = rels['lts']

		self._UBUNTU += rels['vers']

	def _refresh_ubuntu(self, path):
		log.info('refreshing Ubuntu releases...')

		rels = {
			'vers': [],
		}

		resp = urllib.request.urlopen('http://changelogs.ubuntu.com/meta-release')
		for p in debian.deb822.Deb822.iter_paragraphs(resp):
			if p['Supported'] != '1':
				continue

			dist = p['Dist']

			rels['latest'] = dist
			if 'LTS' in p['Version']:
				rels['lts'] = dist

			rels['vers'].append(dist)

		with open(path, 'w') as f:
			json.dump(rels, f)

	def _load(self):
		if self._loaded:
			return

		self._load_debian()
		self._load_ubuntu()
		self._ENVS = self._DEBIAN + self._UBUNTU + list(self._ALIASES.keys())
		self += sorted(['-'.join(c) for c in itertools.product(self._ENVS, self._ARCHS)])
		self._loaded = True

	def copy(self):
		self._load()
		return super().copy()

	def __getitem__(self, *args, **kwargs):
		self._load()
		return super().__getitem__(*args, **kwargs)

	def __iter__(self):
		self._load()
		return super().__iter__()

	def __len__(self):
		self._load()
		return super().__len__()

ENVS = _Envs()


text:
package org.springframework.cloud.stream.binder;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.Lifecycle;
import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.integration.core.Pausable;
import org.springframework.integration.support.context.NamedComponent;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * Default implementation for a {@link Binding}.
 *
 * @param <T> type of binding
 * @author Jennifer Hickey
 * @author Mark Fisher
 * @author Gary Russell
 * @author Marius Bogoevici
 * @author Oleg Zhurakousky
 * @see org.springframework.cloud.stream.annotation.EnableBinding
 */

@JsonPropertyOrder({ "bindingName", "name", "group", "pausable", "state" })
@JsonIgnoreProperties("running")
public class DefaultBinding<T> implements Binding<T> {

	protected final String name;

	protected final String group;

	protected final T target;

	protected final Lifecycle lifecycle;

	private final Log logger = LogFactory.getLog(this.getClass().getName());

	private boolean paused;

	private boolean restartable;

	/**
	 * Creates an instance that associates a given name, group and binding target with an
	 * optional {@link Lifecycle} component, which will be stopped during unbinding.
	 * @param name the name of the binding target
	 * @param group the group (only for input targets)
	 * @param target the binding target
	 * @param lifecycle {@link Lifecycle} that runs while the binding is active and will
	 * be stopped during unbinding
	 */
	public DefaultBinding(String name, String group, T target, Lifecycle lifecycle) {
		Assert.notNull(target, "target must not be null");
		this.name = name;
		this.group = group;
		this.target = target;
		this.lifecycle = lifecycle;
		this.restartable = StringUtils.hasText(group);
	}

	public DefaultBinding(String name, T target, Lifecycle lifecycle) {
		this(name, null, target, lifecycle);
		this.restartable = true;
	}

	public String getName() {
		return this.name;
	}

	public String getBindingName() {
		String resolvedName = (this.target instanceof IntegrationObjectSupport)
				? ((IntegrationObjectSupport) this.target).getComponentName() : getName();
		return resolvedName == null ? getName() : resolvedName;
	}

	public String getGroup() {
		return this.group;
	}

	public String getState() {
		String state = "N/A";
		if (this.lifecycle != null) {
			if (isPausable()) {
				state = this.paused ? "paused" : this.getRunningState();
			}
			else {
				state = this.getRunningState();
			}
		}
		return state;
	}

	public boolean isRunning() {
		return this.lifecycle != null && this.lifecycle.isRunning();
	}

	public boolean isPausable() {
		return this.lifecycle instanceof Pausable;
	}

	@Override
	public final synchronized void start() {
		if (!this.isRunning()) {
			if (this.lifecycle != null && this.restartable) {
				this.lifecycle.start();
			}
			else {
				this.logger.warn("Can not re-bind an anonymous binding");
			}
		}
	}

	@Override
	public final synchronized void stop() {
		if (this.isRunning()) {
			this.lifecycle.stop();
		}
	}

	@Override
	public final synchronized void pause() {
		if (this.lifecycle instanceof Pausable) {
			((Pausable) this.lifecycle).pause();
			this.paused = true;
		}
		else {
			this.logger
					.warn("Attempted to pause a component that does not support Pausable "
							+ this.lifecycle);
		}
	}

	@Override
	public final synchronized void resume() {
		if (this.lifecycle instanceof Pausable) {
			((Pausable) this.lifecycle).resume();
			this.paused = false;
		}
		else {
			this.logger.warn(
					"Attempted to resume a component that does not support Pausable "
							+ this.lifecycle);
		}
	}

	@Override
	public final void unbind() {
		this.stop();
		afterUnbind();
	}

	Lifecycle getEndpoint() {
		return this.lifecycle;
	}

	@Override
	public String toString() {
		return " Binding [name=" + this.name + ", target=" + this.target + ", lifecycle="
				+ ((this.lifecycle instanceof NamedComponent)
						? ((NamedComponent) this.lifecycle).getComponentName()
						: ObjectUtils.nullSafeToString(this.lifecycle))
				+ "]";
	}

	/**
	 * Listener method that executes after unbinding. Subclasses can implement their own
	 * behaviour on unbinding by overriding this method.
	 */
	protected void afterUnbind() {
	}

	private String getRunningState() {
		return isRunning() ? "running" : "stopped";
	}

}


text:
import testtools

from tempest.common.utils import data_utils
from tempest import config
from tempest.openstack.common import log as logging
from tempest.scenario import manager
from tempest import test

CONF = config.CONF
LOG = logging.getLogger(__name__)

class TestNetworkAdvancedServerOps(manager.NetworkScenarioTest):

    """
    This test case checks VM connectivity after some advanced
    instance operations executed:

     * Stop/Start an instance
     * Reboot an instance
     * Rebuild an instance
     * Pause/Unpause an instance
     * Suspend/Resume an instance
     * Resize an instance
    """

    @classmethod
    def setUpClass(cls):
        super(TestNetworkAdvancedServerOps, cls).setUpClass()
        cls.check_preconditions()
        if not (CONF.network.tenant_networks_reachable
                or CONF.network.public_network_id):
            msg = ('Either tenant_networks_reachable must be "true", or '
                   'public_network_id must be defined.')
            cls.enabled = False
            raise cls.skipException(msg)

    def cleanup_wrapper(self, resource):
        self.cleanup_resource(resource, self.__class__.__name__)

    def setUp(self):
        super(TestNetworkAdvancedServerOps, self).setUp()
        key_name = data_utils.rand_name('keypair-smoke-')
        self.keypair = self.create_keypair(name=key_name)
        self.addCleanup(self.cleanup_wrapper, self.keypair)
        security_group =\
            self._create_security_group_neutron(tenant_id=self.tenant_id)
        self.addCleanup(self.cleanup_wrapper, security_group)
        network = self._create_network(self.tenant_id)
        self.addCleanup(self.cleanup_wrapper, network)
        router = self._get_router(self.tenant_id)
        self.addCleanup(self.cleanup_wrapper, router)
        subnet = self._create_subnet(network)
        self.addCleanup(self.cleanup_wrapper, subnet)
        subnet.add_to_router(router.id)
        public_network_id = CONF.network.public_network_id
        create_kwargs = {
            'nics': [
                {'net-id': network.id},
            ],
            'key_name': self.keypair.name,
            'security_groups': [security_group.name],
        }
        server_name = data_utils.rand_name('server-smoke-%d-')
        self.server = self.create_server(name=server_name,
                                         create_kwargs=create_kwargs)
        self.addCleanup(self.cleanup_wrapper, self.server)
        self.floating_ip = self._create_floating_ip(self.server,
                                                    public_network_id)
        self.addCleanup(self.cleanup_wrapper, self.floating_ip)

    def _check_network_connectivity(self, should_connect=True):
        username = CONF.compute.image_ssh_user
        private_key = self.keypair.private_key
        self._check_tenant_network_connectivity(
            self.server, username, private_key, should_connect=should_connect,
            servers_for_debug=[self.server])
        floating_ip = self.floating_ip.floating_ip_address
        self._check_public_network_connectivity(floating_ip, username,
                                                private_key, should_connect,
                                                servers=[self.server])

    def _wait_server_status_and_check_network_connectivity(self):
        self.status_timeout(self.compute_client.servers, self.server.id,
                            'ACTIVE')
        self._check_network_connectivity()

    @test.services('compute', 'network')
    def test_server_connectivity_stop_start(self):
        self.server.stop()
        self.status_timeout(self.compute_client.servers, self.server.id,
                            'SHUTOFF')
        self._check_network_connectivity(should_connect=False)
        self.server.start()
        self._wait_server_status_and_check_network_connectivity()

    @test.services('compute', 'network')
    def test_server_connectivity_reboot(self):
        self.server.reboot()
        self._wait_server_status_and_check_network_connectivity()

    @test.services('compute', 'network')
    def test_server_connectivity_rebuild(self):
        image_ref_alt = CONF.compute.image_ref_alt
        self.server.rebuild(image_ref_alt)
        self._wait_server_status_and_check_network_connectivity()

    @testtools.skipUnless(CONF.compute_feature_enabled.pause,
                          'Pause is not available.')
    @test.services('compute', 'network')
    def test_server_connectivity_pause_unpause(self):
        self.server.pause()
        self.status_timeout(self.compute_client.servers, self.server.id,
                            'PAUSED')
        self._check_network_connectivity(should_connect=False)
        self.server.unpause()
        self._wait_server_status_and_check_network_connectivity()

    @testtools.skipUnless(CONF.compute_feature_enabled.suspend,
                          'Suspend is not available.')
    @test.services('compute', 'network')
    def test_server_connectivity_suspend_resume(self):
        self.server.suspend()
        self.status_timeout(self.compute_client.servers, self.server.id,
                            'SUSPENDED')
        self._check_network_connectivity(should_connect=False)
        self.server.resume()
        self._wait_server_status_and_check_network_connectivity()

    @testtools.skipUnless(CONF.compute_feature_enabled.resize,
                          'Resize is not available.')
    @test.services('compute', 'network')
    def test_server_connectivity_resize(self):
        resize_flavor = CONF.compute.flavor_ref_alt
        if resize_flavor == CONF.compute.flavor_ref:
            msg = "Skipping test - flavor_ref and flavor_ref_alt are identical"
            raise self.skipException(msg)
        resize_flavor = CONF.compute.flavor_ref_alt
        self.server.resize(resize_flavor)
        self.status_timeout(self.compute_client.servers, self.server.id,
                            'VERIFY_RESIZE')
        self.server.confirm_resize()
        self._wait_server_status_and_check_network_connectivity()


text:
package io.proleap.cobol.asg.metamodel.procedure;

import java.util.List;

import io.proleap.cobol.CobolParser.ProcedureDivisionUsingParameterContext;
import io.proleap.cobol.asg.metamodel.CobolDivisionElement;

public interface UsingClause extends CobolDivisionElement {

	UsingParameter addUsingParameter(ProcedureDivisionUsingParameterContext ctx);

	List<UsingParameter> getUsingParameters();
}


text:
layout: post
unique_id: smog_check
title: Smog Check
categories: []
locations:
---

YESTERDAY:
* woke up randomly at 6 am and couldn't get a little music progression out of my head
  * downloaded a free app called MuseScore 2 and was able to jot it down
  * went back to sleep
* smog check in the morning
  * super easy and got a $15 off coupon :D
* researched FFTs on PDM output from digital mic
* yoga
  * handstand practice!
* lunch at Subway
* got UART to USB connector
  * rewrote UART driver, works properly
* fixed an annoying buffer overrun bug in my flash driver
* refactored Bluetooth command logic
* second Amazon locker pickup
  * battery on robot vacuum cleaner died
* steamed a fish
  * Brian made a scampi with fresh pasta to go with it
* smoothie to finish the last banana before I head to LA
  * finished some leftover green beans too
* paid my DMV registration bill
* ported data upload part from Android app into Python for a UART dump

TODAY:
* morning climbing
* lunch with an old friend
* drive to LA!
  * bringing Amy's violin and electric guitar down
  * also a super secret box of documents for my aunt
  * 7 hours
  * nap on a lovely beach south of San Luis Obispo
* had some of my parent's homemade rice dumplings for dinner!
* found out my parents have gotten into dehydrating random stuff
  * kitchen's full of jars of powdered ginger, scallions, okra, etc

LEARNINGS:
* the modulation for PDM is done on the sensor side in a digital microphone (which ... kinda makes sense)


text:
<!DOCTYPE html>
<link rel="help" href="https://crbug.com/1236657">
<link rel="match" href="../reference/ref-filled-green-100px-square.xht">
<meta name="assert" content="A table should be centered with auto margins and zero insets.">

Test passes if there is a filled green square and no red.


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Finding The Way Home</title>
    <meta name="description" content="Finding The Way Home - A beautiful narrative written with the world's most elegant publishing platform. The story begins here." />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/jasper/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/jasper/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

        <link rel="canonical" href="/jasper/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/jasper/page2/" />

    <meta property="og:site_name" content="Finding The Way Home" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Finding The Way Home" />
    <meta property="og:description" content="A beautiful narrative written with the world's most elegant publishing platform. The story begins here." />
    <meta property="og:url" content="/jasper/" />
    <meta property="og:image" content="/jasper/assets/images/cover1.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Finding The Way Home" />
    <meta name="twitter:description" content="A beautiful narrative written with the world's most elegant publishing platform. The story begins here." />
    <meta name="twitter:url" content="/jasper/" />
    <meta name="twitter:image:src" content="/jasper/assets/images/cover1.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="Finding The Way Home" href="/jasper/rss.xml" />

Menu

        Close

Home

About

Fables

Speeches

Fiction

Author

    Subscribe

            Menu

Speeches

                Some of the greatest words ever spoken.

     Page 1 of 1

I Have a Dream

I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our... »

            Casper McFadden

                on

                       Speeches

            <time class="post-date" datetime="1963-08-28">28 Aug 1963</time>

The Purpose of Education

As I engage in the so-called "bull sessions" around and about the school, I too often find that most college men have a misconception of the... »

            Casper McFadden

                on

                       Speeches,

                       Fiction

            <time class="post-date" datetime="1948-12-12">12 Dec 1948</time>

     Page 1 of 1

Finding The Way Home © 2015

Proudly published with Jekyll using Jasper


text:
use strict;
use warnings;

my $file = 'bigfile.txt';
my $server_dir = '../server/';
my $server = './triviald';
my $client = '../client/trivial';
my $port = 4001;

my $error_exist = "TFTP client and/or server have not been found, try running make";

die $error_exist unless (-e "$server_dir/$server" and -e $client);

 print "Running server on port $port...\n";

 system ("cd $server_dir && $server -p $port &") ;

 print "Running client : sending $file to localhost on port $port\n";

 if (-e '../server/'.$file){
	 system("killall triviald");
	 die "File already exists in server directory.. please remove it";
 }

 system ("$client -f $file -w -p $port -H 127.0.0.1");

 if(-e '../server/'.$file){
	print "The file is now available in the server/ directory\n";
  }

 else {die "An error has occured\n"; }


text:
import React from 'react';

export default class DropDownComponent extends React.Component {
    convertInput(text) {
        var pattern = /^([1-9]{1}[0-2]{0,1})\:?(\d{2})?\s?([a|p]m?)?$/;
        var matches = text.match(pattern);
        return matches ? Array.prototype.slice.apply(matches, [1]) : [];
    }

    render() {
        var items = !this.props.items ? [] : this.props.items.map((name, index) => {
            return React.DOM.li({ className: 'item' }, name);
        });

        return React.DOM.ul({ className: 'items' }, items);
    }
}


text:
package controllers;

import actors.SockJSActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.libs.F.Function;
import play.mvc.*;
import play.mvc.Http.Context;
import play.sockjs.SockJS;
import play.sockjs.SockJSRouter;

public class Application extends Controller
{

	public static Result index()
	{
		return ok(views.html.ws.render());
	}

	public static SockJSRouter api = SockJSRouter.tryAccept(new Function<Context, SockJS>(){
		@Override
		public SockJS apply(Context context) throws Throwable {
			System.out.println("Got SockJS connection from: " + context.request().remoteAddress());
			//return SockJS.reject(Result);

			context.request().setUsername("chris");

			return SockJS.withActor(new Function<ActorRef,Props>(){
				@Override
				public Props apply(ActorRef out) throws Throwable {
					return SockJSActor.props(out, context.request());
				}
			});
		}
	});

}


text:
package org.drools.core.reteoo.builder;

import java.util.List;

import org.drools.core.common.BetaConstraints;
import org.drools.core.reteoo.LeftTupleSource;
import org.drools.core.rule.From;
import org.drools.core.rule.RuleConditionElement;
import org.drools.core.spi.AlphaNodeFieldConstraint;
import org.drools.core.spi.BetaNodeFieldConstraint;

public class FromBuilder
    implements
    ReteooComponentBuilder {

    /* (non-Javadoc)
     * @see org.kie.reteoo.builder.ReteooComponentBuilder#build(org.kie.reteoo.builder.BuildContext, org.kie.reteoo.builder.BuildUtils, org.kie.rule.RuleConditionElement)
     */
    public void build(final BuildContext context,
                      final BuildUtils utils,
                      final RuleConditionElement rce) {
        final From from = (From) rce;
        context.pushRuleComponent( from );

        @SuppressWarnings("unchecked")
        BetaConstraints betaConstraints = utils.createBetaNodeConstraint( context, (List<BetaNodeFieldConstraint>) context.getBetaconstraints(), true );

        context.setTupleSource( (LeftTupleSource) utils.attachNode( context,
                context.getComponentFactory().getNodeFactoryService().buildFromNode( context.getNextId(),
                                                                                from.getDataProvider(),
                                                                                context.getTupleSource(),
                                                                                context.getAlphaConstraints().toArray( new AlphaNodeFieldConstraint[context.getAlphaConstraints().size()] ),
                                                                                betaConstraints,
                                                                                context.isTupleMemoryEnabled(),
                                                                                context,
                                                                                from ) ) );
        context.setAlphaConstraints( null );
        context.setBetaconstraints( null );
        context.popRuleComponent();
    }

    /**
     * @inheritDoc
     */
    public boolean requiresLeftActivation(final BuildUtils utils,
                                          final RuleConditionElement rce) {
        return true;
    }

}


text:
<?php
require_once dirname(__FILE__) . "/example.inc.php";

$container = S2ContainerFactory::create("./resource/example.dicon.xml");
$dao = $container->getComponent("CdDao");

var_dump($dao->getCD1(2, 'aaa'));
echo "=====" . PHP_EOL;
var_dump($dao->getCD2(2, 'help!', 'rock'));
?>


text:
CppUnit::Test* MailTestSuite::suite()
{
	CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MailTestSuite");

	pSuite->addTest(MailMessageTest::suite());
	pSuite->addTest(MailStreamTest::suite());
	pSuite->addTest(SMTPClientSessionTest::suite());
	pSuite->addTest(POP3ClientSessionTest::suite());

	return pSuite;
}