text:
local PLAYER = FindMetaTable( "Player" )

// Save data //
function PLAYER:PerkShop_Save()
	if not (self.PerkShop) then return false,"Player not loaded" end

	local data = util.TableToJSON( self.PerkShop )
	if not data then return false,"Failed to compress table" end // This shouldn't happen, but just in case

	self:SetPData( "PerkShopData", data )

	self:PerkShop_UpdateItems()

	return true
end
function PLAYER:PerkShop_Load()
	self.PerkShop = { // Create/Reset the table
		Points = (-1),
		Items = {},
		Equipped = {},
	}

	local str = self:GetPData( "PerkShopData" )
	if str then
		local data = util.JSONToTable( str )
		if data then
			self.PerkShop.Items = data.Items or self.PerkShop.Items
			self.PerkShop.Equipped = data.Equipped or self.PerkShop.Equipped
			self:PerkShop_SetPoints(data.Points or self.PerkShop.Points)
		end
	end

	for classname,level in pairs(self.PerkShop.Equipped) do
		local name,cat = PerkShop:SplitClassname( classname )
		if name and cat then
			local itm = PerkShop:GetItem( name, cat )
			if itm and itm.OnEquip then
				itm:OnEquip( self, level )
			end
		end
	end

	self:PerkShop_UpdateItems()

	return true
end

// Set data //
function PLAYER:PerkShop_SetPoints( num )
	if not self.PerkShop then return false,"Player not loaded" end // Not loaded, nothing we can do

	self.PerkShop.Points = math.max( num, 0 )
	self:SetNWInt( "PerkShop_Points", self.PerkShop.Points )

	return true
end
function PLAYER:PerkShop_GivePoints( add ) return self:PerkShop_SetPoints( self:PerkShop_Points() + add ) end // For convenience
function PLAYER:PerkShop_TakePoints( sub ) return self:PerkShop_SetPoints( self:PerkShop_Points() - sub ) end // And again

function PLAYER:PerkShop_ClearItems()
	if not self.PerkShop then return false,"Player not loaded" end // Not loaded, nothing we can do

	self.PerkShop.Items = {}
	self:PerkShop_Save()

	return true
end
function PLAYER:PerkShop_GiveItem( item, level )
	if not self.PerkShop then return false,"Player not loaded" end // Not loaded, nothing we can do

	self.PerkShop.Items[item.Category.."_"..item.Class] = level or 1
	self:PerkShop_Save()

	return true
end
function PLAYER:PerkShop_TakeItem( item, level )
	if not self.PerkShop then return false,"Player not loaded" end // Not loaded, nothing we can do

	self.PerkShop.Items[item.Category.."_"..item.Class] = nil
	self:PerkShop_Save()

	return true
end

// Equipping //
function PLAYER:PerkShop_Equip( item, level ) // Level 0 is unequip
	if not self.PerkShop then return false,"Player not loaded" end
	level = level or 1

	local itmLevel = self:PerkShop_HasItem( item.Class, item.Category )
	if not itmLevel then return false,"Attempting to equip unowned item" end

	if level>itmLevel then return false,"Attempting to equip higher than level" end

	if self.PerkShop.Equipped[item.Classname] and self.PerkShop.Equipped[item.Classname]>0 and item.OnRemove then
		item:OnRemove( self, self.PerkShop.Equipped[item.Classname] )
	end

	self.PerkShop.Equipped[item.Classname] = level>0 and level or nil
	self:PerkShop_Save()

	if level>0 then
		if item.OnEquip then item:OnEquip( self, level ) end
	end

	return true
end
concommand.Add( "perk_equip", function( p,c,a )
	if not (IsValid(p)) then return end
	local item = PerkShop:GetItem( a[2], a[1] )
	if item then
		local newLevel = tonumber(a[3]) or 1
		local success, err = p:PerkShop_Equip( item, newLevel )
		if success then
			if newLevel==0 then
				p:ChatPrint( string.format( "%sUnequipped %s: %s", PerkShop.Tag, a[1], a[2] ) )
			else
				p:ChatPrint( string.format( "%sEquipped %s: %s %s", PerkShop.Tag, a[1], a[2], newLevel~=1 and "(level "..newLevel..")" or "" ) )
			end
		else
			p:ChatPrint( string.format( "%sEquip failed. (%s)", PerkShop.Tag, err or "N/A" ) )
		end
	else
		p:ChatPrint( string.format( "%sEquip failed. (Item %s_%s does not exist)", PerkShop.Tag, a[1], a[2] ) )
	end
end)
concommand.Add( "perk_unequip", function( p,c,a )
	if not (IsValid(p)) then return end
	local item = PerkShop:GetItem( a[2], a[1] )
	if item then
		local success, err = p:PerkShop_Equip( item, 0 )
		if success then
			p:ChatPrint( string.format( "%sUnequipped %s: %s %s", PerkShop.Tag, a[1], a[2], tonumber(a[3]) and "(level "..tonumber(a[3])..")" or "" ) )
		else
			p:ChatPrint( string.format( "%sUnequip failed. (%s)", PerkShop.Tag, err or "N/A" ) )
		end
	else
		p:ChatPrint( string.format( "%sUnequip failed. (Item %s_%s does not exist)", PerkShop.Tag, a[1], a[2] ) )
	end
end)

// Purchasing //
function PLAYER:PerkShop_Buy( item, newLevel )
	if not self.PerkShop then return false,"Player not loaded" end

	newLevel = newLevel or 1
	if newLevel>item.Level then return false,"Attempting to buy over max level" end

	local oldLevel = self:PerkShop_HasItem( item.Classname ) or 0
	if oldLevel>=newLevel then return false,"Attempting to buy level lower than owned" end

	local cost,err = PerkShop:GetCost( item.Class, item.Category, oldLevel, newLevel or 1 )
	if cost==-1 then return false,err or "Failed to calculate value" end

	if cost>self:PerkShop_Points() then return false,"Insufficient funds" end

	local success,err = self:PerkShop_TakePoints( cost )
	if not success then return false,err or "Failed to spend "..PerkShop.PointsLabel end

	return self:PerkShop_GiveItem( item, newLevel or 1 )
end
function PLAYER:PerkShop_Sell( item, sellLevels )
	if not self.PerkShop then return false,"Player not loaded" end

	sellLevels = sellLevels or 0

	local oldLevel = self:PerkShop_HasItem( item.Classname )
	if not oldLevel then return false,"Attempting to sell unowned item" end

	local newLevel = (sellLevels==0 and 0) or math.max(oldLevel-sellLevels,0)
	if oldLevel<newLevel then return false,"Attempting to sell level higher than owned" end

	local equipped = self:PerkShop_Equip( item, math.max(oldLevel-sellLevels,0) )
	if not equipped then self:PerkShop_Equip( item, 0 ) end

	local refund,err = PerkShop:GetCost( item.Class, item.Category, oldLevel, newLevel or 1 )
	if refund==-1 then return false,err or "Failed to calculate value" end

	refund = math.floor(refund*0.75)

	local success,err = self:PerkShop_GivePoints( refund )
	if not success then return false,err or "Failed to refund "..PerkShop.PointsLabel end

	if newLevel>0 then
		return self:PerkShop_GiveItem( item, newLevel )
	else
		return self:PerkShop_TakeItem( item )
	end
end

concommand.Add( "perk_buy", function( p,c,a )
	if not (IsValid(p)) then return end
	local item = PerkShop:GetItem( a[2], a[1] )
	if item then
		local success,err = p:PerkShop_Buy( item, tonumber(a[3]) )
		if success then
			p:ChatPrint( string.format( "%sSuccessfully bought %s: %s %s", PerkShop.Tag, a[1], a[2], tonumber(a[3]) and "(level "..tonumber(a[3])..")" or "" ) )
		else
			p:ChatPrint( string.format( "%sPurchase failed. (%s)", PerkShop.Tag, err or "N/A" ) )
		end
	else
		p:ChatPrint( string.format( "%sPurchase failed. (Item %s_%s does not exist)", PerkShop.Tag, a[1], a[2] ) )
	end
end)
concommand.Add( "perk_sell", function( p,c,a )
	if not (IsValid(p)) then return end
	local item = PerkShop:GetItem( a[2], a[1] )
	if item then
		local success,err = p:PerkShop_Sell( item, tonumber(a[3]) )
		if success then
			p:ChatPrint( string.format( "%sSuccessfully sold %s: %s %s", PerkShop.Tag, a[1], a[2], tonumber(a[3]) and "("..tonumber(a[3]).." levels)" or "" ) )
		else
			p:ChatPrint( string.format( "%sSale failed. (%s)", PerkShop.Tag, err or "N/A" ) )
		end
	else
		p:ChatPrint( string.format( "%sSale failed. (Item %s_%s does not exist)", PerkShop.Tag, a[1], a[2] ) )
	end
end)


text:
require 'omniauth/oauth'
require 'multi_json'

module OmniAuth
  module Strategies
    # Authenticate to Facebook utilizing OAuth 2.0 and retrieve
    # basic user information.
    #
    # @example Basic Usage
    #   use OmniAuth::Strategies::Instagram, 'client_id', 'client_secret'
    class Instagram < OAuth2
      # @option options [String] :scope separate the scopes by a space
      def initialize(app, client_id = nil, client_secret = nil, options = {}, &block)
        client_options = {
          :site => "https://api.instagram.com/",
          :authorize_url      => "/oauth/authorize",
          :access_token_url   => "/oauth/access_token"
        }

        super(app, :instagram, client_id, client_secret, client_options, options, &block)
      end

      def request_phase
        options[:scope] ||= "basic"
        options[:response_type] ||= 'code'
        super
      end

      def callback_phase
        options[:grant_type] ||= 'authorization_code'
        super
      end

      def user_data
        @data ||= MultiJson.decode(@access_token.get("/v1/users/self"))
      end

      def user_info
        {
          'nickname' => user_data['data']['username'],
          'name' => user_data['data']['full_name'],
          'image' => user_data['data']['profile_picture'],
          'urls' => {}
        }
      end

      def auth_hash
        OmniAuth::Utils.deep_merge(super, {
          'uid' => user_data['data']['id'],
          'user_info' => user_info,
          'extra' => {'user_hash' => user_data['data']}
        })
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.tinkerpop.gremlin.driver.ser;

import org.apache.tinkerpop.gremlin.driver.MessageSerializer;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.HaltedTraverserStrategy;

