text:
package io.cloudslang.content.dropbox.entities.constants;

/**
 * Created by TusaM
 * 5/26/2017.
 */
public class Constants {
    private Constants() {
        // prevent instantiation
    }

    public static class Api {
        public static final String FOLDERS = "folders";
        public static final String FILES = "files";
    }

    public static class ErrorMessages {
        public static final String CONSTRAINS_ERROR_MESSAGE = "The value doesn't meet conditions for general purpose usage. " +
                "See operation inputs description section for details.";
        public static final String UNKNOWN_BUILDER_TYPE = "Unknown builder type.";
        public static final String UNKNOWN_DROPBOX_HEADER = "Unknown Dropbox header.";
        public static final String UNSUPPORTED_DROPBOX_API = "Unsupported Dropbox API.";
    }

    public static class FolderActions {
        public static final String CREATE_FOLDER = "CreateFolder";
        public static final String DELETE_FILE_OR_FOLDER = "DeleteFileOrFolder";
    }

    public static class HttpClientInputsValues {
        public static final String ALLOW_ALL = "allow_all";
        public static final String APPLICATION_JSON = "application/json";
        public static final String AUTHORIZATION_HEADER_PREFIX = "Authorization:Bearer";
        public static final String BROWSER_COMPATIBLE = "browser_compatible";
        public static final String STRICT = "strict";

    }

    public static class Miscellaneous {
        public static final String BLANK_CHAR = " ";
        public static final String CREATE_FOLDER_PATH_REGEX = "(/(.|[\r\n])*)|(ns:[0-9]+(/.*)?)";
        public static final String DELETE_FOLDER_PATH_REGEX = "(/(.|[\r\n])*)|(ns:[0-9]+(/.*)?)|(id:.*)";
    }

    public static class Values {
        public static final int INIT_INDEX = 0;
        public static final int VERSION_2 = 2;
    }
}


text:
<?php
namespace Website\Form\Filter;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;

class WebsiteCfgFilter extends InputFilter
{

	/**
	 * Configura os Filtros/Validações a serem executadas no formulário
	 */
	public function __construct()
	{
		$factory = new InputFactory();

		// Adiciona o campo Foto Topo ao InputFilter
		$this->add($factory->createInput(
			array(
				 'type' => 'Zend\InputFilter\FileInput',
				 'name' => 'fotoTopoSite',
				 'required' => false,
				 'validators' => array(
			 					 array(
									  'name' => 'FileUploadFile',
									  'break_chain_on_failure' => true,
									  'options' => array(
									 				    'messages' => array(
																           \Zend\Validator\File\UploadFile::INI_SIZE       => 'O tamanho do arquivo excede o definido no arquivo ini.',
																           \Zend\Validator\File\UploadFile::FORM_SIZE      => 'O tamanho do arquivo excede o definido no formulário.',
																           \Zend\Validator\File\UploadFile::PARTIAL        => 'O arquivo não foi completamente enviado. Envie novamente.',
																           \Zend\Validator\File\UploadFile::NO_FILE        => 'O arquivo não foi enviado.',
																           \Zend\Validator\File\UploadFile::NO_TMP_DIR     => 'Não foi encontrado um diretório temporário.',
																           \Zend\Validator\File\UploadFile::CANT_WRITE     => 'O arquivo não pôde ser escrito no servidor.',
																           \Zend\Validator\File\UploadFile::EXTENSION      => 'Uma extensão do PHP retornou um erro ao enviar o arquivo.',
																           \Zend\Validator\File\UploadFile::ATTACK         => 'O arquivo foi enviado de forma ilegal. Possível tentativa de ataque.',
																           \Zend\Validator\File\UploadFile::FILE_NOT_FOUND => 'Arquivo não encontrado.',
																           \Zend\Validator\File\UploadFile::UNKNOWN        => 'Erro desconhecido ao enviar o arquivo.',
									 				   					   ),
									 				    ),
									  ),
								 array(
								 	  'name' => 'FileSize',
								 	  'break_chain_on_failure' => true,
								 	  'options' => array(
								 	  					'max' => '8MB',
								 	  					'messages' => array(
								 	  									   \Zend\Validator\File\Size::TOO_BIG   => 'O tamanho máximo do arquivo deve ser %max%. O arquivo enviado possui %size%.',
								 	  									   \Zend\Validator\File\Size::NOT_FOUND => 'O arquivo não é legível ou não existe.',
								 	  									   ),
								 	  					),
								 	  ),
			 					 array(
									  'name' => 'FileIsImage',
									  'break_chain_on_failure' => true,
									  'options' => array(
									 				    'messages' => array(
									 				   					   \Zend\Validator\File\IsImage::FALSE_TYPE   => 'O arquivo enviado foi detectado como sendo %type%. Envie uma imagem no formato JPEG, PNG ou GIF.',
									 				   					   \Zend\Validator\File\IsImage::NOT_DETECTED => 'O sistema não conseguiu detectar o tipo de arquivo enviado. Envie uma imagem no formato JPEG, PNG ou GIF.',
									 				   					   \Zend\Validator\File\IsImage::NOT_READABLE => 'O sistema não conseguiu ler o arquivo. Envie uma imagem no formato JPEG, PNG ou GIF.'
									 				   					   ),
									 				    ),
									  ),
			 					 array(
									  'name' => 'FileExcludeMimeType',
									  'break_chain_on_failure' => true,
									  'type' => array('image/jpeg','image/png','image/gif'),
									  'options' => array(
									 				    'messages' => array(
									 				   					   \Zend\Validator\File\MimeType::FALSE_TYPE => 'O arquivo enviado foi detecado como sendo %type%. Envie uma imagem no formato JPEG, PNG ou GIF.',
									 				   					   ),
									 				    ),
								 	  ),
		 				  		 array(
		 				   		 'name' => 'FileImageSize',
								 'break_chain_on_failure' => true,
		 				   		 'options' => array(
		 				   						   'maxWidth' => 6000,
		 				   						   'maxHeight' => 6000,
		 				   						   'messages' => array(
									 				   				  \Zend\Validator\File\ImageSize::WIDTH_TOO_BIG  => 'A largura máxima permitida para esta imagem é de %maxwidth%px mas a imagem enviada possui %width%px.',
									 				   				  \Zend\Validator\File\ImageSize::HEIGHT_TOO_BIG => 'A altura máxima permitida para esta imagem é de %maxheight%px mas a imagem enviada possui %height%px.',
									 				   				  \Zend\Validator\File\ImageSize::NOT_DETECTED   => 'O tamanho da imagem não pôde ser detectado.',
									 				   				  ),
		 				   						   ),
		 				       		  ),
				 					  ),
				 'filters' => array(
							  array(
							  	   'name' => 'FileRenameUpload',
							  	   'options' => array(
							  	   					 'target' => './data/upload/',
							  	   					 'use_upload_name' => false,
							  	   					 'use_upload_extension' => true,
							  	   					 'overwrite' => false,
							  	   					 'randomize' => true,
							  	   					 ),
							  	   ),
				 				   ),
				 )
		));

		// Adiciona o campo Cor Hexadecimal ao InputFilter
		$this->add($factory->createInput(
			array(
				 'name' => 'corHexadecimal',
				 'required' => true,
				 'filters' => array(
				 				   array('name' => 'StringTrim'),
				 				   array('name' => 'StripTags'),
				 				   ),
				 'validators' => array(
								 array('name' => 'StringLength',
									   'options' => array(
												  		 'encoding' => 'UTF-8',
												  		 'min' => 6,
												  		 'max' => 6,
												  		 'messages' => array(
												  		 					\Zend\Validator\StringLength::TOO_SHORT	=> 'O campo Cor Hexadecimal deve ter exatos %min% caracteres.',
																  		    \Zend\Validator\StringLength::TOO_LONG 	=> 'O campo Cor Hexadecimal deve ter exatos %max% caracteres.',
												  			 			    ),
									  				     ),
									  ),
				 					  ),
				 )
		));

		// Adiciona o campo Website Habilitado ao InputFilter
		$this->add($factory->createInput(
			array(
				 'name' => 'websiteHabilitado',
				 'required' => false)
				 )
				 );

	 // Adiciona o campo de segurança CSRF ao InputFilter
	 /*$this->add($factory->createInput(
	 	array(
	 		 'name' => 'security',
	 		 'required' => true,
	 		 )
	 )); */
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.zunix.ryoshi;

import com.github.zunix.ryoshi.api.errorhandlers.TwitchErrorHandler;
import com.github.zunix.ryoshi.api.resources.BlocksResource;
import com.github.zunix.ryoshi.api.resources.ChannelsResource;
import com.github.zunix.ryoshi.api.resources.ChatResource;
import com.github.zunix.ryoshi.api.resources.FollowsResource;
import com.github.zunix.ryoshi.api.resources.GamesResource;
import com.github.zunix.ryoshi.api.resources.IngestsResource;
import com.github.zunix.ryoshi.api.resources.RootResource;
import com.github.zunix.ryoshi.api.resources.SearchResource;
import com.github.zunix.ryoshi.api.resources.StreamsResource;
import com.github.zunix.ryoshi.api.resources.SubscriptionsResource;
import com.github.zunix.ryoshi.api.resources.TeamResource;
import com.github.zunix.ryoshi.api.resources.UsersResource;
import com.github.zunix.ryoshi.api.resources.VideosResource;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;

public class Ryoshi {

  private final String twitchAPIBaseURL = "https://api.twitch.tv/kraken";
  private String clientID;
  private String accessToken;
  private final RequestInterceptor requestInterceptor = new RequestInterceptor() {
    @Override
    public void intercept(RequestInterceptor.RequestFacade request) {
      String twitchMIME = "application/vnd.twitchtv.v3+json";
      request.addHeader("Accept", twitchMIME);
      if (clientID != null && !clientID.isEmpty()) {
        request.addHeader("Client-ID", clientID);
      }
      if (accessToken != null && !accessToken.isEmpty()) {
        request.addHeader("Authorization", "OAuth " + accessToken);
      }
    }
  };
  private RestAdapter restAdapter;

  private IngestsResource ingestsResource;
  private TeamResource teamResource;
  private VideosResource videosResource;
  private RootResource rootResource;
  private UsersResource usersResource;
  private GamesResource gamesResource;
  private StreamsResource streamsResource;
  private ChatResource chatResource;
  private BlocksResource blocksResource;
  private ChannelsResource channelsResource;
  private SubscriptionsResource subscriptionsResource;
  private FollowsResource followsResource;
  private SearchResource searchResource;

  public Ryoshi(boolean loggingEnable) {
    if(loggingEnable){
      restAdapter = new RestAdapter.Builder()
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setEndpoint(twitchAPIBaseURL)
          .setRequestInterceptor(requestInterceptor)
          .setErrorHandler(new TwitchErrorHandler())
          .build();
    } else {
      restAdapter = new RestAdapter.Builder()
          .setEndpoint(twitchAPIBaseURL)
          .setRequestInterceptor(requestInterceptor)
          .setErrorHandler(new TwitchErrorHandler())
          .build();
    }
    initResources();
  }

  public Ryoshi(String clientID, boolean loggingEnable) {
    this.clientID = clientID;
    if(loggingEnable){
      restAdapter = new RestAdapter.Builder()
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setEndpoint(twitchAPIBaseURL)
          .setRequestInterceptor(requestInterceptor)
          .setErrorHandler(new TwitchErrorHandler())
          .build();
    } else {
      restAdapter = new RestAdapter.Builder()
          .setEndpoint(twitchAPIBaseURL)
          .setRequestInterceptor(requestInterceptor)
          .setErrorHandler(new TwitchErrorHandler())
          .build();
    }
    initResources();
  }

  public Ryoshi(String clientID, String accessToken, boolean loggingEnable) {
    this.accessToken = accessToken;
    this.clientID = clientID;
    if(loggingEnable){
      restAdapter = new RestAdapter.Builder()
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setEndpoint(twitchAPIBaseURL)
          .setRequestInterceptor(requestInterceptor)
          .setErrorHandler(new TwitchErrorHandler())
          .build();
    } else {
      restAdapter = new RestAdapter.Builder()
          .setEndpoint(twitchAPIBaseURL)
          .setRequestInterceptor(requestInterceptor)
          .setErrorHandler(new TwitchErrorHandler())
          .build();
    }
    initResources();
  }

  /**
   * @return IngestsResource Interface
   */
  public IngestsResource ingests() {
    return ingestsResource;
  }

  /**
   * @return TeamResource Interface
   */
  public TeamResource team() {
    return teamResource;
  }

  /**
   * @return VideosResource Interface
   */
  public VideosResource videos() {
    return videosResource;
  }

  /**
   * @return RootResource Interface
   */
  public RootResource root() {
    return rootResource;
  }

  /**
   * @return UsersResource Interface
   */
  public UsersResource users() {
    return usersResource;
  }

  /**
   * @return GameResource Interface
   */
  public GamesResource games() {
    return gamesResource;
  }

  /**
   * @return StreamResource Interface
   */
  public StreamsResource streams() {
    return streamsResource;
  }

  /**
   * @return ChatResource Interface
   */
  public ChatResource chat() {
    return chatResource;
  }

  /**
   * @return BlocksResource Interface
   */
  public BlocksResource blocks() {
    return blocksResource;
  }

  /**
   * @return ChannelsResource Interface
   */
  public ChannelsResource channels() {
    return channelsResource;
  }

  /**
   * @return SubscriptionsResource Interface
   */
  public SubscriptionsResource subscriptions() {
    return subscriptionsResource;
  }

  /**
   * @return FollowsResource Interface
   */
  public FollowsResource follows() {
    return followsResource;
  }

  /**
   * @return SearchResource Interface
   */
  public SearchResource search() {
    return searchResource;
  }

  private void initResources() {
    ingestsResource = restAdapter.create(IngestsResource.class);
    teamResource = restAdapter.create(TeamResource.class);
    videosResource = restAdapter.create(VideosResource.class);
    rootResource = restAdapter.create(RootResource.class);
    usersResource = restAdapter.create(UsersResource.class);
    gamesResource = restAdapter.create(GamesResource.class);
    streamsResource = restAdapter.create(StreamsResource.class);
    chatResource = restAdapter.create(ChatResource.class);
    blocksResource = restAdapter.create(BlocksResource.class);
    channelsResource = restAdapter.create(ChannelsResource.class);
    subscriptionsResource = restAdapter.create(SubscriptionsResource.class);
    followsResource = restAdapter.create(FollowsResource.class);
    searchResource = restAdapter.create(SearchResource.class);
  }

}


text:
module Jekyll

  require 'sanitize'

  class Template
    @@header_base = nil
    @@header_styles = nil
    @@footer = nil

    # class_variables refers to looping over the variables in this class
    # In this case, header, header_full, footer....
    class_variables.each do |class_var|
      # Remove the '@@Symbol'
      name = class_var.to_s[2..-1].to_sym

      define_singleton_method name do |site|
        if class_variable_get(class_var).nil?
          templateFilePath = File.join(site.source,
            "_includes/codesamples/sample_#{name}.html")
          content = File.read(templateFilePath)
          class_variable_set(class_var,
            Liquid::Template.parse(content).render({
              "baseurl" => site.config["sample_link_base"]}))
        end
        class_variable_get(class_var)
      end
    end
  end

  class SampleHTMLAsset < Jekyll::StaticFile
    def initialize(site, relativeDir, filename, langcode, newpath)
      # IMPORTANT
      # Be careful when altering the names of these
      # class variables. Jekyll may be relying on the
      # variable for other things.
      @site = site
      @base = File.join Dir.pwd, site.config['WFContentSource']
      # We join here since relative_path is a read only attribute on StaticFile
      # http://www.rubydoc.info/github/mojombo/jekyll/master/Jekyll/StaticFile#relative_path-instance_method
      @dir  = File.join(langcode, relativeDir)
      @name = filename
      @newpath = newpath
      @contents = contents()
    end

    def contents()
      filePath = File.join(@base, @dir, @name)
      contents = File.read(filePath).force_encoding('UTF-8')
      contents.gsub!(/<!-- \/\/ \[(?:(?:START)|(?:END)) [^\]]+\] -->\s*\n?/m, "\n")
      contents.gsub!(/\/\* \/\/ \[(?:(?:START)|(?:END)) [^\]]+\] \*\/\s*\n?/m, "\n")
      contents.gsub!(/<!-- \/\/ \[TEMPLATE ([^\]]+)\] -->\s*\n/m) { |matches|
        tag = $1.downcase
        substituteText = ""
        if (tag == "header_base")
          substituteText = Template.header_base(@site)
        elsif (tag == "header_full")
          substituteText = Template.header_base(@site) + Template.header_styles(@site)
        elsif (tag == "footer")
          substituteText = Template.footer(@site)
        end
        substituteText
      }
      Liquid::Template.parse(contents).render(@site.site_payload)
    end

    def destination(dest)
      File.join(dest, @newpath, @name)
    end

    def write(dest)
      dest_path = destination(dest)
      dirname = File.dirname(dest_path)
      FileUtils.mkdir_p(dirname) if !File.exist?(dirname)
      file = File.new(dest_path, "w")
      file.write(@contents)
      file.close
      true
    end
  end