/**
 * An enum of the default serializers.
 *
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public enum Serializers {

    /**
     * GraphSON 3.0.
     */
    GRAPHSON(SerTokens.MIME_JSON),
    GRAPHSON_V1D0(SerTokens.MIME_GRAPHSON_V1D0),
    GRAPHSON_V2D0(SerTokens.MIME_GRAPHSON_V2D0),
    GRAPHSON_V3D0(SerTokens.MIME_GRAPHSON_V3D0),
    GRAPHBINARY_V1D0(SerTokens.MIME_GRAPHBINARY_V1D0),

    /**
     * @deprecated As of release 3.4.3, replaced by {@link #GRAPHBINARY_V1D0}.
     */
    @Deprecated
    GRYO_V1D0(SerTokens.MIME_GRYO_V1D0),

    /**
     * @deprecated As of release 3.4.3, replaced by {@link #GRAPHBINARY_V1D0}.
     */
    @Deprecated
    GRYO_V3D0(SerTokens.MIME_GRYO_V3D0),

    /**
     * @deprecated As of release 3.2.6, not directly replaced - supported through {@link HaltedTraverserStrategy}.
     */
    @Deprecated
    GRYO_LITE_V1D0(SerTokens.MIME_GRYO_LITE_V1D0);

    private String value;

    Serializers(final String mimeType) {
        this.value = mimeType;
    }

    public String getValue() {
        return value;
    }

    public MessageSerializer simpleInstance() {
        switch (value) {
            case SerTokens.MIME_JSON:
                return new GraphSONMessageSerializerV3d0();
            case SerTokens.MIME_GRAPHSON_V1D0:
                return new GraphSONMessageSerializerGremlinV1d0();
            case SerTokens.MIME_GRAPHSON_V2D0:
                return new GraphSONMessageSerializerV2d0();
            case SerTokens.MIME_GRAPHSON_V3D0:
                return new GraphSONMessageSerializerV3d0();
            case SerTokens.MIME_GRYO_V1D0:
                return new GryoMessageSerializerV1d0();
            case SerTokens.MIME_GRYO_V3D0:
                return new GryoMessageSerializerV3d0();
            case SerTokens.MIME_GRYO_LITE_V1D0:
                return new GryoLiteMessageSerializerV1d0();
            case SerTokens.MIME_GRAPHBINARY_V1D0:
                return new GraphBinaryMessageSerializerV1();
            default:
                throw new RuntimeException("Could not create a simple MessageSerializer instance of " + value);
        }
    }
}


text:
/*jslint white:true, nomen: true, plusplus: true */
/*global mx, define, require, browser, devel, console */
/*mendix */
/*
    Calendar
    ========================

	@file      : calendar.js
	@version   : 4.0
	@author    : Pauline Oudeman - van der Kraats, Robert van 't Hof, Richard Edens, Roeland Salij
	@date      : 06-02-2015
	@copyright : Mendix Technology BV
	@license   : Apache License, Version 2.0, January 2004

	Documentation
    ========================
	FullCalendar implementation.
*/

// Required module list. Remove unnecessary modules, you can always get them back from the boilerplate.
require({
	packages: [{
			name: 'jquery',
			location: '../../widgets/calendar/lib',
			main: 'jquery-2.1.1.min'
    },
		{
			name: 'moment',
			location: '../../widgets/calendar/lib',
			main: 'moment.min'
               },
		{
			name: 'fullCalendar',
			location: '../../widgets/calendar/lib',
			main: 'fullcalendar.min'
               },
		{
			name: 'calendarLang',
			location: '../../widgets/calendar/lib',
			main: 'lang-all'
               }
              ]
}, [
    'dojo/_base/declare', 'mxui/widget/_WidgetBase', 'dijit/_TemplatedMixin',
    'mxui/dom', 'dojo/dom', 'dojo/query', 'dojo/dom-prop', 'dojo/dom-geometry', 'dojo/dom-class', 'dojo/dom-style', 'dojo/dom-construct', 'dojo/_base/array', 'dojo/_base/lang', 'dojo/text',
    'jquery', 'moment', 'fullCalendar', 'calendarLang', 'dojo/text!calendar/widget/template/Calendar.html'
], function (declare, _WidgetBase, _TemplatedMixin, dom, dojoDom, domQuery, domProp, domGeom, domClass, domStyle, domConstruct, dojoArray, lang, text, $, moment, fullCalendar, calendarLang, widgetTemplate) {
	'use strict';

	// Declare widget's prototype.
	return declare('calendar.widget.calendar', [_WidgetBase, _TemplatedMixin], {
		// _TemplatedMixin will create our dom node using this HTML template.
		templateString: widgetTemplate,

		// Internal variables. Non-primitives created in the prototype are shared between all widget instances.
		_mxObj: null,
		_calendarBox: null,
		_handles: null,
		_header: null,
		_buttonText: null,
		_hasStarted: null,
		_eventIsClicked: false,
		_views	: null,
		_titleFormat: null,
		_dateFormat: null,
		_timeFormat: null,
		_colors: null,
		_eventSource: null,
		_fcNode: null,
		_availableViews: null,
		_allowCreate: true,

		postCreate: function () {
			console.debug('Calendar - startup');

			this._colors = this.notused; //workaround for legacy users
			this._availableViews = this.notused1; //workaround for legacy users
			this._setDefaults(); //set default formatting options
			this._handles = [];
			this._eventSource = [];
			this._allowCreate = this.editable || (this.neweventmf !== null && this.neweventmf !== '');
			//make a calendarbox
			this._calendarBox = dom.create('div', {
				'id': 'calendar_' + this.id
			});
			domConstruct.place(this._calendarBox, this.domNode);

			this._fcNode = $('#calendar_' + this.id);

			this._renderCalendar(null);

		},

		update: function (obj, callback) {
			console.debug('Calendar - update');

			if (this._handles.length > 0) {
				dojoArray.forEach(this._handles, function (handle) {
					mx.data.unsubscribe(handle);
				});
			}
            this._handles = [];

			if (obj) {
				this._mxObj = obj;
				this._fetchObjects();
			}

			//subscribe to changes in the event entity and context object(if applicable).
			this._addSubscriptions();

			if (typeof callback !== 'undefined') {
				callback();
			}
		},

		resize: function () {
			console.debug('Calendar - resize');
			this._fcNode.fullCalendar('render');
			this._fetchObjects();
		},

		_addSubscriptions: function () {
			var subscription = mx.data.subscribe({
					entity: this.eventEntity,
					callback: lang.hitch(this, function (entity) {
						//we re-fetch the objects, and refresh them on the calendar
						this._fetchObjects();
					})
				}),
				contextSubscription = null;

			this._handles.push(subscription);

			if (this._mxObj){
				contextSubscription = mx.data.subscribe({
					guid: this._mxObj.getGuid(),
					callback: lang.hitch(this, function (guid) {
						this._fetchObjects();
					})
				});

				this._handles.push(contextSubscription);
			}

		},

		_fetchObjects: function () {
			console.debug('Calendar - fetch objects');
			var constraint = null,
				expectObj = null,
				xpath = null,
				errordiv = null;

			if (this.dataSourceType === "xpath") {
				constraint = this.eventConstraint;
				expectObj = this.eventConstraint.indexOf('[%CurrentObject%]') >= 0;

				if (this._mxObj && expectObj) {
					constraint = this.eventConstraint.replace(/\[%CurrentObject%\]/gi, this._mxObj.getGuid());
				} else if (expectObj) {
					this._clearCalendar();
					return;
				}

				xpath = '//' + this.eventEntity + constraint;
				mx.data.get({
					xpath: xpath,
					callback: lang.hitch(this, this._prepareEvents)
				}, this);
			} else if (this.dataSourceType === "contextmf" && this.contextDatasourceMf) {

				if (this._mxObj) {
					this._execMF(this._mxObj, this.contextDatasourceMf, lang.hitch(this, this._prepareEvents));
				}
			} else if (this.dataSourceType === "mf" && this.datasourceMf) {
				this._execMF(null, this.datasourceMf, lang.hitch(this, this._prepareEvents));
			} else {

				domConstruct.empty(this.domNode);
				if (this.dataSourceType === "contextmf") {
					errordiv = dom.div("Data source type 'Microflow with context object' is selected, but no microflow was specified for property 'Dataview data source microflow'");
				} else if (this.dataSourceType === "mf") {
					errordiv = dom.div("Data source type 'Microflow' is selected, but no microflow was specified for property 'Data source microflow'");
				}

				domStyle.set(errordiv, {
					"border": "1px solid red",
					"color": "red",
					"padding": "5px"
				});
				this.domNode.appendChild(errordiv);
			}
		},

		_clearCalendar: function () {
			console.debug('Calendar - clear calendar');
			if (this._fcNode) {
				this._fcNode.fullCalendar('removeEvents');
			}
		},

		_prepareEvents: function (objs) {
			console.debug('Calendar - prepare events');
			var objTitles = null,
				objRefs = null,
				refTitles = null,
				split = null,
				thisRef = null;

			objTitles = {};
			objRefs = [];
			refTitles = {};
			split = this.titleAttr.split("/");
			thisRef = null;

			if (split.length === 1) {
				// titleAttr is a simple attribute and the key of objTitles is
				// the GUID of the object and the title is the attribute.
				$.each(objs, lang.hitch(this, function (index, obj) {
					objTitles[obj.getGUID()] = obj.get(this.titleAttr);
				}));
				this._createEvents(objs, objTitles);
			} else if (split.length === 3) {

				// titleAttr is a reference and we have more work to do.
				$.each(objs, function (index, obj) {
					thisRef = obj.getAttribute(split[0]);
					objTitles[obj.getGUID()] = thisRef;
					// objRefs should only contain the unique list of referred objects.
					if (objRefs.indexOf(thisRef) < 0) {
						objRefs.push(thisRef);
					}
				});
				// Now get the actual title strings from the list of referred objects ...
				// This is an asynchronous call.
				mx.data.get({
					guids: objRefs,
					nocache: false,
					callback: function (refObjs) {
						var i = null,
							index = null,
							thisValue = null;

						// Get the title string for each referenced object and store it
						// as the value in the refTitles array.
						for (i = 0; i < refObjs.length; i++) {
							refTitles[refObjs[i].getGUID()] = refObjs[i].get(split[2]);
						}
						// Now, loop through the objTitles array and replace the value (which is
						// is the GUID of the referred object) with the actual title string extracted
						// from the referred object.
						for (index in objTitles) {
							if (objTitles.hasOwnProperty(index)) {
								thisValue = objTitles[index];
								objTitles[index] = refTitles[objTitles[index]];
							}
						}
						// Now that we finally have all of the referenced titles, we can call
						// createEvents()
						this._createEvents(objs, objTitles);

					}
				}, this);
				//this._createEvents(objs, objTitles);
			} else {
				// this should never happen and is likely an error
				console.error("Error in titleAttr: " + this.titleAttr + ". This should be either a simple attribute or a 1-deep reference.");
			}
		},

		_createEvents: function (objs, titles) {
			console.debug('Calendar - create events');
			var events = [],
				objcolors = null;

			$.each(objs, lang.hitch(this, function (index, obj) {
				//get the colors
				if (this._colors.length > 0 && this.typeAttr) {
					objcolors = this._getObjectColors(obj);
				}
				//get the dates
				var start = new Date(obj.get(this.startAttr)),
					end = new Date(obj.get(this.endAttr)),

					//create a new calendar event
					newEvent = {
						title: titles[obj.getGUID()],
						start: start,
						end: end,
						allDay: obj.get(this.alldayAttr),
						editable: this.editable,
						mxobject: obj //we add the mxobject to be able to handle events with relative ease.
					};

				if (objcolors) {
					newEvent.backgroundColor = objcolors.backgroundColor;
					newEvent.borderColor = objcolors.borderColor;
					newEvent.textColor = objcolors.textColor;
				}
				events.push(newEvent);
			}));
			//check if the calendar already exists (are we just updating events here?)
			if (this._fcNode.hasClass('fc')) {
				//if it does, remove, add the new source and refetch
				this._fcNode.fullCalendar('render');
				if (this._eventSource && this._eventSource.length >= 1) {
					this._fcNode.fullCalendar('removeEventSource', this._eventSource);
				}

				this._fcNode.fullCalendar('addEventSource', events);
				this._fcNode.fullCalendar('refetchEvents');
			} else {
				//else create the calendar
				this._renderCalendar(events);
			}
			this._eventSource = events;
		},

		_renderCalendar: function (events) {
			console.debug('Calendar - render calendar');
			var options = this._setCalendarOptions(events);

			this._fcNode.fullCalendar(options);

			//go to the startposition if we have one
			if (this._mxObj && this._mxObj.get(this.startPos)) {
				this._fcNode.fullCalendar('gotoDate', new Date(this._mxObj.get(this.startPos)));
			}
		},

		_onEventChange: function (event, dayDelta, minuteDelta, allDay, revertFunc) {
			console.debug('Calendar - on event change');
			var obj = event.mxobject;
			this._setVariables(obj, event, this.startAttr, this.endAttr, allDay);
			this._execMF(obj, this.onchangemf);
		},

		_onEventClick: function (event) {
			console.debug('Calendar - on event click');
			var obj = event.mxobject;
			this._setVariables(obj, event, this.startAttr, this.endAttr);
			this._execMF(obj, this.onclickmf);
		},

		_onSelectionMade: function (startDate, endDate, allDay, jsEvent, view) {
			console.debug('Calendar - on selection made');
			var eventData = {
				start: startDate,
				end: endDate
			};

			if (!this._eventIsClicked) {

				mx.data.create({
					entity: this.eventEntity,
					callback: function (obj) {
						this._setVariables(obj, eventData, this.startAttr, this.endAttr, allDay);
						if (this._mxObj && this.neweventref !== '') {
							obj.addReference(this.neweventref.split('/')[0], this._mxObj.getGuid());
						}
						this._execMF(obj, this.neweventmf);
					},
					error: function (err) {
						console.warn('Error creating object: ', err);
					}
				}, this);

				this._eventIsClicked = true;

				setTimeout(lang.hitch(this, function () {
					this._eventIsClicked = false;
				}), 1000);
			}
		},

		_getObjectColors: function (obj) {
		console.debug('Calendar - get object colors ' + obj.getGUID());

			var objcolors = null;

			$.each(this._colors, lang.hitch(this, function (index, color) {
				//set color when enum color equals the color we have on file
				if (obj.get(this.typeAttr) === color.enumKey) {
					objcolors = {
						backgroundColor: color.bgColor,
						borderColor: color.border,
						textColor: color.textColor
					};

					//We have found the color so we can stop iterating
					return false;
				}
			}));

			return objcolors;
		},

		_setVariables: function (obj, event, startAttribute, endAttribute, allDay) {
			console.debug('Calendar - set variables');
			//update the mx object
			obj.set(startAttribute, event.start);
			if (event.end !== null) {
				obj.set(endAttribute, event.end);
			}

			if (allDay !== null) {
				obj.set(this.alldayAttr, allDay);
			}
		},

		_setDefaults: function () {
			console.debug('Calendar - set defaults');
			var views = [];

			this._header = {
				left: 'title',
				center: ''
			};

			this._titleFormat = {
				month: 'MMMM YYYY', // September 2009
				week: "MMM D YYYY", // Sep 13 2009
				day: 'MMMM D YYYY' //  Sep 8, 2009
			};

			if (this.titleFormat) {
				this._titleFormat[''] = this.titleFormat;
			}

			this._dateFormat = this.dateFormat || {
				month: 'ddd', // Mon
				week: 'ddd M/D', // Mon 9/7
				day: 'dddd M/D' // Monday 9/7
			};

			if (this.dateFormat) {
				this._dateFormat[''] = this.dateFormat;
			}

			this._timeFormat = {};
			if (this.timeFormat) {
				this._timeFormat[''] = this.timeFormat;
			}

			this._buttonText = {};

			this._views = {};

			if (this._availableViews.length > 0) {
				//fill default specifics
				$.each(this._availableViews, lang.hitch(this, function (index, view) {
					var viewName = view.availableViews;
					views.push(viewName);

					this._views[viewName] = {};

					if (view.eventLimit > 0) {
						this._views[viewName].eventLimit = view.eventLimit;
					}

					if (view.titleFormatViews !== '') {
						this._titleFormat[viewName] = view.titleFormatViews;
					}
					if (view.dateFormatViews !== '') {
						this._dateFormat[viewName] = view.dateFormatViews;
					}
					if (view.timeFormatViews !== '') {
						this._timeFormat[viewName] = view.timeFormatViews;
					}

					if (view.labelViews !== '') {
						this._buttonText[viewName] = view.labelViews;
					}
				}));

			}

			if (this.todaycaption) {
				this._buttonText.today = this.todaycaption;
			}

			this._header.right = 'today ' + views.join() + ' prev,next';

			this.monthNamesFormat = this.monthNamesFormat ? this.monthNamesFormat.split(",") : null;
			this.monthShortNamesFormat = this.monthShortNamesFormat ? this.monthShortNamesFormat.split(",") : null;
			this.dayNamesFormat = this.dayNamesFormat ? this.dayNamesFormat.split(",") : null;
			this.dayShortNamesFormat = this.dayShortNamesFormat ? this.dayShortNamesFormat.split(",") : null;
			this.slotMinutes = this.slotMinutes ? this.slotMinutes : '00:30:00';
			this.axisFormat = this.axisFormat ? this.axisFormat : 'h(:mm)a';
			this.startTime = this.startTime ? this.startTime : '08:00';
			this.endTime = this.endTime ? this.endTime : '17:00';

		},

		_setCalendarOptions: function (events) {
			console.debug('Calendar - set calendar options');
			var options = {
				//contents
				header: this._header,
				events: events,
				//configs
				editable: this._allowCreate, //allows resizing events
				selectable: this._allowCreate, //allows selecting a portion of the day or one or multiple days (based on the view)
				//event handling
				eventResize: lang.hitch(this, this._onEventChange), //is called when an event is dragged and has changed
				eventDrop: lang.hitch(this, this._onEventChange), //is called when an event is dragged and has changed
				eventClick: lang.hitch(this, this._onEventClick), //is called when an event is clicked
				viewRender: lang.hitch(this, this._onViewChange), //is called when the view (start/end on month, week, etc) has changed
				select: lang.hitch(this, this._onSelectionMade), //is called after a selection has been made
				//appearance
				timezone: 'local',
				views : this._views,
				defaultView: this.defaultView,
				firstDay: this.firstday,
				height: this.calHeight,
				weekNumbers: this.showWeekNumbers,
				weekNumberTitle: this.weeknumberTitle,
				weekends: this.showWeekends,
				slotDuration: this.slotMinutes,
				axisFormat: this.axisFormat,
				buttonText: this._buttonText,
				lang: this.languageSetting,
				eventLimit: this.limitEvents
			};

			if (this._titleFormat) {
				options.titleFormat = this._titleFormat;
			}
			if (this._timeFormat) {
				options.timeFormat = this._timeFormat;
			}
			if (this._dateFormat) {
				options.columnFormat = this._dateFormat;
			}
			if (this.monthNamesFormat) {
				options.monthNames = this.monthNamesFormat;
			}
			if (this.monthShortNamesFormat) {
				options.monthNamesShort = this.monthShortNamesFormat;
			}
			if (this.dayNamesFormat) {
				options.dayNames = this.dayNamesFormat;
			}
			if (this.dayShortNamesFormat) {
				options.dayNamesShort = this.dayShortNamesFormat;
			}
			if (this.alldaycaption) {
				options.allDayText = this.alldaycaption;
			}
			if (this.businessHours) {
				options.businessHours = {
					start: this.startTime,
					end: this.endTime,
					dow: [1, 2, 3, 4, 5]
				};
			}
			return options;
		},

		_execMF: function (obj, mf, cb) {
			if (mf) {
				var params = {
					applyto: "selection",
					actionname: mf,
					guids: []
				};
				if (obj) {
					params.guids = [obj.getGuid()];
				}
				mx.data.action({
					params: params,
					callback: function (objs) {
						if (cb) {
							cb(objs);
						}
					},
					error: function (error) {
						if (cb) {
							cb();
						}
						console.warn(error.description);
					}
				}, this);

			} else if (cb) {
				cb();
			}
		},

		//            _execMFFromUI : function (obj, mf, cb) {
		//                console.debug('Calendar - exec mf from ui');
		//                if (mf) {
		//                    var params = {
		//                        applyto		: "selection",
		//                        guids : []
		//                    };
		//                    if (obj) {
		//                        params.guids = [obj.getGuid()];
		//                    }
		//
		//                    mx.ui.action(mf, {
		//                        context: new mendix.lib.MxContext(),
		//                        progress: "modal",
		//                        params	: params,
		//                        callback: function(result) {
		//                            if (cb) {
		//                                cb(result);
		//                            }
		//                        }
		//                    });
		//
		//                } else if (cb) {
		//                    cb();
		//                }
		//
		//            },

		_onViewChange: function (view, element) {

			if(this.viewChangeEntity !== '') {
				var eventData = {
					start: view.start,
					end: view.end
				};

				mx.data.create({
					entity: this.viewChangeEntity,
					callback: function (obj) {
						this._setVariables(obj, eventData, this.viewStartAttr, this.viewEndAttr);
						this._execMF(obj, this.onviewchangemf);
					},
					error: function (err) {
						console.warn('Error creating object: ', err);
					}
				}, this);
			}
		},

		uninitialize: function () {
			if (this._handles.length > 0) {
				dojoArray.forEach(this._handles, function (handle) {
					mx.data.unsubscribe(handle);
				});
			}
		}

	});
});


text:
require 'spec_helper'