end


text:
package dawn.flow

class NamedFunction[A, B](f: A => B, name: String, rqModel: Boolean = false)
    extends (A => B) {
  override def toString = name
  def apply(x: A) = f(x)
  def requireModel = rqModel
}


text:
package org.dbflute.erflute.editor.controller.command.diagram_contents.element.connection;

import java.util.ArrayList;
import java.util.List;

import org.dbflute.erflute.editor.controller.command.AbstractCommand;
import org.dbflute.erflute.editor.model.ERDiagram;
import org.dbflute.erflute.editor.model.diagram_contents.element.connection.Bendpoint;
import org.dbflute.erflute.editor.model.diagram_contents.element.connection.Relationship;
import org.dbflute.erflute.editor.model.diagram_contents.element.connection.WalkerConnection;

public class DefaultLineCommand extends AbstractCommand {

    private int sourceXp;
    private int sourceYp;
    private int targetXp;
    private int targetYp;
    private final WalkerConnection connection;
    private final List<Bendpoint> oldBendpointList;

    public DefaultLineCommand(ERDiagram diagram, WalkerConnection connection) {
        if (connection instanceof Relationship) {
            final Relationship relation = (Relationship) connection;
            this.sourceXp = relation.getSourceXp();
            this.sourceYp = relation.getSourceYp();
            this.targetXp = relation.getTargetXp();
            this.targetYp = relation.getTargetYp();
        }

        this.connection = connection;
        this.oldBendpointList = connection.getBendpoints();
    }

    @Override
    protected void doExecute() {
        connection.setBendpoints(new ArrayList<Bendpoint>());
        if (connection instanceof Relationship) {
            final Relationship relation = (Relationship) connection;
            relation.setSourceLocationp(-1, -1);
            relation.setTargetLocationp(-1, -1);
            relation.setParentMove();
        }
    }

    @Override
    protected void doUndo() {
        connection.setBendpoints(oldBendpointList);
        if (connection instanceof Relationship) {
            final Relationship relation = (Relationship) connection;
            relation.setSourceLocationp(sourceXp, sourceYp);
            relation.setTargetLocationp(targetXp, targetYp);
            relation.setParentMove();
        }
    }
}


text:
@interface DTHTMLAttributedStringBuilder ()

- (void)_registerTagStartHandlers;
- (void)_registerTagEndHandlers;

@end