describe Boffin::Tracker do
  before :all do
    SpecHelper.flush_keyspace!
    @tracker   = Boffin::Tracker.new(MockDitty, [:views, :likes, :shares])
    @instance1 = MockDitty.new(100)
    @instance2 = MockDitty.new(200)
    @instance3 = MockDitty.new(300)
    @instance4 = MockDitty.new(400)
    @user1     = MockUser.new(1)
    @user2     = MockUser.new(2)
    @date      = Date.today

    Timecop.freeze(@date - 2) do
      @tracker.hit(:views, @instance3)
      @tracker.hit(:likes, @instance3, :unique => [@user1])
      @tracker.hit(:views, @instance3, :unique => ['sess.1'])
      @tracker.hit(:views, @instance3, :unique => ['sess.2'])
      @tracker.hit(:views, @instance3, :unique => [@user2])
      @tracker.hit(:likes, @instance1, :unique => [nil, nil])
      @tracker.hit(:views, @instance3, :unique => ['sess.4'])
      @tracker.hit(:views, @instance3, :unique => [@user1])
      @tracker.hit(:views, @instance2, :unique => [@user2])
      @tracker.hit(:views, @instance3, :unique => [@user2])
      @tracker.hit(:likes, @instance3)
      @tracker.hit(:views, @instance3, :unique => ['sess.1'])
      @tracker.hit(:views, @instance3)
      @tracker.hit(:likes, @instance3, :unique => [@user1])
      @tracker.hit(:views, @instance3, :unique => ['sess.1'], :increment => 2)
    end

    Timecop.freeze(@date - 1) do
      @tracker.hit(:views, @instance1)
      @tracker.hit(:likes, @instance2, :unique => [@user1])
      @tracker.hit(:views, @instance2, :unique => ['sess.4'])
      @tracker.hit(:views, @instance2, :unique => [nil, @user1])
      @tracker.hit(:views, @instance2, :unique => ['sess.3'])
      @tracker.hit(:views, @instance1, :unique => ['sess.3'])
      @tracker.hit(:views, @instance1, :unique => [@user1])
      @tracker.hit(:views, @instance2, :unique => ['sess.2'])
      @tracker.hit(:views, @instance1, :unique => [@user1])
      @tracker.hit(:views, @instance1, :unique => [@user2])
    end

    @tracker.hit(:views, @instance3, :unique => ['sess.2'])
    @tracker.hit(:views, @instance2, :unique => [@user2])
    @tracker.hit(:likes, @instance2)
    @tracker.hit(:views, @instance2, :unique => [@user1])
    @tracker.hit(:views, @instance1, :unique => ['sess.4'])
    @tracker.hit(:views, @instance3, :unique => ['sess.3'])
    @tracker.hit(:views, @instance1, :unique => [@user1])
    @tracker.hit(:views, @instance1, :unique => [@user2])
  end

  describe '#hit' do
    it 'throws an error if the hit type is not in the list' do
      lambda { @tracker.hit(:view, @instance1) }.
        should raise_error Boffin::UndefinedHitTypeError
    end
  end

  describe '#hit_count' do
    it 'throws an error if the hit type is not in the list' do
      lambda { @tracker.count(:view, @instance1) }.
        should raise_error Boffin::UndefinedHitTypeError
    end

    it 'returns the raw hit count for the instance' do
      @tracker.count(:views, @instance1).should == 8
    end

    it 'returns 0 for an instance that was never hit' do
      @tracker.count(:views, 'neverhit').should == 0
    end

    it 'returns the unique hit count for the instance' do
      @tracker.count(:views, @instance1, :unique => true).should == 5
    end

    it 'returns 0 for an instance that was never hit' do
      @tracker.count(:likes, @instance4, :unique => true).should == 0
    end
  end

  describe '#hit_count_for_session_id' do
    it 'throws an error if the hit type is not in the list' do
      lambda { @tracker.count(:view, @instance1, :unique => 'sess.1') }.
        should raise_error Boffin::UndefinedHitTypeError
    end

    it 'returns the number of times the instance was hit by the session id' do
      @tracker.count(:views, @instance3, :unique => 'sess.1').should == 3
    end

    it 'returns a count of 0 if the session id never hit the instance' do
      @tracker.count(:views, @instance1, :unique => 'nohit').should == 0
    end
  end

  describe '#top' do
    it 'throws an error if passed hit type is invalid' do
      lambda { @tracker.top(:view, :days => 3) }.
        should raise_error Boffin::UndefinedHitTypeError
    end

    it 'throws an error if passed weights with hit type that is invalid' do
      lambda { @tracker.top({ :view => 1 }, :days => 3) }.
        should raise_error Boffin::UndefinedHitTypeError
    end

    it 'returns ids ordered by hit counts of weighted totals' do
      ids = @tracker.top({ :views => 1, :likes => 2 }, :days => 3)
      ids.should == ['300', '200', '100']
    end

    it 'returns ids ordered by total counts of a specific hit type' do
      ids = @tracker.top(:views, :days => 3)
      ids.should == ['300', '100', '200']
    end

    it 'returns ids in ascending order when passed { order: "asc" } as an option' do
      ids = @tracker.top(:views, :days => 3, :order => 'asc')
      ids.should == ['200', '100', '300']
    end

    it 'throws an error if the specified order is not valid' do
      lambda { @tracker.top(:views, :days => 3, :order => 'desk') }.
        should raise_error ArgumentError
    end

    it 'returns ids and counts when passed { counts: true } as an option' do
      ids = @tracker.top(:views, :days => 3, :counts => true)
      ids.should == [
        ['300', 13],
        ['100', 8],
        ['200', 7]
      ]
    end

    it 'returns ids based on unique hit data when passed { unique: true } as an option' do
      ids = @tracker.top(:views, :days => 3, :counts => true, :unique => true)
      ids.should == [
        ['300', 7],
        ['200', 5],
        ['100', 5]
      ]
    end
  end

  describe '#keyspace' do
    it 'returns a keyspace' do
      @tracker.keyspace.unique_namespace?.should be_false
    end

    it 'returns a unique keyspace when passed true' do
      @tracker.keyspace(true).unique_namespace?.should be_true
    end
  end
end


text:
package controllers

import play.api.mvc.Action;
import play.api.mvc.Controller;
import play.api.mvc.AnyContent;
import play.api.mvc.Request;
import play.api.mvc.Result;
import play.api.Play;
import play.api.Play.current;
import play.api.cache.Cache;

import play.api.data.Form;
import play.api.data.Forms.tuple;
import play.api.data.Forms.nonEmptyText;
import play.api.data.Forms.text;
import play.api.data.Forms.boolean;
import play.api.data.Forms.optional;

import java.io.File;

import jp.co.flect.formvalidation.salesforce.SalesforceObjectBuilder;
import jp.co.flect.formvalidation.salesforce.SalesforceInfo;
import jp.co.flect.salesforce.SalesforceClient;
import jp.co.flect.log.Level;
import jp.co.flect.play2.utils.Params;
import jp.co.flect.net.OAuth2;

object Salesforce extends Controller {

  private val AUTH_URL  = "https://login.salesforce.com/services/oauth2/authorize";
  private val TOKEN_URL = "https://login.salesforce.com/services/oauth2/token";

  private val APPID    = sys.env.get("SALESFORCE_APPID");
  private val SECRET   = sys.env.get("SALESFORCE_SECRET");

  private val baseClient = new SalesforceClient(new File("conf/salesforce/partner.wsdl"));

  private def enabled = APPID.nonEmpty && SECRET.nonEmpty;
  private def cacheKey(implicit request: Request[AnyContent]) = Params(request).sessionId + "-clilent";

  def filterAction(f: Request[AnyContent] => Result): Action[AnyContent] = Action { request =>
    if (!enabled) {
      Ok("Not supported feature.");
    } else if (Play.isProd && request.headers.get("x-forwarded-proto").getOrElse("http") == "http") {
      Redirect("https://" + request.host + request.path);
    } else {
      f(request);
    }
  }

  def prepare = filterAction { implicit request =>
    Cache.get(cacheKey) match {
      case Some(client) =>
        Ok(views.html.salesforcePrepare());
      case None =>
        Redirect("/salesforce/login");
    }
  }

  def login(code: String, sandbox: Boolean) = filterAction { implicit request =>
    val (authUrl, tokenUrl) = if (sandbox) {
      (AUTH_URL.replace("login.salesforce.com", "test.salesforce.com"),
       TOKEN_URL.replace("login.salesforce.com", "test.salesforce.com"));
    } else {
      (AUTH_URL, TOKEN_URL);
    }
    val loginUrl = "http://" + request.host + "/salesforce/login";
    val oauth = new OAuth2(
      authUrl,
      tokenUrl,
      APPID.get,
      SECRET.get,
      loginUrl
    );
    if (code.isEmpty) {
      Ok(views.html.salesforceLogin(oauth));
    } else {
      val res = oauth.authenticate(code);
      val client = new SalesforceClient(baseClient);
      client.getLogger.setLevel(Level.TRACE);
      if (sandbox) {
        val endpoint = client.getEndpoint().replace("login.salesforce.com", "test.salesforce.com");
        client.setEndpoint(endpoint);
      }
      client.login(res);
      Cache.set(cacheKey, client, 60 * 60);
      Redirect("/salesforce/prepare");
    }
  }

  private val createForm = Form(
    tuple(
      "name" -> nonEmptyText,
      "label" -> optional(text),
      "description" -> optional(text),
      "json" -> nonEmptyText,
      "useEmailField" -> boolean,
      "useUrlField" -> boolean
    )
  );

  def create = filterAction { implicit request =>
    val form = createForm.bindFromRequest;
    if (form.hasErrors) {
      BadRequest;
    } else {
      val (name, label, desc, json, useEmailField, useUrlField) = form.get;
      Cache.getAs[SalesforceClient](cacheKey) match {
        case Some(client) =>
          val builder = new SalesforceObjectBuilder(client, new File("conf/salesforce/metadata.wsdl"));
          builder.setUseEmailField(useEmailField);
          builder.setUseUrlField(useUrlField);
          try {
            val info = new SalesforceInfo(name);
            label.foreach(info.setLabel(_));
            desc.foreach(info.setDescription(_));

            builder.generate(info, json);
            Ok("OK");
          } catch {
            case e: Exception =>
              Ok(e.getMessage);
          }
        case None =>
          Redirect("/salesforce/login");
      }
    }
  }

}


text:
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType

from wagtail.wagtailadmin import widgets

from wagtail.wagtailcore.models import Page
from wagtail.tests.testapp.models import SimplePage, EventPage