@implementation DTHTMLAttributedStringBuilder
{
	NSData *_data;
	NSDictionary *_options;
	BOOL _shouldKeepDocumentNodeTree;

	// settings for parsing
	CGFloat _textScale;
	DTColor *_defaultLinkColor;
	DTCSSStylesheet *_globalStyleSheet;
	NSURL *_baseURL;
	DTCoreTextFontDescriptor *_defaultFontDescriptor;
	DTCoreTextParagraphStyle *_defaultParagraphStyle;

	// root node inherits these defaults
	DTHTMLElement *_defaultTag;

	// parsing state, accessed from inside blocks
	NSMutableAttributedString *_tmpString;

	// GCD
	dispatch_queue_t _stringAssemblyQueue;
	dispatch_group_t _stringAssemblyGroup;
	dispatch_queue_t _dataParsingQueue;
	dispatch_group_t _dataParsingGroup;
	dispatch_queue_t _treeBuildingQueue;;
	dispatch_group_t _treeBuildingGroup;

	// lookup table for blocks that deal with begin and end tags
	NSMutableDictionary *_tagStartHandlers;
	NSMutableDictionary *_tagEndHandlers;

	DTHTMLAttributedStringBuilderWillFlushCallback _willFlushCallback;

	// new parsing
	DTHTMLElement *_rootNode;
	DTHTMLElement *_bodyElement;
	DTHTMLElement *_currentTag;
}

- (id)initWithHTML:(NSData *)data options:(NSDictionary *)options documentAttributes:(NSDictionary **)docAttributes
{
	self = [super init];
	if (self)
	{
		_data = data;
		_options = options;

		// documentAttributes ignored for now

		//GCD setup
		_stringAssemblyQueue = dispatch_queue_create("DTHTMLAttributedStringBuilder", 0);
		_stringAssemblyGroup = dispatch_group_create();
		_dataParsingQueue = dispatch_queue_create("DTHTMLAttributedStringBuilderParser", 0);
		_dataParsingGroup = dispatch_group_create();
		_treeBuildingQueue = dispatch_queue_create("DTHTMLAttributedStringBuilderParser Tree Queue", 0);
		_treeBuildingGroup = dispatch_group_create();
	}

	return self;
}

- (void)dealloc
{
#if !OS_OBJECT_USE_OBJC
	dispatch_release(_stringAssemblyQueue);
	dispatch_release(_stringAssemblyGroup);
	dispatch_release(_dataParsingQueue);
	dispatch_release(_dataParsingGroup);
	dispatch_release(_treeBuildingQueue);
	dispatch_release(_treeBuildingGroup);
#endif
}

- (BOOL)_buildString
{
#if DEBUG_LOG_METRICS
	// metrics: get start time
	CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
#endif

	// only with valid data
	if (![_data length])
	{
		return NO;
	}

	// register default handlers
	[self _registerTagStartHandlers];
	[self _registerTagEndHandlers];

 	// Specify the appropriate text encoding for the passed data, default is UTF8
	NSString *textEncodingName = [_options objectForKey:NSTextEncodingNameDocumentOption];
	NSStringEncoding encoding = NSUTF8StringEncoding; // default

	if (textEncodingName)
	{
		CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)textEncodingName);
		encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
	}

	// custom option to use iOS 6 attributes if running on iOS 6
	if ([[_options objectForKey:DTUseiOS6Attributes] boolValue])
	{
		if (![DTVersion osVersionIsLessThen:@"6.0"])
		{
			___useiOS6Attributes = YES;
		}
		else
		{
			___useiOS6Attributes = NO;
		}
	}
	else
	{
		// default is not to use them because many features are not supported
		___useiOS6Attributes = NO;
	}

	// custom option to scale text
	_textScale = [[_options objectForKey:NSTextSizeMultiplierDocumentOption] floatValue];
	if (!_textScale)
	{
		_textScale = 1.0f;
	}

	// use baseURL from options if present
	_baseURL = [_options objectForKey:NSBaseURLDocumentOption];

	// the combined style sheet for entire document
	_globalStyleSheet = [[DTCSSStylesheet defaultStyleSheet] copy];

	// do we have a default style sheet passed as option?
	DTCSSStylesheet *defaultStylesheet = [_options objectForKey:DTDefaultStyleSheet];
	if (defaultStylesheet)
	{
		// merge the default styles to the combined style sheet
		[_globalStyleSheet mergeStylesheet:defaultStylesheet];
	}

	// for performance reasons we will return this mutable string
	_tmpString = [[NSMutableAttributedString alloc] init];

	// base tag with font defaults
	_defaultFontDescriptor = [[DTCoreTextFontDescriptor alloc] initWithFontAttributes:nil];

	// set the default font size
	CGFloat defaultFontSize = 12.0f;

	NSNumber *defaultFontSizeNumber = [_options objectForKey:DTDefaultFontSize];

	if (defaultFontSizeNumber)
	{
		defaultFontSize = [defaultFontSizeNumber floatValue];
	}

	_defaultFontDescriptor.pointSize = defaultFontSize * _textScale;

	NSString *defaultFontFamily = [_options objectForKey:DTDefaultFontFamily];

	if (defaultFontFamily)
	{
		_defaultFontDescriptor.fontFamily = defaultFontFamily;
	}
	else
	{
		_defaultFontDescriptor.fontFamily = @"Times New Roman";
	}

	_defaultLinkColor = [_options objectForKey:DTDefaultLinkColor];

	if (_defaultLinkColor)
	{
		if ([_defaultLinkColor isKindOfClass:[NSString class]])
		{
			// convert from string to color
			_defaultLinkColor = [DTColor colorWithHTMLName:(NSString *)_defaultLinkColor];
		}

		// get hex code for the passed color
		NSString *colorHex = [_defaultLinkColor htmlHexString];

		// overwrite the style
		NSString *styleBlock = [NSString stringWithFormat:@"a {color:#%@;}", colorHex];
		[_globalStyleSheet parseStyleBlock:styleBlock];
	}

	// default is to have A underlined
	NSNumber *linkDecorationDefault = [_options objectForKey:DTDefaultLinkDecoration];

	if (linkDecorationDefault)
	{
		if (![linkDecorationDefault boolValue])
		{
			// remove default decoration
			[_globalStyleSheet parseStyleBlock:@"a {text-decoration:none;}"];
		}
	}

	DTColor *defaultLinkHighlightColor = [_options objectForKey:DTDefaultLinkHighlightColor];

	if (defaultLinkHighlightColor)
	{
		if ([defaultLinkHighlightColor isKindOfClass:[NSString class]])
		{
			// convert from string to color
			defaultLinkHighlightColor = [DTColor colorWithHTMLName:(NSString *)defaultLinkHighlightColor];
		}

		// get hex code for the passed color
		NSString *colorHex = [defaultLinkHighlightColor htmlHexString];

		// overwrite the style
		NSString *styleBlock = [NSString stringWithFormat:@"a:active {color:#%@;}", colorHex];
		[_globalStyleSheet parseStyleBlock:styleBlock];
	}

	// default paragraph style
	_defaultParagraphStyle = [DTCoreTextParagraphStyle defaultParagraphStyle];

	NSNumber *defaultLineHeightMultiplierNum = [_options objectForKey:DTDefaultLineHeightMultiplier];

	if (defaultLineHeightMultiplierNum)
	{
		CGFloat defaultLineHeightMultiplier = [defaultLineHeightMultiplierNum floatValue];
		_defaultParagraphStyle.lineHeightMultiple = defaultLineHeightMultiplier;
	}

	NSNumber *defaultTextAlignmentNum = [_options objectForKey:DTDefaultTextAlignment];

	if (defaultTextAlignmentNum)
	{
		_defaultParagraphStyle.alignment = (CTTextAlignment)[defaultTextAlignmentNum integerValue];
	}

	NSNumber *defaultFirstLineHeadIndent = [_options objectForKey:DTDefaultFirstLineHeadIndent];
	if (defaultFirstLineHeadIndent)
	{
		_defaultParagraphStyle.firstLineHeadIndent = [defaultFirstLineHeadIndent integerValue];
	}

	NSNumber *defaultHeadIndent = [_options objectForKey:DTDefaultHeadIndent];
	if (defaultHeadIndent)
	{
		_defaultParagraphStyle.headIndent = [defaultHeadIndent integerValue];
	}

	NSNumber *defaultListIndent = [_options objectForKey:DTDefaultListIndent];
	if (defaultListIndent)
	{
		_defaultParagraphStyle.listIndent = [defaultListIndent integerValue];
	}

	_defaultTag = [[DTHTMLElement alloc] init];
	_defaultTag.fontDescriptor = _defaultFontDescriptor;
	_defaultTag.paragraphStyle = _defaultParagraphStyle;
	_defaultTag.textScale = _textScale;

	id defaultColor = [_options objectForKey:DTDefaultTextColor];
	if (defaultColor)
	{
		if ([defaultColor isKindOfClass:[DTColor class]])
		{
			// already a DTColor
			_defaultTag.textColor = defaultColor;
		}
		else
		{
			// need to convert first
			_defaultTag.textColor = [DTColor colorWithHTMLName:defaultColor];
		}
	}

	// create a parser
	DTHTMLParser *parser = [[DTHTMLParser alloc] initWithData:_data encoding:encoding];
	parser.delegate = (id)self;

	__block BOOL result;
	dispatch_group_async(_dataParsingGroup, _dataParsingQueue, ^{ result = [parser parse]; });

	// wait until all string assembly is complete
	dispatch_group_wait(_dataParsingGroup, DISPATCH_TIME_FOREVER);
	dispatch_group_wait(_treeBuildingGroup, DISPATCH_TIME_FOREVER);
	dispatch_group_wait(_stringAssemblyGroup, DISPATCH_TIME_FOREVER);

	// clean up handlers because they retained self
	_tagStartHandlers = nil;
	_tagEndHandlers = nil;

#if DEBUG_LOG_METRICS
	// metrics: get end time
	CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();

	// output metrics
	NSLog(@"DTCoreText created string from %@ HTML in %.2f sec", [NSString stringByFormattingBytes:[_data length]], endTime-startTime);
#endif

	return result;
}

- (NSAttributedString *)generatedAttributedString
{
	if (!_tmpString)
	{
		[self _buildString];
	}

	return _tmpString;
}

#pragma mark GCD

- (void)_registerTagStartHandlers
{
	if (_tagStartHandlers)
	{
		return;
	}

	_tagStartHandlers = [[NSMutableDictionary alloc] init];

	void (^blockquoteBlock)(void) = ^
	{
		_currentTag.paragraphStyle.headIndent += 25.0 * _textScale;
		_currentTag.paragraphStyle.firstLineHeadIndent = _currentTag.paragraphStyle.headIndent;
		_currentTag.paragraphStyle.paragraphSpacing = _defaultFontDescriptor.pointSize;
	};

	[_tagStartHandlers setObject:[blockquoteBlock copy] forKey:@"blockquote"];

	void (^aBlock)(void) = ^
	{
		if (_currentTag.isColorInherited || !_currentTag.textColor)
		{
			_currentTag.textColor = _defaultLinkColor;
			_currentTag.isColorInherited = NO;
		}

		// remove line breaks and whitespace in links
		NSString *cleanString = [[_currentTag attributeForKey:@"href"] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
		cleanString = [cleanString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

		NSURL *link = [NSURL URLWithString:cleanString];

		// deal with relative URL
		if (![link scheme])
		{
			if ([cleanString length])
			{
				link = [NSURL URLWithString:cleanString relativeToURL:_baseURL];

				if (!link)
				{
					// NSURL did not like the link, so let's encode it
					cleanString = [cleanString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

					link = [NSURL URLWithString:cleanString relativeToURL:_baseURL];
				}
			}
			else
			{
				link = _baseURL;
			}
		}

		_currentTag.link = link;

		// the name attribute of A becomes an anchor
		_currentTag.anchorName = [_currentTag attributeForKey:@"name"];
	};

	[_tagStartHandlers setObject:[aBlock copy] forKey:@"a"];

	void (^liBlock)(void) = ^
	{
		_currentTag.paragraphStyle.paragraphSpacing = 0;

		DTCSSListStyle *listStyle = [_currentTag.paragraphStyle.textLists lastObject];

		if (listStyle.type != DTCSSListStyleTypeNone)
		{
			// first tab is to right-align bullet, numbering against
			CGFloat tabOffset = _currentTag.paragraphStyle.headIndent - 5.0f*_textScale;
			[_currentTag.paragraphStyle addTabStopAtPosition:tabOffset alignment:kCTRightTextAlignment];
		}

		// second tab is for the beginning of first line after bullet
		[_currentTag.paragraphStyle addTabStopAtPosition:_currentTag.paragraphStyle.headIndent alignment:	kCTLeftTextAlignment];
	};

	[_tagStartHandlers setObject:[liBlock copy] forKey:@"li"];

	void (^listBlock)(void) = ^
	{
		_currentTag.paragraphStyle.firstLineHeadIndent = _currentTag.paragraphStyle.headIndent;
		_currentTag.paragraphStyle.headIndent += _currentTag.paragraphStyle.listIndent;

		// create the appropriate list style from CSS
		DTCSSListStyle *newListStyle = [_currentTag listStyle];

		// append this list style to the current paragraph style text lists
		NSMutableArray *textLists = [_currentTag.paragraphStyle.textLists mutableCopy];
		if (!textLists)
		{
			textLists = [NSMutableArray array];
		}

		[textLists addObject:newListStyle];

		// workaround for different styles on stacked lists
		if ([textLists count]>1) // not necessary for first
		{
			// find out if each list is ordered or unordered
			NSMutableArray *tmpArray = [NSMutableArray array];
			for (DTCSSListStyle *oneList in textLists)
			{
				if ([oneList isOrdered])
				{
					[tmpArray addObject:@"ol"];
				}
				else
				{
					[tmpArray addObject:@"ul"];
				}
			}

			// build a CSS selector
			NSString *selector = [tmpArray componentsJoinedByString:@" "];

			// find style
			NSDictionary *style = [[_globalStyleSheet styles] objectForKey:selector];

			if (style)
			{
				[newListStyle updateFromStyleDictionary:style];
			}
		}

		_currentTag.paragraphStyle.textLists = textLists;
	};

	[_tagStartHandlers setObject:[listBlock copy] forKey:@"ul"];
	[_tagStartHandlers setObject:[listBlock copy] forKey:@"ol"];

	void (^h1Block)(void) = ^
	{
		_currentTag.headerLevel = 1;
	};
	[_tagStartHandlers setObject:[h1Block copy] forKey:@"h1"];

	void (^h2Block)(void) = ^
	{
		_currentTag.headerLevel = 2;
	};
	[_tagStartHandlers setObject:[h2Block copy] forKey:@"h2"];

	void (^h3Block)(void) = ^
	{
		_currentTag.headerLevel = 3;
	};
	[_tagStartHandlers setObject:[h3Block copy] forKey:@"h3"];

	void (^h4Block)(void) = ^
	{
		_currentTag.headerLevel = 4;
	};
	[_tagStartHandlers setObject:[h4Block copy] forKey:@"h4"];

	void (^h5Block)(void) = ^
	{
		_currentTag.headerLevel = 5;
	};
	[_tagStartHandlers setObject:[h5Block copy] forKey:@"h5"];

	void (^h6Block)(void) = ^
	{
		_currentTag.headerLevel = 6;
	};
	[_tagStartHandlers setObject:[h6Block copy] forKey:@"h6"];

	void (^fontBlock)(void) = ^
	{
		NSString *sizeAttribute = [_currentTag attributeForKey:@"size"];

		if (sizeAttribute)
		{
			NSInteger sizeValue = [sizeAttribute intValue];

			switch (sizeValue)
			{
				case 1:
					_currentTag.fontDescriptor.pointSize = _textScale * 10.0f;
					break;
				case 2:
					_currentTag.fontDescriptor.pointSize = _textScale * 13.0f;
					break;
				case 3:
					_currentTag.fontDescriptor.pointSize = _textScale * 16.0f;
					break;
				case 4:
					_currentTag.fontDescriptor.pointSize = _textScale * 18.0f;
					break;
				case 5:
					_currentTag.fontDescriptor.pointSize = _textScale * 24.0f;
					break;
				case 6:
					_currentTag.fontDescriptor.pointSize = _textScale * 32.0f;
					break;
				case 7:
					_currentTag.fontDescriptor.pointSize = _textScale * 48.0f;
					break;
				default:
					_currentTag.fontDescriptor.pointSize = _defaultFontDescriptor.pointSize;
					break;
			}
		}

		NSString *face = [_currentTag attributeForKey:@"face"];

		if (face)
		{
			_currentTag.fontDescriptor.fontName = face;

			// face usually invalidates family
			_currentTag.fontDescriptor.fontFamily = nil;
		}

		NSString *color = [_currentTag attributeForKey:@"color"];

		if (color)
		{
			_currentTag.textColor = [DTColor colorWithHTMLName:color];
		}
	};

	[_tagStartHandlers setObject:[fontBlock copy] forKey:@"font"];

	void (^pBlock)(void) = ^
	{
		_currentTag.paragraphStyle.firstLineHeadIndent = _currentTag.paragraphStyle.headIndent + _defaultParagraphStyle.firstLineHeadIndent;
	};

	[_tagStartHandlers setObject:[pBlock copy] forKey:@"p"];
}

- (void)_registerTagEndHandlers
{
	if (_tagEndHandlers)
	{
		return;
	}

	_tagEndHandlers = [[NSMutableDictionary alloc] init];

	void (^objectBlock)(void) = ^
	{
		if ([_currentTag isKindOfClass:[DTTextAttachmentHTMLElement class]])
		{
			if ([_currentTag.textAttachment isKindOfClass:[DTObjectTextAttachment class]])
			{
				DTObjectTextAttachment *objectAttachment = (DTObjectTextAttachment *)_currentTag.textAttachment;

				// transfer the child nodes to the attachment
				objectAttachment.childNodes = [_currentTag.childNodes copy];
			}
		}
	};

	[_tagEndHandlers setObject:[objectBlock copy] forKey:@"object"];

	void (^styleBlock)(void) = ^
	{
		DTCSSStylesheet *localSheet = [(DTStylesheetHTMLElement *)_currentTag stylesheet];
		[_globalStyleSheet mergeStylesheet:localSheet];
	};

	[_tagEndHandlers setObject:[styleBlock copy] forKey:@"style"];

	void (^linkBlock)(void) = ^
	{
		NSString *href = [_currentTag attributeForKey:@"href"];
		NSString *type = [[_currentTag attributeForKey:@"type"] lowercaseString];

		if ([type isEqualToString:@"text/css"])
		{
			NSURL *stylesheetURL = [NSURL URLWithString:href relativeToURL:_baseURL];
			if ([stylesheetURL isFileURL])
			{
				NSString *stylesheetContent = [NSString stringWithContentsOfURL:stylesheetURL encoding:NSUTF8StringEncoding error:nil];
				if (stylesheetContent)
				{
					DTCSSStylesheet *localSheet = [[DTCSSStylesheet alloc] initWithStyleBlock:stylesheetContent];
					[_globalStyleSheet mergeStylesheet:localSheet];
				}
			}
			else {
				NSLog(@"WARNING: css link referencing a non-local target, ignored");
			}
		}
	};

	[ _tagEndHandlers setObject:[linkBlock copy] forKey:@"link"];
}

#pragma mark DTHTMLParser Delegate

- (void)parser:(DTHTMLParser *)parser didStartElement:(NSString *)elementName attributes:(NSDictionary *)attributeDict
{
	dispatch_group_async(_treeBuildingGroup, _treeBuildingQueue, ^{
		DTHTMLElement *newNode = [DTHTMLElement elementWithName:elementName attributes:attributeDict options:_options];

		DTHTMLElement *previousLastChild = nil;

		if (_currentTag)
		{
			// inherit stuff
			[newNode inheritAttributesFromElement:_currentTag];
			[newNode interpretAttributes];

			previousLastChild = [_currentTag.childNodes lastObject];

			// add as new child of current node
			[_currentTag addChildNode:newNode];

			// remember body node
			if (!_bodyElement && [newNode.name isEqualToString:@"body"])
			{
				_bodyElement = newNode;
			}
		}
		else
		{
			// might be first node ever
			if (!_rootNode)
			{
				_rootNode = newNode;

				[_rootNode inheritAttributesFromElement:_defaultTag];
				[_rootNode interpretAttributes];
			}
		}

		// apply style from merged style sheet
		NSDictionary *mergedStyles = [_globalStyleSheet mergedStyleDictionaryForElement:newNode];
		if (mergedStyles)
		{
			[newNode applyStyleDictionary:mergedStyles];
		}

		// adding a block element eliminates previous trailing white space text node
		// because a new block starts on a new line
		if (previousLastChild && newNode.displayStyle != DTHTMLElementDisplayStyleInline)
		{
			if ([previousLastChild isKindOfClass:[DTTextHTMLElement class]])
			{
				DTTextHTMLElement *textElement = (DTTextHTMLElement *)previousLastChild;

				if ([[textElement text] isIgnorableWhitespace])
				{
					[_currentTag removeChildNode:textElement];
				}
			}
		}

		_currentTag = newNode;

		// find block to execute for this tag if any
		void (^tagBlock)(void) = [_tagStartHandlers objectForKey:elementName];

		if (tagBlock)
		{
			tagBlock();
		}
	});
}

- (void)parser:(DTHTMLParser *)parser didEndElement:(NSString *)elementName
{
	dispatch_group_async(_treeBuildingGroup, _treeBuildingQueue, ^{
		// output the element if it is direct descendant of body tag, or close of body in case there are direct text nodes

		// find block to execute for this tag if any
		void (^tagBlock)(void) = [_tagEndHandlers objectForKey:elementName];

		if (tagBlock)
		{
			tagBlock();
		}

		if (_currentTag.displayStyle != DTHTMLElementDisplayStyleNone)
		{
			if (_currentTag == _bodyElement || _currentTag.parentElement == _bodyElement)
			{
				DTHTMLElement *theTag = _currentTag;

				dispatch_group_async(_stringAssemblyGroup, _stringAssemblyQueue, ^{
					// has children that have not been output yet
					if ([theTag needsOutput])
					{
						// caller gets opportunity to modify tag before it is written
						if (_willFlushCallback)
						{
							_willFlushCallback(theTag);
						}

						NSAttributedString *nodeString = [theTag attributedString];

						if (nodeString)
						{
							// if this is a block element then we need a paragraph break before it
							if (theTag.displayStyle != DTHTMLElementDisplayStyleInline)
							{
								if ([_tmpString length] && ![[_tmpString string] hasSuffix:@"\n"])
								{
									// trim off whitespace
									while ([[_tmpString string] hasSuffixCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]])
									{
										[_tmpString deleteCharactersInRange:NSMakeRange([_tmpString length]-1, 1)];
									}

									[_tmpString appendString:@"\n"];
								}
							}

							[_tmpString appendAttributedString:nodeString];
							theTag.didOutput = YES;

							if (!_shouldKeepDocumentNodeTree)
							{
								// we don't need the children any more
								[theTag removeAllChildNodes];
							}
						}

					}
				});
			}

		}

		while (![_currentTag.name isEqualToString:elementName])
		{
			// missing end of element, attempt to recover
			_currentTag = [_currentTag parentElement];
		}

		// go back up a level
		_currentTag = [_currentTag parentElement];
	});
}

- (void)parser:(DTHTMLParser *)parser foundCharacters:(NSString *)string
{

	dispatch_group_async(_treeBuildingGroup, _treeBuildingQueue, ^{
		NSAssert(_currentTag, @"Cannot add text node without a current node");

		if ([string isIgnorableWhitespace])
		{
			// ignore whitespace as first element of block element
			if (_currentTag.displayStyle!=DTHTMLElementDisplayStyleInline && ![_currentTag.childNodes count])
			{
				return;
			}

			// ignore whitespace following a block element
			DTHTMLElement *previousTag = [_currentTag.childNodes lastObject];

			if (previousTag.displayStyle != DTHTMLElementDisplayStyleInline)
			{
				return;
			}

			// ignore whitespace following a BR
			if ([previousTag isKindOfClass:[DTBreakHTMLElement class]])
			{
				return;
			}
		}

		// adds a text node to the current node
		DTTextHTMLElement *textNode = [[DTTextHTMLElement alloc] init];
		textNode.text = string;

		[textNode inheritAttributesFromElement:_currentTag];
		[textNode interpretAttributes];

		// save it for later output
		[_currentTag addChildNode:textNode];

		DTHTMLElement *theTag = _currentTag;

		// text directly contained in body needs to be output right away
		if (theTag == _bodyElement)
		{
			dispatch_group_async(_stringAssemblyGroup, _stringAssemblyQueue, ^{
				[_tmpString appendAttributedString:[textNode attributedString]];
				theTag.didOutput = YES;
			});

			// only add it to current tag if we need it
			if (_shouldKeepDocumentNodeTree)
			{
				[theTag addChildNode:textNode];
			}

			return;
		}

	});
}

- (void)parser:(DTHTMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
	dispatch_group_async(_treeBuildingGroup, _treeBuildingQueue, ^{
		NSAssert(_currentTag, @"Cannot add text node without a current node");

		NSString *styleBlock = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];

		// adds a text node to the current node
		DTHTMLParserTextNode *textNode = [[DTHTMLParserTextNode alloc] initWithCharacters:styleBlock];

		[_currentTag addChildNode:textNode];
	});
}

- (void)parserDidEndDocument:(DTHTMLParser *)parser
{
	dispatch_group_async(_treeBuildingGroup, _treeBuildingQueue, ^{
		NSAssert(!_currentTag, @"Something went wrong, at end of document there is still an open node");

		dispatch_group_async(_stringAssemblyGroup, _stringAssemblyQueue, ^{
			// trim off white space at end
			while ([[_tmpString string] hasSuffixCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]])
			{
				[_tmpString deleteCharactersInRange:NSMakeRange([_tmpString length]-1, 1)];
			}
		});
	});
}