class TestAdminPageChooserWidget(TestCase):
    def setUp(self):
        self.root_page = Page.objects.get(id=2)

        # Add child page
        self.child_page = SimplePage(
            title="foobarbaz",
            slug="foobarbaz",
        )
        self.root_page.add_child(instance=self.child_page)

    def test_render_html(self):
        widget = widgets.AdminPageChooser()

        html = widget.render_html('test', None, {})
        self.assertIn("<input name=\"test\" type=\"hidden\" />", html)

    def test_render_js_init(self):
        widget = widgets.AdminPageChooser()

        js_init = widget.render_js_init('test-id', 'test', None)
        self.assertEqual(js_init, "createPageChooser(\"test-id\", [\"wagtailcore.page\"], null);")

    def test_render_html_with_value(self):
        widget = widgets.AdminPageChooser()

        html = widget.render_html('test', self.child_page, {})
        self.assertIn("<input name=\"test\" type=\"hidden\" value=\"%d\" />" % self.child_page.id, html)

    def test_render_js_init_with_value(self):
        widget = widgets.AdminPageChooser()

        js_init = widget.render_js_init('test-id', 'test', self.child_page)
        self.assertEqual(js_init, "createPageChooser(\"test-id\", [\"wagtailcore.page\"], %d);" % self.root_page.id)

    # def test_render_html_init_with_content_type omitted as HTML does not
    # change when selecting a content type

    def test_render_js_init_with_content_type(self):
        content_type = ContentType.objects.get_for_model(SimplePage)
        widget = widgets.AdminPageChooser(content_type=content_type)

        js_init = widget.render_js_init('test-id', 'test', None)
        self.assertEqual(js_init, "createPageChooser(\"test-id\", [\"tests.simplepage\"], null);")

    def test_render_js_init_with_multiple_content_types(self):
        content_types = [
            # Not using get_for_models as we need deterministic ordering
            ContentType.objects.get_for_model(SimplePage),
            ContentType.objects.get_for_model(EventPage),
        ]
        widget = widgets.AdminPageChooser(content_type=content_types)

        js_init = widget.render_js_init('test-id', 'test', None)
        self.assertEqual(js_init, "createPageChooser(\"test-id\", [\"tests.simplepage\", \"tests.eventpage\"], null);")


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>markdown-to-ast: online parsing demo</title>
    <link rel="stylesheet" href="css/style.css">

Input: Markdown

            <textarea id="js-input" class="textarea"></textarea>

Output: TxtNode AST

            <textarea id="js-output" class="textarea"></textarea>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>CTEST_USE_LAUNCHERS — CMake 3.8.1 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="CPACK_ABSOLUTE_DESTINATION_FILES" href="CPACK_ABSOLUTE_DESTINATION_FILES.html" />
    <link rel="prev" title="CTEST_UPDATE_VERSION_ONLY" href="CTEST_UPDATE_VERSION_ONLY.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-variables(7) »

CTEST_USE_LAUNCHERS¶

Specify the CTest UseLaunchers setting
in a ctest(1) dashboard client script.

Previous topic

CTEST_UPDATE_VERSION_ONLY

Next topic

CPACK_ABSOLUTE_DESTINATION_FILES

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-variables(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Entities
{
   public class Items : IEntity
    {
        public virtual long Id { get; set; }

        public virtual bool Archived { get; protected set; }

        public virtual bool ArchivedbyAdmin { get; protected set; }

        public virtual string Category { get; set; }

        public virtual string Title { get; set; }

       [DataType(DataType.MultilineText)]
        public virtual string Description { get; set; }

        public virtual string Price { get; set; }

        public virtual string BusinessType { get; set; }

        public virtual string VideoUrl { get; set; }

        public virtual string ImagesUrl { get; set; }

       public virtual long UserId { get; set; }

       public virtual DateTime Date { get; set; }

       public virtual int Views { get; set; }

       public Items()
       {
           Archived = false;

           ArchivedbyAdmin = false;
       }

        public virtual void Archive()
        {
            Archived = true;

        }

        public virtual void Activate()
        {
            Archived = false;
        }

        public virtual void AArchive()
        {
            ArchivedbyAdmin = true;

        }

        public virtual void AActivate()
        {
            ArchivedbyAdmin = false;
        }
    }
}


text:
r"""Common logic for the conversion modules

This logic is used by every module but temperature.py as temperature conversions are mre complex than multiplying
by a conversion coefficient.

"""

code = """def %s(**kwargs):
    if len(kwargs.items()) != 1:
        raise ValueError("Too many keywords")
    try:
        # wrapping in list of keys and values if for Python 3 compatibility
        result = list(kwargs.values())[0] * %s[list(kwargs.keys())[0]] / %s['%s']
    except KeyError:
        raise KeyError("Unknown input unit")
    return result
"""

def create_code(dict_name, key_name):
    r"""Create the code to be compiled on the fly by the conversion modules

    Parameters
    ----------
    dict_name : str
        The name of the dictionnary that defines the units in the conversion module
    key_name : str
        The key name in the dictionnary that defines the units in the conversion module

    Returns
    -------
    str
        Python code string

    """
    return code % (key_name, dict_name, dict_name, key_name)


text:
%	The MIT License (MIT)
%
% 	Copyright (c) 2013-2014 Thomas Kober
%
classdef LineCorrData<handle
    %LINECORRDATA Encapsulates line specific correspondence data

    methods (Access = public)
        function obj = LineCorrData(houghline)
        %LINECORRDATA constructor
            obj.collect_data(houghline);
        end;
    end;

    properties (GetAccess = public, SetAccess = private)
        rho;            % Hough Line Rho Value
        theta;          % Hough Line Theta Value
        length;         % Hough Line Length
        mid_point;      % Hough Line Mid Point
        start_point;    % Hough Line Start Point
        end_point;      % Hough Line End Point
    end;

    methods (Access = private)
        function collect_data(obj, houghline)
        %COLLECT_DATA collect all data from the given houghline

            obj.rho = houghline.rho;
            obj.theta = houghline.theta;
            obj.start_point = houghline.point1;
            obj.end_point = houghline.point2;
            obj.length = norm(houghline.point1 - houghline.point2);

            mid_x = min(houghline.point2(1, 1), houghline.point1(1, 1)) + (abs(houghline.point2(1, 1) - houghline.point1(1, 1)) / 2);
            mid_y = min(houghline.point2(1, 2), houghline.point1(1, 2)) + (abs(houghline.point2(1, 2) - houghline.point1(1, 2)) / 2);
            obj.mid_point = [mid_x mid_y];
        end;
    end;

end


text:
import React from 'react'

const cn = require('classnames/bind').bind(require('./select.scss'))

/**
 * 下拉菜单
 * @param {object} props {
 *      list:[{id,name},...]
 *      onSelected:(id,name,e)
 * }
 */
class Select extends React.Component {
    constructor(...props) {
        super(...props)
        const first = this.props.list[0]
        this.state = {
            dropShow: false //标记是否显示下拉选择框
        }
        this.curItem = {
            id: first.id,
            name: first.name
        }
        this.selectHandle = this.selectHandle.bind(this)
        this.clickHandle = this.clickHandle.bind(this)
    }

    getCurId(){
        return this.curItem.id
    }

    selectHandle(id, name, e) {
        this.curItem = {
            id: id,
            name: name
        }
        this.setState({
            dropShow: false
        })
    }

    clickHandle(e) {
        this.setState({
            dropShow: true
        })
    }

    render() {
        const dropShow = this.state.dropShow
        return (

                <ShowItem act={dropShow} onClick={this.clickHandle} name={this.curItem.name}/>
                {dropShow && <DropList list={this.props.list} onSelected={this.selectHandle}/>}

        )
    }
}

/**
 *
 * @param {object} props {
 *      name:
 *      act:
 *      onClick:
 * }
 * @constructor
 */
const ShowItem = props =>

        {props.name}

/**
 *
 * @param {object} props {
 *      list:[{id,name},...]
 *      onSelected:(id,name,e)
 * }
 * @constructor
 */
const DropList = props =>

{props.list.map(i => <DropItem key={i.id} id={i.id} name={i.name}
                                                                   onClick={props.onSelected}/>)}

/**
 *
 * @param {object} props {
 *      id:
 *      name:
 *      onClick: 点击回调 (id,name,event)
 * }
 * @constructor
 */
const DropItem = props =>

 {
        props.onClick(props.id, props.name, e)
    }}>{props.name}

export default Select


text:
layout: post
title: "Сборка ссылок: Тестирование"
description: "Куда сейчас без тестрирования? Видов тестирования много, очень много. В этом посте вы сможете найти некоторые ссылки на интересные статьи по тестированию софта, а также высоконагруженному тестированию"
category: ссылки
tags: [ссылки, тестирование, highload]
---

Куда сейчас без тестрирования? Видов тестирования много, очень много. В этом посте вы сможете найти некоторые ссылки на интересные статьи по тестированию софта, а также высоконагруженному тестированию

<!--more-->

### Введение

Основы:

* [Software QA Course](http://www.youtube.com/playlist?list=PL7XXjge0nKZeMrUMHotK3_OdgCG1xm6yG)
* [Как тестировать карандаш?](http://www.youtube.com/watch?v=Erctsy6i0zo) - дает представление о том что есть несколько видов тестирования

Блоги:

* [Блог о тестировании программного обеспечения](http://andzhukov.blogspot.ru/)

### Тестирование в программировании

Unit test:

* [Как начать писать тесты за 10 шагов по 10 минут](http://habrahabr.ru/company/infopulse/blog/177581/)
* [Юнит-тестирование для чайников](http://habrahabr.ru/company/etnasoft/blog/169381/)
* [Учимся любить юнит тесты](http://xp.1024.info/Articles/LoveUT.html)

Уже имеем немного опыта:

* [Unit тесты на практике](http://habrahabr.ru/post/191986/)
* [Об использовании модульных тестов и TDD](http://eax.me/unit-testing/)
* [Как научиться писать юнит-тесты, в которых будет смысл и не ошалеть от скуки?](http://toster.ru/q/42652)
* [Тестирование — это не поиск ошибок!](http://habrahabr.ru/post/149903/)
* [Эволюция юнит-теста](http://habrahabr.ru/post/107262/)
* [Тесты вперед?](http://blog.byndyu.ru/2008/10/blog-post_26.html)

Модульное тестирование:

* [Модульное тестирование](http://ru.wikipedia.org/wiki/%D0%9C%D0%BE%D0%B4%D1%83%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5_%D1%82%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5)
* [Модульное тестирование — личный опыт](http://habrahabr.ru/post/110909/)

#### В языках

PHP:

* [Юнит-тестирование в PHP](http://habrahabr.ru/post/56289/)

Python:

* [Python. Генерация юнит-тестов](http://habrahabr.ru/post/192512/)
* [Python unittest: базовые возможности](http://blog.openquality.ru/python-unittest/)
* [Тестирование. Начало](http://habrahabr.ru/post/121162/)
* [Погружение в Python 3 (Пилгрим)/Тестирование](http://ru.wikisource.org/wiki/%D0%9F%D0%BE%D0%B3%D1%80%D1%83%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5_%D0%B2_Python_3_(%D0%9F%D0%B8%D0%BB%D0%B3%D1%80%D0%B8%D0%BC)/%D0%A2%D0%B5%D1%81%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5)
* [Разработка через тестирование в Python и Django](http://www.slideshare.net/JetStyle/python-django-16824866)

### Высокие нагрузки

* [О железе](http://www.server-support.com.ua/IT-%D1%80%D0%B5%D1%88%D0%B5%D0%BD%D0%B8%D1%8F/highload-webserver/)

* [How to Generate Millions of HTTP Requests](http://dak1n1.com/blog/14-http-load-generate)

* [A Million-user Comet Application with Mochiweb, Part 1](http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-1)
* [A Million-user Comet Application with Mochiweb, Part 2](http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-2)
* [A Million-user Comet Application with Mochiweb, Part 3](http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-3)

* [man: httperf](http://www.hpl.hp.com/research/linux/httperf/httperf-man-0.9.txt)
* [Performance Testing with Httperf](http://engineering.yp.com/post/httperf)
* [Benchmark testing with httperf](http://damithakumarage.wordpress.com/2009/03/15/benchmark-testing-with-httperf/)
* [Видео: Benchmarking with httperf](http://pluralsight.com/training/courses/TableOfContents/benchmarking-with-httperf)
* [httperf to test an json rest api](http://cedillos-dharaharsh.blogspot.ru/2013/09/httperf-to-test-json-rest-api.html)
* [HTTP performance testing with httperf, autobench and openload](http://agiletesting.blogspot.ru/2005/04/http-performance-testing-with-httperf.html)

* [Tsung. Нагрузочное тестирование сервера MongooseIM](http://kakyaetosdelal.blogspot.ru/2013/12/tsung-mongooseim.html)
* [Инструмент для нагрузочного тестирования Tsung](http://www.slideshare.net/profyclub_ru/tsung-12235374)
* [Load testing with Tsung](http://dev.bizo.com/2009/07/load-testing-with-tsung.html)
* [Increase Max Connections under Ubuntu? (Tsung concurrency test)](http://ask.make-money-article.com/que/4598914)
* [[Tsung] Configuration Problem](http://lists.process-one.net/pipermail/tsung-users/2008-April/000812.html;)


text:
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        app.setupcamera();
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },
    setupcamera: function () {
        var cameraElement = document.getElementById('camera');
        cameraElement.onclick = app.capture;
        cameraElement = document.getElementById('select');
        cameraElement.onclick = app.select;
    },
    capture: function () {
        var settings = {
            quality: 80,
            destinationType: Camera.DestinationType.FILE_URI,
            allowEdit: false, // this turns on / off cropping
            saveToPhotoAlbum: true,
            correctOrientation: false,
            encodingType: navigator.camera.EncodingType.JPEG,
            cameraDirection: Camera.Direction.BACK,
            targetWidth: 1280,
            targetHeight: 800
        };
        navigator.camera.getPicture(app.camerasuccess, app.camerafail, settings);
    },
    select: function () {
        var settings = {
            quality: 90,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
            correctOrientation : false,
        };
        navigator.camera.getPicture(app.camerasuccess, app.camerafail, settings);
    },
    camerasuccess: function (imageURI) {
        if (device.platform == 'iOS') {
            app.camerasuccessios(imageURI);
        } else if (device.platform == 'Android') {
            app.camerasuccessandroid(imageURI);
        } else {
            console.log('No success call back for platform ' + device.platform + ' using ios callback');
            app.camerasuccessios(imageURI);
        }
    },
    camerasuccessios: function (imageURI) {
        console.log("camerasuccessios: imageURI: " + imageURI);
        var imageElement = document.getElementById('image');
        imageElement.innerHTML = '';
    },
    camerasuccessandroid: function (imageURI) {
        console.log("camerasuccessandroid: imageURI: " + imageURI);
        var imageElement = document.getElementById('image');
        imageElement.innerHTML = '';
    },
};


text:
package com.freiheit.fuava.simplebatch.fsjobs.importer;

import com.freiheit.fuava.simplebatch.BatchTestDirectory;
import com.freiheit.fuava.simplebatch.MapBasedBatchDownloader;
import com.freiheit.fuava.simplebatch.fetch.FetchedItem;
import com.freiheit.fuava.simplebatch.fetch.Fetchers;
import com.freiheit.fuava.simplebatch.fsjobs.downloader.CtlDownloaderJob;
import com.freiheit.fuava.simplebatch.fsjobs.downloader.CtlDownloaderJob.ConfigurationImpl;
import com.freiheit.fuava.simplebatch.processor.FileWriterAdapter;
import com.freiheit.fuava.simplebatch.processor.Processor;
import com.freiheit.fuava.simplebatch.processor.RetryingProcessor;
import com.freiheit.fuava.simplebatch.result.Result;
import com.freiheit.fuava.simplebatch.result.ResultStatistics;
import com.freiheit.fuava.simplebatch.util.CollectionUtils;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Test
public class CtlImporterPathAndConcurrencyTest {

    private final Map<Integer, String> data = CollectionUtils.asMap(
            1, "eins",
            2, "zwei",
            3, "drei",
            4, "vier" );

    @DataProvider
    public Object[][] testData() {
        return new Object[][] {

            {testCase( "Success" )
                .successProcessor()
                .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Fail All" )
                    .failAllProcessor()
                    .expect( BatchTestDirectory.FAILS, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Fail Some" )
                    .failSomeProcessor()
                    .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Fail Batch")
                .failBatchProcessor()
                .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Success File Concurrent" )
                    .successProcessor()
                    .numConcurrentFiles( 2 )
                    .numConcurrentData( 1 )
                    .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Fail All File Concurrent" )
                    .failAllProcessor()
                    .numConcurrentFiles( 2 )
                    .numConcurrentData( 1 )
                    .expect( BatchTestDirectory.FAILS, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Fail Some File Concurrent" )
                    .failSomeProcessor()
                    .numConcurrentFiles( 2 )
                    .numConcurrentData( 1 )
                    .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Fail Batch File Concurrent")
                .failBatchProcessor()
                .numConcurrentFiles( 2 )
                .numConcurrentData( 1 )
                .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

            {testCase( "Success File And Data Concurrent" )
                .successProcessor()
                .numConcurrentFiles( 2 )
                .numConcurrentData( 1 )
                .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Fail All File And Data Concurrent" )
                        .failAllProcessor()
                        .numConcurrentFiles( 2 )
                        .numConcurrentData( 2 )
                        .expect( BatchTestDirectory.FAILS, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Fail Some File And Data Concurrent" )
                        .failSomeProcessor()
                        .numConcurrentFiles( 2 )
                        .numConcurrentData( 2 )
                        .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Fail Batch File And Data Concurrent")
                    .failBatchProcessor()
                    .numConcurrentFiles( 2 )
                    .numConcurrentData( 2 )
                    .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Success Data Concurrent" )
                    .successProcessor()
                    .numConcurrentFiles( 1 )
                    .numConcurrentData( 1 )
                    .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Fail All Data Concurrent" )
                        .failAllProcessor()
                        .numConcurrentFiles( 1 )
                        .numConcurrentData( 2 )
                        .expect( BatchTestDirectory.FAILS, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Fail Some Data Concurrent" )
                        .failSomeProcessor()
                        .numConcurrentFiles( 1 )
                        .numConcurrentData( 2 )
                        .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )},

                {testCase( "Fail Batch Data Concurrent")
                    .failBatchProcessor()
                    .numConcurrentFiles( 1 )
                    .numConcurrentData( 2 )
                    .expect( BatchTestDirectory.ARCHIVE, CollectionUtils.asSet( "inst_01-1.tmp", "inst_01-2.tmp" ) )}

        };
    }

    @Test(dataProvider="testData")
    public void testDownloadAndImport( final TestCase testCase ) throws FileNotFoundException, IOException {

        final BatchTestDirectory tmp = new BatchTestDirectory( "CtlImporterTest" );
        prepare( tmp );

        for (final ExpectedDirState state : testCase.getExpectedDirsAfterDownload()) {
            final Set<String> expectedNames = state.getExpectedNames();
            final Map<String, List<SBFile>> impFiles = listFilesInDir( tmp, state.getDir() );
            Assert.assertEquals( impFiles.keySet(), expectedNames, "Wrong State after Download in " + state.dir   );
        }

        createImporterJob( tmp, testCase.getProcessor() )
        .setNumParallelThreadsFiles( testCase.getNumConcurrentFiles() )
        .setParallelFiles( testCase.getNumConcurrentFiles() > 1 )
        .setNumParallelThreadsContent( testCase.getNumConcurrentData() )
        .setParallelContent( testCase.getNumConcurrentData() > 1 )
        .build().run();

        for (final ExpectedDirState state : testCase.getExpectedDirs()) {
            final Set<String> expectedNames = state.getExpectedNames();
            final Map<String, List<SBFile>> impFiles = listFilesInDir( tmp, state.getDir() );
            Assert.assertEquals( impFiles.keySet(), expectedNames, "Wrong State after Import in " + state.dir  );
        }

        tmp.cleanup();
    }

    private static final class FailBatchProcessor extends RetryingProcessor<FetchedItem<String>, String, String> {
        @Override
        public List<String> apply( final List<String> input ) {
            if ( input.size() > 1 ) {
                throw new IllegalArgumentException( "too many items" );
            }
            return input;
        }
    }

    private static final class FailSomeProcessor extends RetryingProcessor<FetchedItem<String>, String, String> {
        @Override
        public List<String> apply( final List<String> input ) {
            for (final String v : input) {
                if ("2".equals(v) || "4".equals( v )) {
                    throw new IllegalArgumentException("Fail all for tests");
                }
            }
            return input;
        }
    }

    private static final class FailAllProcessor extends RetryingProcessor<FetchedItem<String>, String, String> {
        @Override
        public List<String> apply( final List<String> input ) {
            throw new IllegalArgumentException("Fail all for tests");
        }
    }

    private static final class SuccessProcessor extends RetryingProcessor<FetchedItem<String>, String, String> {
        @Override
        public List<String> apply( final List<String> input ) {
            return input;
        }
    }

    static final class ExpectedDirState {
        private final String dir;
        private final Set<String> expectedNames;

        public ExpectedDirState(final String dir, final Set<String> expectedNames) {
            this.dir = dir;
            this.expectedNames = expectedNames;
        }

        public String getDir() {
            return dir;
        }

        public Set<String> getExpectedNames() {
            return expectedNames;
        }
    }

    static final class TestCase {
        private final String name;

        private Map<Integer, String> data = Collections.emptyMap();
        private int numConcurrentFiles = 1;
        private int numConcurrentData = 1;
        private int fileBatchSize = 1;
        private final Map<String, ExpectedDirState> expectedDirsAfterImport = new HashMap<String, ExpectedDirState>();
        private final Map<String, ExpectedDirState> expectedDirsAfterDownload = new HashMap<String, ExpectedDirState>();
        private Processor<FetchedItem<String>, String, String> processor = new SuccessProcessor();

        public TestCase( final String name ) {
            this.name = name;
        }

        public TestCase processor( final Processor<FetchedItem<String>, String, String> processor ) {
            this.processor = processor;
            return this;
        }

        public TestCase successProcessor( ) {
            return processor( new SuccessProcessor() );
        }
        public TestCase failAllProcessor( ) {
            return processor( new FailAllProcessor() );
        }
        public TestCase failSomeProcessor( ) {
            return processor( new FailSomeProcessor() );
        }
        public TestCase failBatchProcessor( ) {
            return processor( new FailBatchProcessor() );
        }

        public Processor<FetchedItem<String>, String, String> getProcessor() {
            return processor;
        }

        public TestCase data(final Map<Integer, String> data) {
            this.data = data;
            return this;
        }

        public TestCase numConcurrentData( final int numConcurrentData ) {
            this.numConcurrentData = numConcurrentData;
            return this;
        }

        public TestCase numConcurrentFiles( final int numConcurrentFiles ) {
            this.numConcurrentFiles = numConcurrentFiles;
            return this;
        }

        public TestCase fileBatchSize( final int fileBatchSize ) {
            this.fileBatchSize = fileBatchSize;
            return this;
        }

        public TestCase expectAfterDownload( final String dir, final Set<String> keys ) {
            expectedDirsAfterDownload.put( dir, new ExpectedDirState( dir, keys ) );
            return this;
        }

        public TestCase expect( final String dir, final Set<String> keys ) {
            expectedDirsAfterImport.put( dir, new ExpectedDirState( dir, keys ) );
            return this;
        }

        public Map<Integer, String> getData() {
            return data;
        }

        public Collection<ExpectedDirState> getExpectedDirs() {
            return expectedDirsAfterImport.values();
        }

        public Collection<ExpectedDirState> getExpectedDirsAfterDownload() {
            return expectedDirsAfterDownload.values();
        }

        public int getFileBatchSize() {
            return fileBatchSize;
        }

        public int getNumConcurrentData() {
            return numConcurrentData;
        }

        public int getNumConcurrentFiles() {
            return numConcurrentFiles;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    static final class SBFile {
        private final String name;
        SBFile(final Path p) {
            name = p.getFileName().toString();
        }

        public boolean isCtl() {
            return name.endsWith( ".ctl" );
        }

        public boolean isLog() {
            return name.endsWith( ".log" );
        }

        public boolean isData() {
            return !isCtl() && !isLog();
        }

        public String getDataName() {
            return isData() ? name : name.substring( 0, name.length() - 4 );
        }

        @Override
        public String toString() {
            final String prefix = isData() ? "DATA: " : (isLog() ? "LOG: " : "CTL: ");
            return prefix + getDataName();
        }
    }

    private TestCase testCase( final String name ) {
        return new TestCase( name )
                .data( data )
                .fileBatchSize( 2 )
                .expectAfterDownload( BatchTestDirectory.ARCHIVE, Collections.emptySet() )
                .expectAfterDownload( BatchTestDirectory.FAILS, Collections.emptySet() )
                .expectAfterDownload( BatchTestDirectory.PROCESSING, Collections.emptySet() )
                .expectAfterDownload( BatchTestDirectory.DOWNLOADS, CollectionUtils.asSet( "1.tmp", "2.tmp" ) )
                // at least one of those will be overridden
                .expect( BatchTestDirectory.ARCHIVE, Collections.emptySet() )
                .expect( BatchTestDirectory.FAILS, Collections.emptySet() )
                .expect( BatchTestDirectory.PROCESSING, Collections.emptySet() )
                .expect( BatchTestDirectory.DOWNLOADS, Collections.emptySet() )
                ;
    }

    private void prepare( final BatchTestDirectory tmp ) throws IOException {
        assertIsEmpty(tmp.getArchiveDir());

        final AtomicLong counter = new AtomicLong();
        download( tmp, 2, data, counter );

        assertIsEmpty(tmp.getArchiveDir());
        assertIsEmpty(tmp.getFailsDir());
        assertIsEmpty(tmp.getProcessingDir());
    }

    private void assertIsEmpty( final Path dir ) throws IOException {
        final Map<String, List<SBFile>> files = listFilesInDir( dir );
        Assert.assertTrue( files.isEmpty(), "Directory " + dir + " not empty. It contains files " + files );
    }

    private Map<String, List<SBFile>> listFilesInDir( final BatchTestDirectory cfg, final String dir ) throws IOException {
        return listFilesInDir( cfg.getTestDirBase().resolve( dir ) );
    }

    private Map<String, List<SBFile>> listFilesInDir( final Path dir ) throws IOException {
        if ( !dir.toFile().exists() ) {
            return Collections.emptyMap();
        }
        final List<SBFile> files = new ArrayList<>();
        Files.walkFileTree( dir,  new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile( final Path file, final BasicFileAttributes attrs ) throws IOException {
                files.add( new SBFile( file ) );
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory( final Path dir, final IOException exc ) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
        return files.stream().collect( Collectors.groupingBy( SBFile::getDataName ) );
    }

    private CtlImporterJob.Builder<String> createImporterJob( final BatchTestDirectory tmp, final Processor<FetchedItem<String>, String, String> processor ) {
        return new CtlImporterJob.Builder<String>()
                .setConfiguration( new CtlImporterJob.ConfigurationImpl()
                        .setArchivedDirPath( tmp.getArchiveDir() )
                        .setDownloadDirPath( tmp.getDownloadsDir() )
                        .setFailedDirPath( tmp.getFailsDir() )
                        .setProcessingDirPath( tmp.getProcessingDir() )
                )
                .setFileInputStreamReader( input -> {
                    try {
                        try ( BufferedReader ir =
                                new BufferedReader( new InputStreamReader( input, StandardCharsets.UTF_8 ) ) ) {
                            return Collections.singletonList( ir.readLine() );
                        }
                    } catch ( final IOException e ) {
                        throw new RuntimeException( e );
                    }
                }
                )
                .setContentProcessor( processor )
                ;
    }

    private void download( final BatchTestDirectory tmp, final int batchSize, final Map<Integer, String> data, final AtomicLong counter ) {
        final ResultStatistics downloadResults = new CtlDownloaderJob.BatchFileWritingBuilder<Integer, String>()
                .setConfiguration( new ConfigurationImpl().setDownloadDirPath( tmp.getDownloadsDir() ) )
                .setDownloaderBatchSize( batchSize )
                .setIdsFetcher( Fetchers.iterable( data.keySet() ) )
                .setDownloader( new MapBasedBatchDownloader<Integer, String>( data ) )
                .setBatchFileWriterAdapter(
                        new FileWriterAdapter<List<FetchedItem<Integer>>, List<String>>() {
                            private final AtomicLong counter = new AtomicLong();

                            @Override
                            public void write( final Writer writer, final List<String> data ) throws IOException {
                                final String string = String.join( "\n", data );
                                writer.write( string );
                            }

                            @Override
                            public Path prependSubdirs(final String filename) {
                                return Paths.get( filename );
                            }

                            @Override
                            public String getFileName( final Result<List<FetchedItem<Integer>>, List<String>> result ) {
                                return counter.incrementAndGet() + ".tmp";
                            }
                        }
                )
                .build()
                .run();

        Assert.assertTrue( downloadResults.isAllSuccess() );
        Assert.assertFalse( downloadResults.isAllFailed() );
    }

}


text:
title: What Trump's Tax Plan Means for Millennials
date: 2017-11-30 11:00:00 -05:00
tags:
- trump
- republicans
- milennials
- taxes
- tax
- tax plan
- tax reform
- money
- personal finance
- government
image: "/uploads/writing.jpg"
tweet: 'Do your eyes cross when you read about the proposed tax bill? Here''s how
  it may affect you as a millennial. '
posts:
- Here's How You Should Use Your Tax Refund
- How to Do Your Taxes on the Cheap
- Are you stressed out about doing your taxes?
---

I'm sure you've heard about the new tax bill that [moved to the Senate floor](https://www.nytimes.com/2017/11/30/us/politics/tax-overhaul-senate-debate.html) today. If you're like me, your eyes probably cross when you're trying to understand the details of the bill, called "Unified Framework for Fixing Our Broken Tax Code." But even though taxes are complicated and seem boring, this bill, if passed, will have major impacts on American citizens.

## What does this tax bill do?

* Reduces the current marginal income tax brackets to four from seven

* Cuts the tax rate on corporations from 35 percent to 20 percent, which would reduce the amount of taxes paid by corporations by $2 trillion over the next 10 years

* Cuts the top-bracket tax rate to the levels that existed under President George W. Bush, while raising the lowest-bracket rate

* Eliminates the tax on wealthy estates (those valued at more than $5.5 million, or $11 million for couples)

* Eliminates the individual alternative minimum tax, which exists to prevent high-income filers from claiming so many deductions and preferences that they pay little or no tax

* Creates a special new loophole for high-income owners of so-called pass-through business entities, cutting the rate they pay from 39.6 percent to 25 percent (Upwards of 86 percent of small businesses won't benefit at all)

* Eliminates personal and dependent exemptions

* Eliminates the ability to deduct large medical expenses and "casualty" losses, such as property damage from hurricanes that is not covered by insurance

* Eliminates the ability to deduct one's state and local taxes paid

* Designates fetuses as eligible beneficiaries of "section 529" college savings accounts

## What does all this even mean for you?

Because of the enormous corporate and high-income tax cuts, this bill would increase deficits by $1.4 trillion over the next decade. That money has to come from somewhere and, in this bill, it comes from programs, deductions, and services that many of us rely on. All in all, this bill is terrible for anyone who isn't in the top 1 percent. Here are just a few examples of the programs and benefits that would be gutted.

**Education**

* The House bill eliminates the student loan interest deduction, though the Senate bill, as currently written, would leave this in place.

* The bill slashes funding for [Federal Pell Grants](https://studentaid.ed.gov/sa/types/grants-scholarships/pell), which are an important financial aid for low-income students.

**Healthcare**

* The bill eliminates the Affordable Care Act's [individual mandate](https://www.healthcare.gov/fees/fee-for-not-being-covered/), which would drive up premiums by 10 percent in 2019, and cause 13 million Americans to lose their health insurance.

* The House version of the bill would cut $25 billion from [Medicare](https://www.medicare.gov/sign-up-change-plans/decide-how-to-get-medicare/whats-medicare/what-is-medicare.html) in fiscal year 2018 and hundreds of billions of dollars of cuts to the program overall.

* The House bill would eliminate the deduction for high out-of-pocket medical expenses.

**Women**

* The bill eliminates funding for the [Crime Victims Fund](https://www.ovc.gov/about/victimsfund.html), which supports state programs that help crime victims, including efforts to combat violence against women, human trafficking, and child abuse and neglect.

* The bill designates fetuses as eligible beneficiaries of [529 college savings accounts](https://www.sec.gov/reportspubs/investor-publications/investorpubsintro529htm.html). This is a sneaky way to grant personhood to unborn fetuses, with the goal of stripping away women's right to choose.

**Food, Housing, and more**

* The bill eliminates funding for the Commodity Assistance Program, which provides food donations to help the elderly and low-income populations, among others.

* Funding for the Affordable Housing Program is cut completely. This program supports federal home loan bank contributions to subsidize affordable housing and homeownership.

* The bill eliminates funding for the [Promoting Safe and Stable Families Program](https://www.acf.hhs.gov/cb/resource/pssf-title-iv-b-subpart-2-ssa), which, among other things, helps states keep children safe from maltreatment.

This isn't even a complete list of the negative impacts this tax bill would have on American citizens.

## So, what can you do?

**1. Call your Senators!**

The Senate is planning to vote as soon as possible, so it's time to call. This is especially important if you have a Republican Senator. Republican leadership is confident that they can vote this bill through without any support from Democrats. They have a majority, after all. However, some Republicans actually do care about their constituents, and won't blindly vote along party line. And maybe if enough constituents complain, other Republicans will change their vote! (One can hope...)

**2. Spread the word**

There is a lot of misinformation out there. But the truth is: trickle-down economics does not boost economic growth. Tax cuts for the mega rich and for corporations only helps those people and businesses. They don't spread their tax savings among the less fortunate of us. In fact, tax breaks for the very rich actually make the wealth gap bigger and bigger. When you hear this fallacy, correct it. Share the resources below. And tell your friends and family to call their Senators!

**More Resources:**

* [Tall Tax Tales](https://www.usnews.com/opinion/economic-intelligence/articles/2017-10-02/donald-trump-and-the-gop-are-trumpeting-tax-reform-that-benefits-the-rich)

* [A Preliminary Analysis of the Unified Framework](http://www.taxpolicycenter.org/publications/preliminary-analysis-unified-framework)

* [It Started as a Tax Cut. Now It Could Change American Life.](https://mobile.nytimes.com/2017/11/29/business/republican-tax-cut.html?_r=0&referer=http%3A%2F%2Fm.facebook.com)

* [The Entire Rationale For These Tax Cuts Is Bullshit](https://splinternews.com/the-entire-rationale-for-these-tax-cuts-is-bullshit-1819135455)

* [What the Tax Bill Would Look Like for 25,000 Middle-Class Families](https://www.nytimes.com/interactive/2017/11/28/upshot/what-the-tax-bill-would-look-like-for-25000-middle-class-families.html?hp&action=click&pgtype=Homepage&clickSource=g-artboard\+g-artboard-v3&module=b-lede-package-region&region=top-news&WT.nav=top-news)

* [Six Charts That Help Explain the Republican Tax Plan](https://www.nytimes.com/interactive/2017/09/27/us/politics/six-charts-to-explain-the-republican-tax-plan.html?_r=0)

* [An 11th-Hour Raid by the Wealthiest Baby Boomers](https://www.theatlantic.com/politics/archive/2017/11/young-people-will-foot-the-bill-for-the-gops-tax-plan/547097/?utm_source=atlfb)

* [Congressional GOP Tax and Budget Plans Benefit Wealthiest at the Expense of Vulnerable Young People](http://genprogress.org/voices/2017/11/22/45990/congressional-gop-tax-budget-plans-benefit-wealthiest-expense-vulnerable-young-people/)

* [Ivanka Trump Should Stop Pretending the Tax Bill Will Help Women and Families](https://www.americanprogress.org/issues/women/news/2017/11/27/443288/ivanka-trump-stop-pretending-tax-bill-will-help-women-families/)

* [The Senate Tax Bill Would Eliminate Programs for Farmers, Crime Victims, the Elderly, and Children](https://www.americanprogress.org/issues/economy/news/2017/11/21/443207/senate-tax-bill-eliminate-programs-farmers-crime-victims-elderly-children/)

* [Millions of Working- and Middle-Class Americans Would See a Tax Increase Under the Senate GOP Tax Plan](https://www.americanprogress.org/issues/economy/news/2017/11/27/443316/millions-working-middle-class-americans-see-tax-increase-senate-gop-tax-plan/)


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace StageBitz.UserWeb.Controls.Inventory {

    public partial class InventoryBulkUpdatePanel {

        /// <summary>
        /// grbProjectPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::StageBitz.UserWeb.Controls.Common.GroupBox grbProjectPanel;

        /// <summary>
        /// upnlBulkUpdate control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel upnlBulkUpdate;

        /// <summary>
        /// sbInventoryLocations control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::StageBitz.UserWeb.Controls.Inventory.InventoryLocations sbInventoryLocations;

        /// <summary>
        /// btnBulkUpdate control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnBulkUpdate;

        /// <summary>
        /// hdnBulkUpdateSelectedItems control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hdnBulkUpdateSelectedItems;

        /// <summary>
        /// bulkUpdateSavedNotice control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl bulkUpdateSavedNotice;

        /// <summary>
        /// lblToLocation control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblToLocation;

        /// <summary>
        /// popupInventoryLocationDeleted control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::StageBitz.UserWeb.Controls.Common.PopupBox popupInventoryLocationDeleted;

        /// <summary>
        /// divUpdateVisibility control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl divUpdateVisibility;

        /// <summary>
        /// sbInventoryUpdateVisibility control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::StageBitz.UserWeb.Controls.Inventory.InventoryUpdateVisibility sbInventoryUpdateVisibility;

        /// <summary>
        /// btnUpdateVisibility control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnUpdateVisibility;

        /// <summary>
        /// visibilitySavedNotice control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl visibilitySavedNotice;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Roux, Triebel, Bricaud & Le Coeur, Can. J. Bot. 73(4): 663 (1995)

#### Original name
Stigmidium lecidellae Triebel, Cl. Roux & Le Coeur, 1995

### Remarks
null


text:
package org.bitcoins.core.script.flag

import org.bitcoins.testkitcore.util.BitcoinSUnitTest

/** Created by chris on 3/23/16.
  */
class ScriptFlagsTest extends BitcoinSUnitTest {

  "ScriptVerifyNone" must "have the flag zero" in {
    ScriptVerifyNone.flag must be(0)
  }

  "ScriptVerifyP2SH" must "have the flag one" in {
    ScriptVerifyP2SH.flag must be(1)
  }

  "ScriptVerifyStrictEnc" must "have the flag 2" in {
    ScriptVerifyStrictEnc.flag must be(2)
  }

  "ScriptVerifyDerSig" must "have the flag 1 << 2" in {
    ScriptVerifyDerSig.flag must be(1 << 2)
  }

  "ScriptVerifyLowS" must "have the flag 1 << 3" in {
    ScriptVerifyLowS.flag must be(1 << 3)
  }

  "ScriptVerifyNullDummy" must "have the flag 1 << 4" in {
    ScriptVerifyNullDummy.flag must be(1 << 4)
  }

  "ScriptVerifySigPushOnly" must "have the flag 1 << 5" in {
    ScriptVerifySigPushOnly.flag must be(1 << 5)
  }

  "ScriptVerifyMinimalData" must "have the flag 1 << 6" in {
    ScriptVerifyMinimalData.flag must be(1 << 6)
  }

  "ScriptVerifyDiscourageUpgradableNOPs" must "have the flag 1 << 7" in {
    ScriptVerifyDiscourageUpgradableNOPs.flag must be(1 << 7)
  }

  "ScriptVerifyCleanStack" must "have the flag 1 << 8" in {
    ScriptVerifyCleanStack.flag must be(1 << 8)
  }

  "ScriptVerifyCheckLocktimeVerify" must "have the flag 1 << 9" in {
    ScriptVerifyCheckLocktimeVerify.flag must be(1 << 9)
  }

  "ScriptVerifyCheckSequenceVerify" must "have the flag 1 << 10" in {
    ScriptVerifyCheckSequenceVerify.flag must be(1 << 10)
  }
}


text:
package org.trianacode.http;

import org.thinginitself.streamable.Streamable;
import org.trianacode.taskgraph.Task;
import org.trianacode.taskgraph.tool.Tool;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Andrew Harrison
 * @version 1.0.0 Jul 20, 2010
 */

public class ToolParameterRenderer implements Renderer {

    private Task parent;
    private Tool tool;
    private String path;

    public void init(Tool tool, String path) {
        if (tool instanceof Task) {
            Task t = (Task) tool;
            this.parent = t.getUltimateParent();
        }
        this.tool = tool;
        this.path = path;

    }

    public Streamable render(String type, String mime) {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("path", path);
        properties.put("toolname", parent.getToolName());
        properties.put("toolpackage", parent.getToolPackage());
        properties.put("subtoolname", tool.getToolName());
        properties.put("subtoolpackage", tool.getToolPackage());
        return Output.output(properties, type, mime);
    }
}


text:
package com.ibatis.sqlmap.engine.execution;

import java.sql.BatchUpdateException;
import java.util.List;

/**
 * This exception is thrown if a java.sql.BatchUpdateException is
 * caught during the execution of any nested batch. The exception contains the
 * java.sql.BatchUpdateException that is the root cause, as well as the results
 * from any prior nested batch that executed successfully. This exception is
 * only thrown from the executeBatchDetailed method.
 *
 * @author Jeff Butler
 *
 */
public class BatchException extends Exception {

    private List successfulBatchResults;
    private BatchUpdateException batchUpdateException;
    private String failingSqlStatement;
    private String failingStatementId;

    /**
    *
    */
    public BatchException(String message, BatchUpdateException cause, List successfulBatchResults, String failingStatementId,
            String failingSqlStatement) {
        super(message, cause);
        this.batchUpdateException = cause;
        this.successfulBatchResults = successfulBatchResults;
        this.failingStatementId = failingStatementId;
        this.failingSqlStatement = failingSqlStatement;
    }

    /**
     * Returns the BatchUpdateException that caused the nested batch to fail.
     * That exception contains an array of row counts that can be used to
     * determine exactly which statemtn of the batch caused the failure (or
     * failures).
     *
     * @return the root BatchUpdateException
     */
    public BatchUpdateException getBatchUpdateException() {
        return batchUpdateException;
    }

    /**
     * Returns a list of BatchResult objects. There will be one entry in the
     * list for each successful sub-batch executed before the failing batch.
     *
     * @return the previously successful batch results (may be an empty list if
     *         no batch has executed successfully)
     */
    public List getSuccessfulBatchResults() {
        return successfulBatchResults;
    }

    /**
     * Returns the SQL statement that caused the failure (not the parameters)
     *
     * @return the failing SQL string
     */
    public String getFailingSqlStatement() {
        return failingSqlStatement;
    }

    /**
     * Returns the statement id of the statement that caused the failure
     *
     * @return the statement id
     */
    public String getFailingStatementId() {
        return failingStatementId;
    }
}