#pragma mark Properties

@synthesize willFlushCallback = _willFlushCallback;
@synthesize shouldKeepDocumentNodeTree = _shouldKeepDocumentNodeTree;

@end


text:
"""
    DocuSign REST API

    The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.  # noqa: E501

    OpenAPI spec version: v2.1
    Contact: devcenter@docusign.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six

from docusign_esign.client.configuration import Configuration

class EnvelopeDocumentsResult(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'envelope_documents': 'list[EnvelopeDocument]',
        'envelope_id': 'str'
    }

    attribute_map = {
        'envelope_documents': 'envelopeDocuments',
        'envelope_id': 'envelopeId'
    }

    def __init__(self, _configuration=None, **kwargs):  # noqa: E501
        """EnvelopeDocumentsResult - a model defined in Swagger"""  # noqa: E501
        if _configuration is None:
            _configuration = Configuration()
        self._configuration = _configuration

        self._envelope_documents = None
        self._envelope_id = None
        self.discriminator = None

        setattr(self, "_{}".format('envelope_documents'), kwargs.get('envelope_documents', None))
        setattr(self, "_{}".format('envelope_id'), kwargs.get('envelope_id', None))

    @property
    def envelope_documents(self):
        """Gets the envelope_documents of this EnvelopeDocumentsResult.  # noqa: E501

          # noqa: E501

        :return: The envelope_documents of this EnvelopeDocumentsResult.  # noqa: E501
        :rtype: list[EnvelopeDocument]
        """
        return self._envelope_documents

    @envelope_documents.setter
    def envelope_documents(self, envelope_documents):
        """Sets the envelope_documents of this EnvelopeDocumentsResult.

          # noqa: E501

        :param envelope_documents: The envelope_documents of this EnvelopeDocumentsResult.  # noqa: E501
        :type: list[EnvelopeDocument]
        """

        self._envelope_documents = envelope_documents

    @property
    def envelope_id(self):
        """Gets the envelope_id of this EnvelopeDocumentsResult.  # noqa: E501

        The envelope ID of the envelope status that failed to post.  # noqa: E501

        :return: The envelope_id of this EnvelopeDocumentsResult.  # noqa: E501
        :rtype: str
        """
        return self._envelope_id

    @envelope_id.setter
    def envelope_id(self, envelope_id):
        """Sets the envelope_id of this EnvelopeDocumentsResult.

        The envelope ID of the envelope status that failed to post.  # noqa: E501

        :param envelope_id: The envelope_id of this EnvelopeDocumentsResult.  # noqa: E501
        :type: str
        """

        self._envelope_id = envelope_id

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(EnvelopeDocumentsResult, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, EnvelopeDocumentsResult):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, EnvelopeDocumentsResult):
            return True

        return self.to_dict() != other.to_dict()


text:
package edu.utah.ece.async.ibiosim.gui.lpnEditor;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Properties;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.ibiosim.gui.Gui;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyList;
import edu.utah.ece.async.lema.verification.lpn.*;

/**
 *
 * @author Chris Myers
 * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
 * @version %I%
 */
public class VariablesPanel extends JPanel implements ActionListener {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String name = "", type = "", selList;

	private PropertyList variablesList;

	private String[] options = { "Ok", "Cancel" };

	private Boolean continuous, integer;

	private LPN lhpn;

	private JPanel initPanel = null;

	private PropertyField initValue = null, initRate;

	private JComboBox modeBox, initBox;

	private static final String[] types = new String[] { "boolean",
			"continuous", "discrete" };

	private static final String[] modes = new String[] { "input", "output",
			"internal" };

	private static final String[] booleans = new String[] { "true", "false",
			"unknown" };

	private HashMap<String, PropertyField> fields = null;

	public VariablesPanel(String selected, PropertyList variablesList,
			Boolean boolCont, Boolean integer, LPN lhpn) {
		super(new GridLayout(5, 1));
		if (selected != null) {
			String[] array = selected.split(" ");
			this.name = array[0];
		} else {
			this.name = selected;
		}
		this.selList = selected;
		this.variablesList = variablesList;
		this.lhpn = lhpn;
		this.continuous = boolCont;
		this.integer = integer;

		fields = new HashMap<String, PropertyField>();

		// ID field
		PropertyField field = new PropertyField(GlobalConstants.ID, "", null,
				null, Utility.ATACSIDstring);
		fields.put(GlobalConstants.ID, field);
		add(field);

		// Type label
		JPanel tempPanel = new JPanel();
		if (continuous) {
			type = types[1];
		} else if (integer) {
			type = types[2];
		} else {
			type = types[0];
		}
		JLabel tempLabel = new JLabel("Type");
		JLabel typeLabel = new JLabel(type);
		tempPanel.setLayout(new GridLayout(1, 2));
		tempPanel.add(tempLabel);
		tempPanel.add(typeLabel);
		add(tempPanel);

		// Initial field
		if (continuous || integer) {
			if (name != null) {
				String initVal = lhpn.getInitialVal(name);
				initValue = new PropertyField("Initial Value", initVal, null,
						null, Utility.NAMEstring);
			} else {
				initValue = new PropertyField("Initial Value", "0", null, null,
						Utility.NAMEstring);
			}
			fields.put("Initial value", initValue);
			add(initValue);
		} else {
			initPanel = new JPanel();
			JLabel initLabel = new JLabel("Initial Value");
			initBox = new JComboBox(booleans);
			initBox.setSelectedItem(booleans[1]);
			initPanel.setLayout(new GridLayout(1, 2));
			initPanel.add(initLabel);
			initPanel.add(initBox);
			add(initPanel);
		}

		// Mode field
		tempPanel = new JPanel();
		JLabel modeLabel = new JLabel("Mode");
		modeBox = new JComboBox(modes);
		modeBox.setSelectedItem(modes[0]);
		modeBox.addActionListener(this);
		tempPanel.setLayout(new GridLayout(1, 2));
		tempPanel.add(modeLabel);
		tempPanel.add(modeBox);
		add(tempPanel);

		// Initial rate field
		if (continuous) {
			if (name != null) {
				String rate = lhpn.getInitialRate(name);
				initRate = new PropertyField("Initial Rate", rate, null, null,
						Utility.NAMEstring);
			} else {
				initRate = new PropertyField("Initial Rate", "0", null, null,
						Utility.NAMEstring);
			}
			fields.put("Initial rate", initRate);
			add(initRate);
		}

		String oldName = null;
		if (name != null) {
			oldName = name;
			fields.get(GlobalConstants.ID).setValue(name);
			if (lhpn.isContinuous(name) || lhpn.isInteger(name)) {
				String initVal = lhpn.getInitialVal(name);
				fields.get("Initial value").setValue(initVal);
			} else {
				HashMap<String, String> inits;
				if (lhpn.isInput(name)) {
					inits = lhpn.getBoolInputs();
				} else {
					inits = lhpn.getBoolOutputs();
				}
				initBox.setSelectedItem(inits.get(name));
			}
			if (lhpn.isInput(name)) {
				modeBox.setSelectedItem(modes[0]);
			} else if (lhpn.isOutput(name)) {
				modeBox.setSelectedItem(modes[1]);
			} else {
				modeBox.setSelectedItem(modes[2]);
			}
			if (lhpn.isContinuous(name)) {
				String initRate = lhpn.getInitialRate(name);
				fields.get("Initial rate").setValue(initRate);
				fields.get(GlobalConstants.ID).setValue(name);
			}
		}

		boolean display = false;
		while (!display) {
			display = openGui(oldName);
		}
	}

	private boolean checkValues() {
		for (PropertyField f : fields.values()) {
			if (!f.isValidValue()) {
				return false;
			}
		}
		return true;
	}

	private boolean openGui(String oldName) {
		int value = JOptionPane.showOptionDialog(Gui.frame, this,
				"Variable Editor", JOptionPane.YES_NO_OPTION,
				JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
		if (value == JOptionPane.YES_OPTION) {
			if (!checkValues()) {
				return false;
			}
			String[] allVariables = lhpn.getAllIDs();
			if (oldName == null) {
				for (int i = 0; i < allVariables.length; i++) {
					if (allVariables[i] != null) {
						if (allVariables[i].equals(fields.get(
								GlobalConstants.ID).getValue())) {
							 JOptionPane.showMessageDialog(Gui.frame, "Variable id already exists.", "Error", JOptionPane.ERROR_MESSAGE);
							return false;
						}
					}
				}
			} else if (!oldName.equals(fields.get(GlobalConstants.ID)
					.getValue())) {
				for (int i = 0; i < allVariables.length; i++) {
					if (allVariables[i].equals(fields.get(GlobalConstants.ID)
							.getValue())) {
					  JOptionPane.showMessageDialog(Gui.frame,
              "Variable id already exists.", "Error", JOptionPane.ERROR_MESSAGE);
						return false;
					}
				}
			}
			if (fields.containsKey("Initial value")) {
				if (!(fields.get("Initial value").getValue().matches("-?\\d+") || fields
						.get("Initial value").getValue().matches("\\[-?\\d+,-?\\d+\\]"))) {
					 JOptionPane.showMessageDialog(Gui.frame, "Initial value must be an integer or a range of integers.", "Error", JOptionPane.ERROR_MESSAGE);
					return false;
				}
			}
			if (fields.containsKey("Initial rate")) {
				if (!(fields.get("Initial rate").getValue().matches("-?\\d+") || fields
						.get("Initial rate").getValue().matches("\\[-?\\d+,-?\\d+\\]"))) {
				  JOptionPane.showMessageDialog(Gui.frame, "Initial rate must be an integer or a range of integers.", "Error", JOptionPane.ERROR_MESSAGE);

					return false;
				}
			}
			String id = fields.get(GlobalConstants.ID).getValue();

			// Check to see if we need to add or edit
			Properties property = new Properties();
			for (PropertyField f : fields.values()) {
				if (f.getState() == null
						|| f.getState().equals(PropertyField.states[1])) {
					property.put(f.getKey(), f.getValue());
				}
			}
			String tempVal = "";
			if (property.containsKey("Initial Value")) {
				tempVal = property.getProperty("Initial Value");
				property.setProperty("value", tempVal);
				property.remove("Initial Value");
			}
			if (property.containsKey("Initial Rate")) {
				tempVal = property.getProperty("Initial Rate");
				property.setProperty("rate", tempVal);
				property.remove("Initial Rate");
			}

			if (name != null && oldName != null && !oldName.equals(id)) {
				lhpn.changeVariableName(oldName, id);
			}
			if (id.equals(oldName)) {
				lhpn.removeVar(id);
			}
			if (lhpn.isContinuous(id) || continuous) {
				tempVal = fields.get("Initial value").getValue();
				lhpn.addContinuous(id, property);
				lhpn.getVariable(id).setPort(
						modeBox.getSelectedItem().toString());
			} else if (lhpn.isInteger(id) || integer) {
				tempVal = fields.get("Initial value").getValue();
				lhpn.addInteger(id, tempVal);
				lhpn.getVariable(id).setPort(
						modeBox.getSelectedItem().toString());
			} else {
				lhpn.addBoolean(id, initBox.getSelectedItem().toString());
				lhpn.getVariable(id).setPort(
						modeBox.getSelectedItem().toString());
			}
			variablesList.removeItem(selList);
			String list;
			if (continuous || integer) {
				list = id + " - " + type + " - " + modeBox.getSelectedItem().toString() + " - " + tempVal;
			} else {
				list = id + " - " + type + " - " + modeBox.getSelectedItem().toString() + " - "
						+ initBox.getSelectedItem().toString();
			}
			if (continuous) {
				tempVal = fields.get("Initial rate").getValue();
				list = list + " - " + tempVal;
			}
			variablesList.removeItem(list);
			variablesList.addItem(list);
			variablesList.setSelectedValue(id, true);

		} else if (value == JOptionPane.NO_OPTION) {
			return true;
		}
		return true;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("comboBoxChanged")) {
		}
	}

}


text:
<?php
/**
 * If the queued jobs module is installed, this will be used instead of
 * updating vfi's in onBeforeWrite.
 *
 * @author  Mark Guinn <mark@adaircreative.com>
 * @date    07.02.2015
 * @package shop_search
 * @subpackage helpers
 */
if (!interface_exists('QueuedJob')) {
    return;
}

class VirtualFieldIndexQueuedJob extends AbstractQueuedJob implements QueuedJob
{
    /**
     * The QueuedJob queue to use when processing updates
     * @config
     * @var int
     */
    private static $reindex_queue = 2; // QueuedJob::QUEUED;

    /**
     * @param DataObject $object
     * @param array $fields
     */
    public function __construct($object = null, $fields = array())
    {
        if ($object) {
            $this->setObject($object);
        }
        $this->rebuildFields = $fields;
    }

    /**
     * Helper method
     */
    public function triggerProcessing()
    {
        singleton('QueuedJobService')->queueJob($this);
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        $obj = $this->getObject();
        return "Update Virtual Field Indexes: " . ($obj ? $obj->getTitle() : '???');
    }

    /**
     * Reprocess any needed fields
     */
    public function process()
    {
        Versioned::reading_stage('Stage');
        /** @var DataObject|VirtualFieldIndex $obj */
        $obj = $this->getObject();

        if ($obj) {
            $obj->rebuildVFI();
        }

        $this->isComplete = true;
    }
}


text:
<?php

/**
 * @file
 * Tests for ChapterThree\AppleNewsAPI\Document\Components\Text.
 */

use ChapterThree\AppleNewsAPI\Document\Base;
use ChapterThree\AppleNewsAPI\Document\Styles\Fills\Fill;

/**
 * A test class for Fill.
 */
class FillTestClass extends Fill {

  /**
   * {@inheritdoc}
   */
  public function __construct($type) {
    parent::__construct($type);
  }

}

/**
 * Tests for the Fill class.
 */
class FillTest extends PHPUnit_Framework_TestCase {

  /**
   * Setting properties and outputting json.
   */
  public function testSetters() {

    $obj = new FillTestClass('video');

    $json = '{"type":"video"}';

    $this->assertJsonStringEqualsJsonString($json, $obj->json());

    // Optional properties.
    $json = '{"type":"video","attachment":"fixed"}';
    $obj->setAttachment('fixed');
    $this->assertJsonStringEqualsJsonString($json, $obj->json());

  }

}


text:
----

##### A collection of tree views for front-end frameworks.

----

This is the npm repository for the **@bosket/tools** module of the Bosket library.

For more details, please check out the [Bosket website](https://elbywan.github.io/bosket/) or the [source code repository](https://github.com/elbywan/bosket).


text:
from tempest.lib.services.compute import migrations_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services.compute import base

class TestMigrationsClient(base.BaseComputeServiceTest):
    FAKE_MIGRATION_INFO = {"migrations": [{
        "created_at": "2012-10-29T13:42:02",
        "dest_compute": "compute2",
        "dest_host": "1.2.3.4",
        "dest_node": "node2",
        "id": 1234,
        "instance_uuid": "e9e4fdd7-f956-44ff-bfeb-d654a96ab3a2",
        "new_instance_type_id": 2,
        "old_instance_type_id": 1,
        "source_compute": "compute1",
        "source_node": "node1",
        "status": "finished",
        "updated_at": "2012-10-29T13:42:02"}]}

    def setUp(self):
        super(TestMigrationsClient, self).setUp()
        fake_auth = fake_auth_provider.FakeAuthProvider()
        self.mg_client_obj = migrations_client.MigrationsClient(
            fake_auth, 'compute', 'regionOne')

    def _test_list_migrations(self, bytes_body=False):
        self.check_service_client_function(
            self.mg_client_obj.list_migrations,
            'tempest.lib.common.rest_client.RestClient.get',
            self.FAKE_MIGRATION_INFO,
            bytes_body)

    def test_list_migration_with_str_body(self):
        self._test_list_migrations()

    def test_list_migration_with_bytes_body(self):
        self._test_list_migrations(True)


text:
package org.scalatest

import SharedHelpers.thisLineNumber
import exceptions.TestFailedException
import org.scalactic.Prettifier
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers._

class ListShouldBeEmptyLogicalOrSpec extends AnyFunSpec {

  private val prettifier = Prettifier.default

  //ADDITIONAL//

  val fileName: String = "ListShouldBeEmptyLogicalOrSpec.scala"

  def wasEqualTo(left: Any, right: Any): String =
    FailureMessages.wasEqualTo(prettifier, left, right)

  def wasNotEqualTo(left: Any, right: Any): String = {
    val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
    FailureMessages.wasNotEqualTo(prettifier, leftee, rightee)
  }

  def equaled(left: Any, right: Any): String =
    FailureMessages.equaled(prettifier, left, right)

  def didNotEqual(left: Any, right: Any): String = {
    val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right)
    FailureMessages.didNotEqual(prettifier, leftee, rightee)
  }

  def wasNotEmpty(left: Any): String =
    FailureMessages.wasNotEmpty(prettifier, left)

  def wasEmpty(left: Any): String =
    FailureMessages.wasEmpty(prettifier, left)

  def allError(message: String, lineNumber: Int, left: Any): String = {
    val messageWithIndex = UnquotedString("  " + FailureMessages.forAssertionsGenTraversableMessageWithStackDepth(prettifier, 0, UnquotedString(message), UnquotedString(fileName + ":" + lineNumber)))
    FailureMessages.allShorthandFailed(prettifier, messageWithIndex, left)
  }

  val nonEmptyList = List(1, 2, 3)
  val emptyList = List.empty[Int]

  describe("Sorted matcher") {

    describe("when work with 'list should be (empty)'") {

      it("should do nothing when list is empty") {

        emptyList should (be (empty) or be (emptyList))
        nonEmptyList should (be (empty) or be (nonEmptyList))
        emptyList should (be (empty) or be (nonEmptyList))

        emptyList should (be (emptyList) or be (empty))
        emptyList should (be (nonEmptyList) or be (empty))
        nonEmptyList should (be (nonEmptyList) or be (empty))

        emptyList should (be (empty) or equal (emptyList))
        nonEmptyList should (be (empty) or equal (nonEmptyList))
        emptyList should (be (empty) or equal (nonEmptyList))

        emptyList should (equal (emptyList) or be (empty))
        emptyList should (equal (nonEmptyList) or be (empty))
        nonEmptyList should (equal (nonEmptyList) or be (empty))
      }

      it("should throw TestFailedException with correct stack depth when file is not empty") {
        val caught1 = intercept[TestFailedException] {
          nonEmptyList should (be (empty) or be (emptyList))
        }
        assert(caught1.message === Some(wasNotEmpty(nonEmptyList) + ", and " + wasNotEqualTo(nonEmptyList, emptyList)))
        assert(caught1.failedCodeFileName === Some(fileName))
        assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))

        val caught2 = intercept[TestFailedException] {
          nonEmptyList should (be (emptyList) or be (empty))
        }
        assert(caught2.message === Some(wasNotEqualTo(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList)))
        assert(caught2.failedCodeFileName === Some(fileName))
        assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))

        val caught3 = intercept[TestFailedException] {
          nonEmptyList should (be (empty) or equal (emptyList))
        }
        assert(caught3.message === Some(wasNotEmpty(nonEmptyList) + ", and " + didNotEqual(nonEmptyList, emptyList)))
        assert(caught3.failedCodeFileName === Some(fileName))
        assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))

        val caught4 = intercept[TestFailedException] {
          nonEmptyList should (equal (emptyList) or be (empty))
        }
        assert(caught4.message === Some(didNotEqual(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList)))
        assert(caught4.failedCodeFileName === Some(fileName))
        assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
      }
    }

    describe("when work with 'file should not be empty'") {

      it("should do nothing when file is not empty") {
        nonEmptyList should (not be empty or not be emptyList)
        emptyList should (not be empty or not be nonEmptyList)
        nonEmptyList should (not be empty or not be nonEmptyList)

        nonEmptyList should (not be emptyList or not be empty)
        nonEmptyList should (not be nonEmptyList or not be empty)
        emptyList should (not be nonEmptyList or not be empty)

        nonEmptyList should (not be empty or not equal emptyList)
        emptyList should (not be empty or not equal nonEmptyList)
        nonEmptyList should (not be empty or not equal nonEmptyList)

        nonEmptyList should (not equal emptyList or not be empty)
        nonEmptyList should (not equal nonEmptyList or not be empty)
        emptyList should (not equal nonEmptyList or not be empty)
      }

      it("should throw TestFailedException with correct stack depth when file is empty") {
        val caught1 = intercept[TestFailedException] {
          emptyList should (not be empty or not be emptyList)
        }
        assert(caught1.message === Some(wasEmpty(emptyList) + ", and " + wasEqualTo(emptyList, emptyList)))
        assert(caught1.failedCodeFileName === Some(fileName))
        assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))

        val caught2 = intercept[TestFailedException] {
          emptyList should (not be emptyList or not be empty)
        }
        assert(caught2.message === Some(wasEqualTo(emptyList, emptyList) + ", and " + wasEmpty(emptyList)))
        assert(caught2.failedCodeFileName === Some(fileName))
        assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))

        val caught3 = intercept[TestFailedException] {
          emptyList should (not be empty or not equal emptyList)
        }
        assert(caught3.message === Some(wasEmpty(emptyList) + ", and " + equaled(emptyList, emptyList)))
        assert(caught3.failedCodeFileName === Some(fileName))
        assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))

        val caught4 = intercept[TestFailedException] {
          emptyList should (not equal emptyList or not be empty)
        }
        assert(caught4.message === Some(equaled(emptyList, emptyList) + ", and " + wasEmpty(emptyList)))
        assert(caught4.failedCodeFileName === Some(fileName))
        assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
      }
    }

    describe("when work with 'all(xs) should be (empty)'") {

      it("should do nothing when all(xs) is empty") {
        all(List(emptyList)) should (be (empty) or be (emptyList))
        all(List(nonEmptyList)) should (be (empty) or be (nonEmptyList))
        all(List(emptyList)) should (be (empty) or be (nonEmptyList))

        all(List(emptyList)) should (be (emptyList) or be (empty))
        all(List(emptyList)) should (be (nonEmptyList) or be (empty))
        all(List(nonEmptyList)) should (be (nonEmptyList) or be (empty))

        all(List(emptyList)) should (be (empty) or equal (emptyList))
        all(List(nonEmptyList)) should (be (empty) or equal (nonEmptyList))
        all(List(emptyList)) should (be (empty) or equal (nonEmptyList))

        all(List(emptyList)) should (equal (emptyList) or be (empty))
        all(List(emptyList)) should (equal (nonEmptyList) or be (empty))
        all(List(nonEmptyList)) should (equal (nonEmptyList) or be (empty))
      }

      it("should throw TestFailedException with correct stack depth when xs is not sorted") {
        val left1 = List(nonEmptyList)
        val caught1 = intercept[TestFailedException] {
          all(left1) should (be (emptyList) or be (empty))
        }
        assert(caught1.message === Some(allError(wasNotEqualTo(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList), thisLineNumber - 2, left1)))
        assert(caught1.failedCodeFileName === Some(fileName))
        assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))

        val left2 = List(nonEmptyList)
        val caught2 = intercept[TestFailedException] {
          all(left2) should (be (empty) or be (emptyList))
        }
        assert(caught2.message === Some(allError(wasNotEmpty(nonEmptyList) + ", and " + wasNotEqualTo(nonEmptyList, emptyList), thisLineNumber - 2, left2)))
        assert(caught2.failedCodeFileName === Some(fileName))
        assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))

        val left3 = List(nonEmptyList)
        val caught3 = intercept[TestFailedException] {
          all(left3) should (equal (emptyList) or be (empty))
        }
        assert(caught3.message === Some(allError(didNotEqual(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList), thisLineNumber - 2, left3)))
        assert(caught3.failedCodeFileName === Some(fileName))
        assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))

        val left4 = List(nonEmptyList)
        val caught4 = intercept[TestFailedException] {
          all(left4) should (be (empty) or equal (emptyList))
        }
        assert(caught4.message === Some(allError(wasNotEmpty(nonEmptyList) + ", and " + didNotEqual(nonEmptyList, emptyList), thisLineNumber - 2, left4)))
        assert(caught4.failedCodeFileName === Some(fileName))
        assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
      }
    }

    describe("when work with 'all(xs) should not be sorted'") {
      it("should do nothing when xs is not sorted") {
        all(List(nonEmptyList)) should (not be empty or not be emptyList)
        all(List(emptyList)) should (not be empty or not be nonEmptyList)
        all(List(nonEmptyList)) should (not be empty or not be nonEmptyList)

        all(List(nonEmptyList)) should (not be emptyList or not be empty)
        all(List(nonEmptyList)) should (not be nonEmptyList or not be empty)
        all(List(emptyList)) should (not be nonEmptyList or not be empty)

        all(List(nonEmptyList)) should (not be empty or not equal emptyList)
        all(List(emptyList)) should (not be empty or not equal nonEmptyList)
        all(List(nonEmptyList)) should (not be empty or not equal nonEmptyList)

        all(List(nonEmptyList)) should (not equal emptyList or not be empty)
        all(List(nonEmptyList)) should (not equal nonEmptyList or not be empty)
        all(List(emptyList)) should (not equal nonEmptyList or not be empty)
      }

      it("should throw TestFailedException with correct stack depth when xs is not sorted") {
        val left1 = List(emptyList)
        val caught1 = intercept[TestFailedException] {
          all(left1) should (not be emptyList or not be empty)
        }
        assert(caught1.message === Some(allError(wasEqualTo(emptyList, emptyList) + ", and " + wasEmpty(emptyList), thisLineNumber - 2, left1)))
        assert(caught1.failedCodeFileName === Some(fileName))
        assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))

        val left2 = List(emptyList)
        val caught2 = intercept[TestFailedException] {
          all(left2) should (not be empty or not be emptyList)
        }
        assert(caught2.message === Some(allError(wasEmpty(emptyList) + ", and " + wasEqualTo(emptyList, emptyList), thisLineNumber - 2, left2)))
        assert(caught2.failedCodeFileName === Some(fileName))
        assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))

        val left3 = List(emptyList)
        val caught3 = intercept[TestFailedException] {
          all(left3) should (not equal emptyList or not be empty)
        }
        assert(caught3.message === Some(allError(equaled(emptyList, emptyList) + ", and " + wasEmpty(emptyList), thisLineNumber - 2, left3)))
        assert(caught3.failedCodeFileName === Some(fileName))
        assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))

        val left4 = List(emptyList)
        val caught4 = intercept[TestFailedException] {
          all(left4) should (not be empty or not equal emptyList)
        }
        assert(caught4.message === Some(allError(wasEmpty(emptyList) + ", and " + equaled(emptyList, emptyList), thisLineNumber - 2, left4)))
        assert(caught4.failedCodeFileName === Some(fileName))
        assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
      }
    }
  }
}


text:
/**
 * pics.js
 *
 * The file that handles the pics section of the site.
 */
window.AdamElliot = window.AdamElliot || {};

AdamElliot.Pics = (function() {
  var FLICKR_PATH = "http://api.flickr.com/services/feeds/photos_public.gne?id=30782515@N02&format=json&jsoncallback=?";
  var FRAME_RATE = 20;
  var FRAME_DELAY = Math.floor(FRAME_RATE * 5.6);
  var SIZE = 180;

  var Picture = function(path) {
    var self = this;
    CanvasObject.Path.call(this);

    var SUB_SIZE = [20, 30, 36, 45][Math.floor(Math.random() * 4)];
    var SUB_SIZE_2 = SUB_SIZE / 2;
    var COLS = (SIZE / SUB_SIZE);
    var SECTIONS = COLS * COLS;
    var PIXEL_BORDER = 6;
    var MAX_SCALES = 1 + Math.round(SECTIONS / 5);
    var SCALE_FRAME_OFFSET = 1;
    var DURATION = 2.7;

    var offsetX = 0, offsetY = 0;
    var bitmap;

    var scaleStep = (SECTIONS / (MAX_SCALES >> 1)) / DURATION / FRAME_RATE;
    var sectionScale = [];
    for (var i = 0; i < SECTIONS; i++) sectionScale[i] = 0;

    var startTargetIndex = 0, endTargetIndex = 0;
    var order = [];
    for (var i = 0; i < SECTIONS; i++) order[i] = i;
    order.sort(function() { return Math.random() - 0.5; });

    this.fillStyle = 'black';

    this.defineHook('finshedDisplay');

    var scaleSection = function(index) {
      if (sectionScale[index] >= 1.0)
        return false;
      sectionScale[index] += scaleStep;
      if (sectionScale[index] > 1.0) sectionScale[index] = 1.0;

      var s = SUB_SIZE * sectionScale[index], s_2 = s / 2;
      var x = (index % COLS) * SUB_SIZE + (SUB_SIZE_2 - s_2);
      var y = Math.floor(index / COLS) * SUB_SIZE + (SUB_SIZE_2 - s_2);

      var s_x = x + offsetX, s_y = y + offsetY;
      var clampX = 0, clampY = 0;

      if (s_x + s > bitmap.width())   clampX = (s_x + s) - bitmap.width();
      if (s_y + s > bitmap.height())  clampY = (s_y + s) - bitmap.height();

      var ds = Math.min(SUB_SIZE, s + PIXEL_BORDER);
      var bp = (ds - s) / 2;

      self.fillRectAt((index << 1) + 1, x - bp, y - bp, ds, ds);
      self.drawImageAt((index << 1) + 2, bitmap.canvas(), x + offsetX, y + offsetY, s - clampX, s - clampY, x, y, s, s);

      return true;
    };

    CanvasObject.Bitmap.withImage(path, function(_bitmap) {
      bitmap = _bitmap;

      if (bitmap.width() > SIZE)  offsetX = (bitmap.width() - SIZE) / 2;
      if (bitmap.height() > SIZE) offsetY = (bitmap.height() - SIZE) / 2;

      var func, count = 0;
      var fade = 0.0;
      self.enterFrame(func = function() {
        fade += 0.005;
        self.fillStyle = 'rgba(0,0,0,' + fade + ')';
        self.fillRectAt(0, 0, 0, SIZE, SIZE);

        var moveForward = !scaleSection(order[startTargetIndex]);
        for (var i = startTargetIndex + 1; i < endTargetIndex; i++)
          scaleSection(order[i]);

        if (moveForward) {
          startTargetIndex++;
          endTargetIndex++;
          endTargetIndex = Math.min(endTargetIndex, SECTIONS - 1);
        }

        if (count++ % SCALE_FRAME_OFFSET == 0 &&
          (endTargetIndex - startTargetIndex) < MAX_SCALES) {
          endTargetIndex++;
          endTargetIndex = Math.min(endTargetIndex, SECTIONS - 1);
        }

        if (startTargetIndex >= SECTIONS) {
          self.removeHandler('enterFrame', func);
          self.trigger('finshedDisplay');
        }
      });
    });
  };

  var Klass = function(_frame) {
    var self = this;
    var frame = _frame, buttons;
    var canvas = frame.getFrame().find("canvas");
    CanvasObject.Stage.call(this, canvas[0], FRAME_RATE);

    var images, imageIndex = 0;
    var pictures = [], pictureIndex = 0;
    var frameDelay = FRAME_DELAY;
    var order = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    order.sort(function() { return Math.random() - 0.5; });

    this.resize(550, 550);
    this.setUpdateMethod(false, false);

    canvas.click(function(event) {
      var x = Math.floor(event.offsetX / 184);
      var y = Math.floor(event.offsetY / 184);
      var index = x + y * 3;

      if (pictures[order.indexOf(index)])
        window.open(pictures[order.indexOf(index)].url, "_blank");
    });

    var addPicture = function() {
      if (pictures[pictureIndex]) self.removeChild(pictures[pictureIndex]);

      var picture = new Picture(images[imageIndex].media.m);
      picture.url = images[imageIndex].link;
      self.addChild(picture);

      imageIndex++;

      var index = order[pictureIndex];

      picture.x = (index % 3) * (SIZE + 5);
      picture.y = Math.floor(index / 3) * (SIZE + 5);

      pictures[pictureIndex++] = picture;

      picture.finshedDisplay(function() {
        self.removeChild(picture);
      });

      pictureIndex %= 9;
      imageIndex %= images.length;
    };

    var initialize = function() {
      if (!frame) return;

      $.getJSON(FLICKR_PATH, function(data) {
        images = data.items;
        images.sort(function() { return Math.random() - 0.5; });

        var initialPics = 9, i = 0;
        var func;
        self.enterFrame(func = function() {
          if ((i++ % FRAME_RATE) === 0) {
            addPicture();
            if (--initialPics <= 0) this.removeHandler('enterFrame', func);
          }
        });

        self.enterFrame(function() {
          if (frameDelay === 0) {
            addPicture();
            frameDelay = FRAME_DELAY;
          }
          frameDelay--;
        });
      });
    };

    this.clearFunc = function() {
      self.context().fillStyle = 'rgba(0, 0, 0, 0.02)';
      self.context().fillRect(0, 0, 550, 550);
    };

    initialize.call(this);
  };

  return Klass;
})();