text:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.util.Vector;

public class WinGammaPlatformVC7 extends WinGammaPlatform {

   // TODO How about moving all globals configs to its own BuildConfig?

   String projectVersion() {
      return "7.10";
   };

   public void writeProjectFile(String projectFileName, String projectName,
         Vector<BuildConfig> allConfigs) throws IOException {
      System.out.println();
      System.out.println("    Writing .vcproj file: " + projectFileName);
      // If we got this far without an error, we're safe to actually
      // write the .vcproj file
      printWriter = new PrintWriter(new FileWriter(projectFileName));

      printWriter
      .println("<?xml version=\"1.0\" encoding=\"windows-1251\"?>");
      startTag("VisualStudioProject", new String[] { "ProjectType",
            "Visual C++", "Version", projectVersion(), "Name", projectName,
            "ProjectGUID", "{8822CB5C-1C41-41C2-8493-9F6E1994338B}",
            "SccProjectName", "", "SccLocalPath", "" });
      startTag("Platforms");
      tag("Platform",
            new String[] { "Name",
            (String) BuildConfig.getField(null, "PlatformName") });
      endTag();

      startTag("Configurations");

      for (BuildConfig cfg : allConfigs) {
         writeConfiguration(cfg);
      }

      endTag();

      tag("References");

      writeFiles(allConfigs);

      tag("Globals");

      endTag();
      printWriter.close();

      System.out.println("    Done.");
   }

   void writeCustomToolConfig(Vector<BuildConfig> configs, String[] customToolAttrs) {
      for (BuildConfig cfg : configs) {
         startTag("FileConfiguration",
               new String[] { "Name", (String) cfg.get("Name") });
         tag("Tool", customToolAttrs);

         endTag();
      }
   }

   void writeFiles(Vector<BuildConfig> allConfigs) {

      // This code assummes there are no config specific includes.
      startTag("Files");
      String sourceBase = BuildConfig.getFieldString(null, "SourceBase");

      // Use first config for all global absolute includes.
      BuildConfig baseConfig = allConfigs.firstElement();
      Vector<String> rv = new Vector<String>();

      // Then use first config for all relative includes
      Vector<String> ri = new Vector<String>();
      baseConfig.collectRelevantVectors(ri, "RelativeSrcInclude");
      for (String f : ri) {
         rv.add(sourceBase + Util.sep + f);
      }

      baseConfig.collectRelevantVectors(rv, "AbsoluteSrcInclude");

      handleIncludes(rv, allConfigs);

      startTag("Filter", new String[] { "Name", "Resource Files", "Filter",
      "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe" });
      endTag();

      endTag();
   }

   // Will visit file tree for each include
   private void handleIncludes(Vector<String> includes, Vector<BuildConfig> allConfigs) {
      for (String path : includes)  {
         FileTreeCreatorVC7 ftc = new FileTreeCreatorVC7(FileSystems.getDefault().getPath(path) , allConfigs, this);
         try {
            ftc.writeFileTree();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }

   void writeConfiguration(BuildConfig cfg) {
      startTag("Configuration", new String[] { "Name", cfg.get("Name"),
            "OutputDirectory", cfg.get("OutputDir"),
            "IntermediateDirectory", cfg.get("OutputDir"),
            "ConfigurationType", "2", "UseOfMFC", "0",
            "ATLMinimizesCRunTimeLibraryUsage", "FALSE" });

      tagV("Tool", cfg.getV("CompilerFlags"));

      tag("Tool", new String[] { "Name", "VCCustomBuildTool" });

      tagV("Tool", cfg.getV("LinkerFlags"));

      String postBuildCmd = BuildConfig.getFieldString(null,
            "PostbuildCommand");
      if (postBuildCmd != null) {
         tag("Tool",
               new String[] {
               "Name",
               "VCPostBuildEventTool",
               "Description",
               BuildConfig
               .getFieldString(null, "PostbuildDescription"),
               // Caution: String.replace(String,String) is available
               // from JDK5 onwards only
               "CommandLine",
                   cfg.expandFormat(postBuildCmd.replace("\t",
                           "
")) });
      }

      tag("Tool", new String[] { "Name", "VCPreBuildEventTool" });

      tag("Tool",
            new String[] {
            "Name",
            "VCPreLinkEventTool",
            "Description",
            BuildConfig.getFieldString(null, "PrelinkDescription"),
            // Caution: String.replace(String,String) is available
            // from JDK5 onwards only
            "CommandLine",
            cfg.expandFormat(BuildConfig.getFieldString(null,
                  "PrelinkCommand").replace("\t", "
")) });

      tag("Tool", new String[] { "Name", "VCResourceCompilerTool",
            "PreprocessorDefinitions", "NDEBUG", "Culture", "1033" });

      tag("Tool", new String[] { "Name", "VCMIDLTool",
            "PreprocessorDefinitions", "NDEBUG", "MkTypLibCompatible",
            "TRUE", "SuppressStartupBanner", "TRUE", "TargetEnvironment",
            "1", "TypeLibraryName",
            cfg.get("OutputDir") + Util.sep + "vm.tlb", "HeaderFileName",
      "" });

      endTag();
   }

   protected String getProjectExt() {
      return ".vcproj";
   }
}

class CompilerInterfaceVC7 extends CompilerInterface {
   void getBaseCompilerFlags_common(Vector defines, Vector includes,
         String outDir, Vector rv) {

      // advanced M$ IDE (2003) can only recognize name if it's first or
      // second attribute in the tag - go guess
      addAttr(rv, "Name", "VCCLCompilerTool");
      addAttr(rv, "AdditionalIncludeDirectories", Util.join(",", includes));
      addAttr(rv, "PreprocessorDefinitions",
            Util.join(";", defines).replace("\"", """));
      addAttr(rv, "PrecompiledHeaderThrough", "precompiled.hpp");
      addAttr(rv, "PrecompiledHeaderFile", outDir + Util.sep + "vm.pch");
      addAttr(rv, "AssemblerListingLocation", outDir);
      addAttr(rv, "ObjectFile", outDir + Util.sep);
      addAttr(rv, "ProgramDataBaseFileName", outDir + Util.sep + "jvm.pdb");
      // Set /nologo optin
      addAttr(rv, "SuppressStartupBanner", "TRUE");
      // Surpass the default /Tc or /Tp. 0 is compileAsDefault
      addAttr(rv, "CompileAs", "0");
      // Set /W3 option. 3 is warningLevel_3
      addAttr(rv, "WarningLevel", "3");
      // Set /WX option,
      addAttr(rv, "WarnAsError", "TRUE");
      // Set /GS option
      addAttr(rv, "BufferSecurityCheck", "FALSE");
      // Set /Zi option. 3 is debugEnabled
      addAttr(rv, "DebugInformationFormat", "3");
   }

   Vector getBaseCompilerFlags(Vector defines, Vector includes, String outDir) {
      Vector rv = new Vector();

      getBaseCompilerFlags_common(defines, includes, outDir, rv);
      // Set /Yu option. 3 is pchUseUsingSpecific
      // Note: Starting VC8 pchUseUsingSpecific is 2 !!!
      addAttr(rv, "UsePrecompiledHeader", "3");
      // Set /EHsc- option
      addAttr(rv, "ExceptionHandling", "FALSE");

      return rv;
   }

   Vector getBaseLinkerFlags(String outDir, String outDll, String platformName) {
      Vector rv = new Vector();

      addAttr(rv, "Name", "VCLinkerTool");
      addAttr(rv, "AdditionalOptions",
            "/export:JNI_GetDefaultJavaVMInitArgs "
                  + "/export:JNI_CreateJavaVM "
                  + "/export:JVM_FindClassFromBootLoader "
                  + "/export:JNI_GetCreatedJavaVMs "
                  + "/export:jio_snprintf /export:jio_printf "
                  + "/export:jio_fprintf /export:jio_vfprintf "
                  + "/export:jio_vsnprintf "
                  + "/export:JVM_GetVersionInfo "
                  + "/export:JVM_GetThreadStateNames "
                  + "/export:JVM_GetThreadStateValues "
                  + "/export:JVM_InitAgentProperties ");
      addAttr(rv, "AdditionalDependencies", "Wsock32.lib winmm.lib");
      addAttr(rv, "OutputFile", outDll);
      // Set /INCREMENTAL option. 1 is linkIncrementalNo
      addAttr(rv, "LinkIncremental", "1");
      addAttr(rv, "SuppressStartupBanner", "TRUE");
      addAttr(rv, "ModuleDefinitionFile", outDir + Util.sep + "vm.def");
      addAttr(rv, "ProgramDatabaseFile", outDir + Util.sep + "jvm.pdb");
      // Set /SUBSYSTEM option. 2 is subSystemWindows
      addAttr(rv, "SubSystem", "2");
      addAttr(rv, "BaseAddress", "0x8000000");
      addAttr(rv, "ImportLibrary", outDir + Util.sep + "jvm.lib");
      if (platformName.equals("Win32")) {
         // Set /MACHINE option. 1 is X86
         addAttr(rv, "TargetMachine", "1");
      } else {
         // Set /MACHINE option. 17 is X64
         addAttr(rv, "TargetMachine", "17");
      }

      return rv;
   }

   void getDebugCompilerFlags_common(String opt, Vector rv) {

      // Set /On option
      addAttr(rv, "Optimization", opt);
      // Set /FR option. 1 is brAllInfo
      addAttr(rv, "BrowseInformation", "1");
      addAttr(rv, "BrowseInformationFile", "$(IntDir)" + Util.sep);
      // Set /MD option. 2 is rtMultiThreadedDLL
      addAttr(rv, "RuntimeLibrary", "2");
      // Set /Oy- option
      addAttr(rv, "OmitFramePointers", "FALSE");

   }

   Vector getDebugCompilerFlags(String opt) {
      Vector rv = new Vector();

      getDebugCompilerFlags_common(opt, rv);

      return rv;
   }

   Vector getDebugLinkerFlags() {
      Vector rv = new Vector();

      addAttr(rv, "GenerateDebugInformation", "TRUE"); // == /DEBUG option

      return rv;
   }

   void getAdditionalNonKernelLinkerFlags(Vector rv) {
      extAttr(rv, "AdditionalOptions", "/export:AsyncGetCallTrace ");
   }

   void getProductCompilerFlags_common(Vector rv) {
      // Set /O2 option. 2 is optimizeMaxSpeed
      addAttr(rv, "Optimization", "2");
      // Set /Oy- option
      addAttr(rv, "OmitFramePointers", "FALSE");
      // Set /Ob option. 1 is expandOnlyInline
      addAttr(rv, "InlineFunctionExpansion", "1");
      // Set /GF option.
      addAttr(rv, "StringPooling", "TRUE");
      // Set /MD option. 2 is rtMultiThreadedDLL
      addAttr(rv, "RuntimeLibrary", "2");
      // Set /Gy option
      addAttr(rv, "EnableFunctionLevelLinking", "TRUE");
   }

   Vector getProductCompilerFlags() {
      Vector rv = new Vector();

      getProductCompilerFlags_common(rv);

      return rv;
   }

   Vector getProductLinkerFlags() {
      Vector rv = new Vector();

      // Set /OPT:REF option. 2 is optReferences
      addAttr(rv, "OptimizeReferences", "2");
      // Set /OPT:optFolding option. 2 is optFolding
      addAttr(rv, "EnableCOMDATFolding", "2");

      return rv;
   }

   String getOptFlag() {
      return "2";
   }

   String getNoOptFlag() {
      return "0";
   }

   String makeCfgName(String flavourBuild, String platform) {
      return flavourBuild + "|" + platform;
   }

}


text:
using System.Collections.Generic;
using System.Web.Http.Description;

namespace ApiAuthor
{
    public class ResourceGrouping
    {
        public string Name { get; set; }
        public string Remarks { get; set; }
        public IList<ApiDescription> ApiDescriptions { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
define ('ROOT', dirname(__DIR__));
define ('ROOT_APP', ROOT . '/src');

require_once(ROOT . '/vendor/autoload.php');

// Set up dependencies

$di = require_once(ROOT_APP . '/dependencies.php');

return $di;


text:
namespace SIM.Pipelines.Agent
{
  public static class PublishAgentFiles
  {
    #region Publish

    public const string PublishContents = @"
<%@ Page Language=""C#"" AutoEventWireup=""true"" %>
<%@ Import Namespace=""System.IO"" %>
<%@ Import Namespace=""Sitecore"" %>
<%@ Import Namespace=""Sitecore.Configuration"" %>
<%@ Import Namespace=""Sitecore.Data.Engines"" %>
<%@ Import Namespace=""Sitecore.Data.Proxies"" %>
<%@ Import Namespace=""Sitecore.Diagnostics"" %>
<%@ Import Namespace=""Sitecore.Globalization"" %>
<%@ Import Namespace=""Sitecore.Publishing"" %>
<%@ Import Namespace=""Sitecore.SecurityModel"" %>
<%@ Import Namespace=""Sitecore.Security.Accounts"" %>

<script runat=""server"">

#region Methods

  protected override void OnInitComplete(EventArgs e)
  {
    try
    {
      Sitecore.Context.SetActiveSite(""shell"");
      using (new UserSwitcher(""sitecore\\admin"", true))
      {
        using (new ProxyDisabler())
        {
          using (new SyncOperationContext())
          {
            var language = Language.Parse(EmptyToNull(this.Request.QueryString[""lang""]) ?? EmptyToNull(this.Request.QueryString[""language""]) ?? ""en"");
            var languages = new [] { language };
            var target = Factory.GetDatabase(EmptyToNull(this.Request.QueryString[""target""]) ?? ""web"");
            var source = Factory.GetDatabase(EmptyToNull(this.Request.QueryString[""source""]) ?? ""master"");
            var targets = new [] { target };
            var id = PublishManager.PublishSmart(source, targets, languages);
            this.UpdateStatus(@""Started: publish "" + id);
          }
        }
      }
    }
    catch (Exception ex)
    {
      var inn = string.Empty;
      if (ex.InnerException != null)
      {
        inn = ""\n\nInner Exception:\n"" + ex.InnerException;
      }

      this.Finish(@""Error: "" + ex + inn);
    }
  }

  private void Finish(string message)
  {
    Log.Info(@""[SIM] " + PublishAgentFiles.PublishFileName + @": "" + message, this);
    this.UpdateStatus(message);
    this.Response.Write(message);
  }

  private void UpdateStatus(string message)
  {
    var installedTemp = this.Server.MapPath(Path.Combine(Settings.TempFolderPath, ""sim.status""));
    File.WriteAllText(installedTemp, message);
  }

  private string GetFilePath(string name)
  {
    Assert.ArgumentNotNullOrEmpty(name, ""name"");

    var packageFolderPath = Sitecore.Configuration.Settings.PackagePath;
    Assert.IsNotNullOrEmpty(packageFolderPath, ""packageFolderPath"");

    // if path is virtual i.e. not C:\something then do a map path
    if (packageFolderPath.Length < 2 || packageFolderPath[1] != ':')
    {
      packageFolderPath = packageFolderPath.TrimStart('/');
      var prefix = ""~/"";
      if (packageFolderPath.StartsWith(prefix))
      {
        packageFolderPath = packageFolderPath.Substring(prefix.Length);
      }

      packageFolderPath = Server.MapPath(prefix + packageFolderPath);
    }

    return Path.Combine(packageFolderPath, name);
  }

  private string EmptyToNull(string str)
  {
    return string.IsNullOrEmpty(str) ? null : str;
  }

#endregion

</script>";
    public const string PublishFileName = @"Publish.aspx";

    #endregion

    #region Status

    public const string StatusContents = @"<%@ Page Language=""C#"" AutoEventWireup=""true"" %>
<%@ Import Namespace=""System.IO"" %>
<%@ Import Namespace=""Sitecore"" %>
<%@ Import Namespace=""Sitecore.Configuration"" %>
<%@ Import Namespace=""Sitecore.Diagnostics"" %>
<%@ Import Namespace=""Sitecore.Publishing"" %>
<%@ Import Namespace=""Sitecore.Jobs"" %>
<script runat=""server"">

#region Methods

  protected override void OnInitComplete(EventArgs e)
  {
    var installedTemp = this.Server.MapPath(Path.Combine(Settings.TempFolderPath, ""sim.status""));
    var message = GetMessage(installedTemp);

    Log.Info(@""[SIM] " + AgentFiles.StatusFileName + @": "" + message, this);
    this.Response.Write(message);
  }

  private string GetMessage(string installedTemp)
  {
    if (File.Exists(installedTemp))
    {
      var message = File.ReadAllText(installedTemp);
      var pos = message.LastIndexOf(' ');
      if(pos<0) throw new Exception(""CANT BE"");
      var id = message.Substring(pos).Trim();
      var state = PublishManager.GetStatus(Handle.Parse(id));
      message = GetState(state) + "": publish "" + id;
      return message;
    }
    else
    {
      return @""Pending: no information"";
    }
  }

  private string GetState(PublishStatus state)
  {
    if (state == null)
    {
      return ""Completed""; // needs adjusting
    }

    if (state.IsDone)
    {
      return ""Completed"";
    }

    if (state.Failed)
    {
      return ""Failed"";
    }

    if (state.State == JobState.Running)
    {
      return ""Running"";
    }

    if (state.State == JobState.Initializing)
    {
      return ""Initializing"";
    }

    if (state.State == JobState.Queued)
    {
      return ""Queued"";
    }

    return ""Unknown"";
  }

#endregion

</script>";
    public const string StatusFileName = @"Status.aspx";

    #endregion
  }
}


text:
layout: post
pretitle: Bericht vom 11. Treffen am 24.01.2017
title: CSS Grid Layout + Webpack Tooling
author: Jan Deppisch
author_twitter: netzartist
published: true
---

Volles Haus, spannende Talks, Führung durch die historischen Räumlichkeiten des namics-Office in Frankfurt, lecker Catering und natürlich entspanntes Networking ... so kann man das 11. Treffen knapp zusammenfassen.

Herzlichen Dank an die Speaker [Bastian Heist](https://sandstorm.de/) und [Sebastian Werner](https://www.sebastian-software.de/) sowie Constantin von [Namics](https://www.namics.com/) für die unkomplizierte Organisation sowie das Sponsoring!

Hier sind die Slides:

Tolle volle Hütte bei @namics in Frankfurt! @swernerx startet mit interessantem Überblick über Webpack & Co. pic.twitter.com/ynQiMCawSE
— Frontend RheinMain (@frontend_rm) 24. Januar 2017

Danke @beheist, @swernerx  und euch Frankfurter Frontend Freaks für den langen Abend bei @Namics :-) #frontendrm #rheinmainrocks pic.twitter.com/b9T91nm6b9
— Frontend RheinMain (@frontend_rm) 25. Januar 2017


text:
// text wrapping for all svg nodes
function textwrap(element) {
	var texts = element.getElementsByTagName("text");
	var i=0;
	for (i=0;i<texts.length;i++	) {
		var width = texts[i].previousElementSibling.getAttribute("width");
		d3plus.textwrap()
				.container(d3.select(texts[i]))
				.width(width-20)
				.draw();
	}
};

function setRootPanelHeight() {
	$('.root-panel-body').css('height', $('.root-panel').outerHeight() - $('.root-panel-heading').outerHeight());
}

$(document).ready(function() {

    var style = location.search.split('style=')[1];

    if (style == 'tabbed') {
        $('#tabbed').show();
        $('#listed').hide();
        // Set heigh of panels the first time

	// Set jQuery UI Layout panes
	$('body').layout({
		minSize: 50,
		maskContents: true,
		north: {
		  size: 55,
		  spacing_open: 8,
		  closable: false,
		  resizable: false
		},
		west: {
				size: 350,
				spacing_open: 8
			},
		west__childOptions: {
		  maskContents: true,
		  south: {
			  minSize: 50,
					size: 250,
					spacing_open: 8
				},
				center: {
					minSize: 50,
					onresize: "setRootPanelHeight"
				}
		}
	   });

        setRootPanelHeight();
    }
	textwrap(document);

	$(".documentation").each(function() {
		$(this).html($(this).text());

	});

    if (style == 'listed') {
        $('#print').hide();
        $('#link').hide();
        $('#tabbed').hide();
        $('#listed').show();
        $('#panel').removeClass('panel');
        $('#panel').removeClass('panel-default');
        $('#panel').removeClass('root-panel');
        $('#panelheader').removeClass('panel-heading').addClass("well");
        $('#panelheader').removeClass('root-panel-heading');
        $('#panelbody').removeClass('panel-body');
        $('#panelbody').removeClass('root-panel-body');
    }

});


text:
#pragma once

#include <string>

#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/text_format.h"

#include "modules/perception/proto/rt.pb.h"

namespace apollo {
namespace perception {
namespace inference {
bool ReadProtoFromTextFile(const std::string &filename,
                           google::protobuf::Message *proto);
bool ReadProtoFromBinaryFile(const std::string &filename,
                             google::protobuf::Message *proto);
bool loadNetParams(const std::string &param_file, NetParameter *param);
std::string locateFile(const std::string &path, const std::string &input);

}  // namespace inference
}  // namespace perception
}  // namespace apollo


text:
def add_ability_to_pool(pool, ability):
    pool.append(ability)

def remove_ability_from_pool(pool, ability):
    pool.remove(ability)

def empty_pool(pool):
    pool.clear()

def pop_value_from_pool(pool):
    return pool.pop()

def get_random_ability_value(ability):
    return ability.dice.randomVal() + ability.modifier

def get_sum_of_random_values_from_pool(pool):
    result = 0
    while len(pool) > 0:
        ability = pop_value_from_pool(pool)
        result += get_random_ability_value(ability)

    return result


text:
@interface YCYNewVc ()

@end

@implementation YCYNewVc

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor yellowColor];

    [self setupNavBar];
}

#pragma mark - 设置导航条
- (void)setupNavBar {

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"MainTagSubIcon"] highImage:[UIImage imageNamed:@"MainTagSubIconClick"] target:self action:@selector(tagClick)];

    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];
}

- (void)tagClick {

    YCYSubTagVc *subTag = [[YCYSubTagVc alloc] init];
    [self.navigationController pushViewController:subTag animated:YES];
}
@end


text:
import csv
from artefact.utils import memoize

class SchemaDataMismatchError(Exception):
    pass

class Report(object):

    DELIMITER = ','
    QUOTECHAR = '"'

    def __init__(self, report_data, schema, client_customer_id=None, **kwargs):
        self.__report_data = report_data
        self.__reader = None
        self.__schema = schema
        self.__headers = []
        self.__utf8 = False
        self._client_customer_id = client_customer_id

        self.__check_data_integrity()

    @property
    def client_customer_id(self):
        return self._client_customer_id

    @property
    def schema(self):
        return self.__schema

    @property
    def headers(self):
        return self.__data_headers

    @property
    def rows(self):
        data = self.__data
        data.next()
        for line in data:
            yield line

    @property
    @memoize
    def length(self):
        return sum(1 for _ in self.rows)

    @property
    def __data(self):
        self.__report_data.seek(0)
        if self.__reader is None:
            self.__reader = csv.DictReader(self.__report_data, delimiter=self.DELIMITER, quotechar=self.QUOTECHAR)
        return self.__reader

    @property
    def __data_headers(self):
        return set(self.__data.fieldnames)

    def __check_data_integrity(self):
        '''
            The API expects the fields to be specified using the camelCase field name, but
            the returned report contains the "display name". This check ensures that
            we have the data we expect
        '''

        data_headers = self.__data_headers
        expected_headers = [field.display_name for field in self.__schema]

        if set(expected_headers) != set(data_headers):
            raise SchemaDataMismatchError(expected_headers, data_headers)


text:
package com.aweip.jsf.services;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import com.aweip.model.entityes.Car;

/**
 * The Class CarService.
 */
@ManagedBean(name = "carService")
@ApplicationScoped
public class CarService implements Serializable {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The Constant colors. */
	private final static String[] colors;

	/** The Constant brands. */
	private final static String[] brands;

	static {
		colors = new String[10];
		colors[0] = "Black";
		colors[1] = "White";
		colors[2] = "Green";
		colors[3] = "Red";
		colors[4] = "Blue";
		colors[5] = "Orange";
		colors[6] = "Silver";
		colors[7] = "Yellow";
		colors[8] = "Brown";
		colors[9] = "Maroon";

		brands = new String[10];
		brands[0] = "BMW";
		brands[1] = "Mercedes";
		brands[2] = "Volvo";
		brands[3] = "Audi";
		brands[4] = "Renault";
		brands[5] = "Fiat";
		brands[6] = "Volkswagen";
		brands[7] = "Honda";
		brands[8] = "Jaguar";
		brands[9] = "Ford";
	}

	/**
	 * Creates the cars.
	 *
	 * @param size
	 *            the size
	 * @return the list
	 */
	public List<Car> createCars(int size) {
		List<Car> list = new ArrayList<Car>();
		for (int i = 0; i < size; i++) {
			list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(),
					getRandomColor(), getRandomPrice(), getRandomSoldState()));
		}

		return list;
	}

	/**
	 * Gets the random id.
	 *
	 * @return the random id
	 */
	private String getRandomId() {
		return UUID.randomUUID().toString().substring(0, 8);
	}

	/**
	 * Gets the random year.
	 *
	 * @return the random year
	 */
	private int getRandomYear() {
		return (int) (Math.random() * 50 + 1960);
	}

	/**
	 * Gets the random color.
	 *
	 * @return the random color
	 */
	private String getRandomColor() {
		return colors[(int) (Math.random() * 10)];
	}

	/**
	 * Gets the random brand.
	 *
	 * @return the random brand
	 */
	private String getRandomBrand() {
		return brands[(int) (Math.random() * 10)];
	}

	/**
	 * Gets the random price.
	 *
	 * @return the random price
	 */
	public int getRandomPrice() {
		return (int) (Math.random() * 100000);
	}

	/**
	 * Gets the random sold state.
	 *
	 * @return the random sold state
	 */
	public boolean getRandomSoldState() {
		return (Math.random() > 0.5) ? true : false;
	}

	/**
	 * Gets the colors.
	 *
	 * @return the colors
	 */
	public List<String> getColors() {
		return Arrays.asList(colors);
	}

	/**
	 * Gets the brands.
	 *
	 * @return the brands
	 */
	public List<String> getBrands() {
		return Arrays.asList(brands);
	}
}


text:
import test_framework.loginit
# Test emergent consensus scenarios

import time
import random
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
from test_framework.util import *
from test_framework.blocktools import *
import test_framework.script as script
import pdb
import sys
if sys.version_info[0] < 3:
    raise "Use Python 3"
import logging

def mostly_sync_mempools(rpc_connections, difference=50, wait=1, verbose=1):
    """
    Wait until everybody has the most of the same transactions in their memory
    pools. There is no guarantee that mempools will ever sync due to the
    filterInventoryKnown bloom filter.
    """
    iterations = 0
    while True:
        iterations += 1
        pool = set(rpc_connections[0].getrawmempool())
        num_match = 1
        poolLen = [len(pool)]
        for i in range(1, len(rpc_connections)):
            tmp = set(rpc_connections[i].getrawmempool())
            if tmp == pool:
                num_match = num_match + 1
            if iterations > 10 and len(tmp.symmetric_difference(pool)) < difference:
                num_match = num_match + 1
            poolLen.append(len(tmp))
        if verbose:
            logging.info("sync mempool: " + str(poolLen))
        if num_match == len(rpc_connections):
            break
        time.sleep(wait)

class ExcessiveBlockTest (BitcoinTestFramework):
    def __init__(self, extended=False):
        self.extended = extended
        BitcoinTestFramework.__init__(self)

    def setup_network(self, split=False):
        self.nodes = []
        self.nodes.append(start_node(0, self.options.tmpdir, ["-debug=net", "-debug=graphene", "-usecashaddr=0", "-rpcservertimeout=0"], timewait=60 * 10))
        self.nodes.append(start_node(1, self.options.tmpdir, ["-debug=net", "-debug=graphene", "-usecashaddr=0", "-rpcservertimeout=0"], timewait=60 * 10))
        self.nodes.append(start_node(2, self.options.tmpdir, ["-debug=net", "-debug=graphene", "-usecashaddr=0", "-rpcservertimeout=0"], timewait=60 * 10))
        self.nodes.append(start_node(3, self.options.tmpdir, ["-debug=net", "-debug=graphene", "-usecashaddr=0", "-rpcservertimeout=0"], timewait=60 * 10))

        interconnect_nodes(self.nodes)
        self.is_network_split = False
        self.sync_all()

        if 0:  # getnewaddress can be painfully slow.  This bit of code can be used to during development to
               # create a wallet with lots of addresses, which then can be used in subsequent runs of the test.
               # It is left here for developers to manually enable.
            TEST_SIZE = 100  # TMP 00
            print("Creating addresses...")
            self.nodes[0].keypoolrefill(TEST_SIZE + 1)
            addrs = [self.nodes[0].getnewaddress() for _ in range(TEST_SIZE + 1)]
            with open("walletAddrs.json", "w") as f:
                f.write(str(addrs))
                pdb.set_trace()

    def run_test(self):
        BitcoinTestFramework.run_test(self)
        self.testCli()

        # clear out the mempool
        for n in self.nodes:
            while len(n.getrawmempool()):
                n.generate(1)
                sync_blocks(self.nodes)
        logging.info("cleared mempool: %s" % str([len(x) for x in [y.getrawmempool() for y in self.nodes]]))
        self.testExcessiveBlockSize()
        self.testExcessiveTx()

    def testCli(self):

        # Assumes the default excessive at 32MB and mining at 8MB
        try:
            self.nodes[0].setminingmaxblock(33000000)
        except JSONRPCException as e:
            pass
        else:
            assert(0)  # was able to set the mining size > the excessive size

        try:
            self.nodes[0].setminingmaxblock(99)
        except JSONRPCException as e:
            pass
        else:
            assert(0)  # was able to set the mining size below our arbitrary minimum

        try:
            self.nodes[0].setexcessiveblock(1000, 10)
        except JSONRPCException as e:
            pass
        else:
            assert(0)  # was able to set the excessive size < the mining size

    def sync_all(self):
        """Synchronizes blocks and mempools (mempools may never fully sync)"""
        if self.is_network_split:
            sync_blocks(self.nodes[:2])
            sync_blocks(self.nodes[2:])
            mostly_sync_mempools(self.nodes[:2])
            mostly_sync_mempools(self.nodes[2:])
        else:
            sync_blocks(self.nodes)
            mostly_sync_mempools(self.nodes)

    def createUtxos(self, node, addrs, amt):
        wallet = node.listunspent()
        wallet.sort(key=lambda x: x["amount"], reverse=True)

        # Create a LOT of UTXOs
        logging.info("Create lots of UTXOs...")
        n = 0
        group = min(100, amt)
        count = 0
        for w in wallet:
            count += group
            split_transaction(node, [w], addrs[n:group + n])
            n += group
            if n >= len(addrs):
                n = 0
            if count > amt:
                break
        logging.info("mine blocks")
        node.generate(1)  # mine all the created transactions
        logging.info("sync all blocks and mempools")
        self.sync_blocks()

    def expectHeights(self, blockHeights, waittime=10):
        loop = 0
        count = []
        while loop < waittime:
            counts = [x.getblockcount() for x in self.nodes]
            if counts == blockHeights:
                return True  # success!
            else:
                for (a,b) in zip(counts, blockHeights):
                    if counts > blockHeights:
                        assert("blockchain synced too far")
            time.sleep(.25)
            loop += .25
            if int(loop) == loop and (int(loop) % 10) == 0:
                logging.info("...waiting %f %s != %s" % (loop, counts, blockHeights))
        return False

    def generateTx(self, node, txBytes, addrs, data=None):
        wallet = node.listunspent()
        wallet.sort(key=lambda x: x["amount"], reverse=False)
        logging.info("Wallet length is %d" % len(wallet))

        size = 0
        count = 0
        decContext = decimal.getcontext().prec
        decimal.getcontext().prec = 8 + 8  # 8 digits to get to 21million, and each bitcoin is 100 million satoshis
        while size < txBytes:
            count += 1
            utxo = wallet.pop()
            outp = {}
            # Make the tx bigger by adding addtl outputs so it validates faster
            payamt = satoshi_round(utxo["amount"] / decimal.Decimal(8.0))
            for x in range(0, 8):
                # its test code, I don't care if rounding error is folded into the fee
                outp[addrs[(count + x) % len(addrs)]] = payamt
                #outscript = self.wastefulOutput(addrs[(count+x)%len(addrs)])
                #outscripthex = hexlify(outscript).decode("ascii")
                #outp[outscripthex] = payamt
            if data:
                outp["data"] = data
            txn = createrawtransaction([utxo], outp, createWastefulOutput)
            # txn2 = node.createrawtransaction([utxo], outp)
            signedtxn = node.signrawtransaction(txn)
            size += len(binascii.unhexlify(signedtxn["hex"]))
            node.sendrawtransaction(signedtxn["hex"])
        logging.info("%d tx %d length" % (count, size))
        decimal.getcontext().prec = decContext
        return (count, size)

    def testExcessiveTx(self):
        """This test checks the behavior of the nodes in the presence of excessively large transactions.
           It will set the accept depth to different values on each node, and then verify that each node
           Does not follow the excessive tip until the accept depth is exceeded.

           The test also validates the rejection of a > 100kb transaction in a > 1MB block, and again
           watches as each node eventually accepts the large tx based on accept depth.
        """
        TEST_SIZE = 20
        logging.info("Test excessive transactions")
        if 1:
            tips = self.nodes[0].getchaintips()

            self.nodes[0].set("net.excessiveAcceptDepth=0")
            self.nodes[1].set("net.excessiveAcceptDepth=1")
            self.nodes[2].set("net.excessiveAcceptDepth=2")
            self.nodes[3].set("net.excessiveAcceptDepth=3")

            self.nodes[0].set("net.excessiveBlock=2000000")
            self.nodes[1].set("net.excessiveBlock=2000000")
            self.nodes[2].set("net.excessiveBlock=2000000")
            self.nodes[3].set("net.excessiveBlock=2000000")

            logging.info("Cleaning up node state")
            for n in self.nodes:
                n.generate(10)
                self.sync_blocks()

            self.sync_all()
            # verify mempool is cleaned up on all nodes
            mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
            assert_equal(mbefore, [(0, 0)] * 4)

            if 1:
                logging.info("Creating addresses...")
                self.nodes[0].keypoolrefill(TEST_SIZE + 1)
                addrs = [self.nodes[0].getnewaddress() for _ in range(TEST_SIZE + 1)]
            else:  # enable if you are using a pre-created wallet, as described above
                logging.info("Loading addresses...")
                with open("wallet10kAddrs.json") as f:
                    addrs = json.load(f)

            if 1:  # Test not relaying a large transaction

                # Make the excessive transaction size smaller so its quicker to produce a excessive one
                self.nodes[0].set("net.excessiveTx=10000")
                self.nodes[1].set("net.excessiveTx=10000")
                self.nodes[2].set("net.excessiveTx=10000")
                self.nodes[3].set("net.excessiveTx=10000")
                self.nodes[0].setminingmaxblock(1000000)
                self.nodes[1].setminingmaxblock(1000000)
                self.nodes[2].setminingmaxblock(1000000)
                self.nodes[3].setminingmaxblock(1000000)

                wallet = self.nodes[0].listunspent()
                wallet.sort(key=lambda x: x["amount"], reverse=True)
                while len(wallet) < 500:
                    # Create a LOT of UTXOs
                    logging.info("Create lots of UTXOs...")
                    n = 0
                    group = min(100, TEST_SIZE)
                    count = 0
                    for w in wallet:
                        count += 1
                        split_transaction(self.nodes[0], [w], addrs[n:group + n])
                        n += group
                        if n >= len(addrs):
                            n = 0
                        if count > 50:  # We don't need any more
                            break
                    logging.info("mine blocks")
                    self.nodes[0].generate(5)  # mine all the created transactions
                    logging.info("sync all blocks and mempools")
                    self.sync_blocks()

                    wallet = self.nodes[0].listunspent()
                    wallet.sort(key=lambda x: x["amount"], reverse=True)

                logging.info("clean out the mempool")
                mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                while mbefore != [(0, 0)] * 4:
                    time.sleep(1)
                    self.nodes[0].generate(1)
                    time.sleep(10)
                    mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]

                # we need the mempool to be empty to track that this one tx doesn't prop
                assert_equal(mbefore, [(0, 0)] * 4)

                logging.info("Test not relaying a large transaction")

                (tx, vin, vout, txid) = split_transaction(self.nodes[0], wallet[0:500], [addrs[0]], txfeePer=60)
                logging.debug("Transaction Length is: ", len(binascii.unhexlify(tx)))
                assert(len(binascii.unhexlify(tx)) > 10000)  # txn has to be big for the test to work

                mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                assert_equal(mbefore[1:], [(0, 0), (0, 0), (0, 0)])  # verify that the transaction did not propagate
                assert(mbefore[0][0] > 0)  # verify that the transaction is in my node

                logging.info("allowing tx a chance to propagate - sleeping...")
                while len(self.nodes[0].getmempoolinfo()) < 1:
                    logging.info("sleeping 1")
                    time.sleep(1)

                logging.info("Test a large transaction in block < 1MB")
                largeBlock = self.nodes[0].generate(1)
                self.sync_blocks()
                counts = [x.getblockcount() for x in self.nodes]
                latest = counts[0]
                # Verify that all nodes accepted the block, even if some of them didn't
                # have the transaction.  They should all accept a <= 1MB block with a tx
                # <= 1MB
                assert_equal(counts, [latest, latest, latest, latest])

            # this test checks the behavior of > 1MB blocks with excessive
            # transactions.  it takes a LONG time to generate and propagate 1MB+ txs.
            if self.extended:

                logging.info("Creating addresses...")
                self.nodes[0].keypoolrefill(2000)
                addrs = [self.nodes[0].getnewaddress() for _ in range(2000)]
                # Create a LOT of UTXOs for the next test
                wallet = self.nodes[0].listunspent()
                wallet.sort(key=lambda x: x["amount"], reverse=True)
                wlen = len(wallet)
                while wlen < 8000:
                    logging.info("Create lots of UTXOs by 100...")
                    n = 0
                    for w in wallet:
                        split_transaction(self.nodes[0], [w], addrs[n:100 + n])
                        logging.info(str(wlen))
                        n += 100
                        if n >= len(addrs):
                            n = 0
                        wlen += 99
                        if wlen > 8000:
                            break

                    blk = self.nodes[0].generate(1)
                    blkinfo = self.nodes[0].getblock(blk[0])
                    logging.info("Generated block %d size: %d, num tx: %d" %
                                 (blkinfo["height"], blkinfo["size"], len(blkinfo["tx"])))
                    wallet = self.nodes[0].listunspent()
                    wallet.sort(key=lambda x: x["amount"], reverse=True)
                    wlen = len(wallet)

                self.nodes[0].generate(1)
                self.sync_blocks()

                logging.info("Building > 1MB block...")
                # Set the excessive transaction size larger for this node so we can
                # generate an "excessive" block for the other nodes
                self.nodes[0].set("net.excessiveTx=1000000")

                self.generateTx(self.nodes[0], 1000000, addrs)

                # Now generate a > 100kb transaction & mine it into a > 1MB block

                self.nodes[0].setminingmaxblock(2000000)
                self.nodes[0].set("net.excessiveBlock=2000000")

                wallet.sort(key=lambda x: x["amount"], reverse=True)
                (tx, vin, vout, txid) = split_transaction(self.nodes[0], wallet[0:2500], [addrs[0]], txfeePer=60)
                logging.debug("Transaction Length is: ", len(binascii.unhexlify(tx)))
                assert(len(binascii.unhexlify(tx)) > 100000)  # txn has to be big for the test to work

                origCounts = [x.getblockcount() for x in self.nodes]
                base = origCounts[0]
                mpool = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                logging.debug(str(mpool))
                largeBlock = self.nodes[0].generate(1)
                mpool = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                logging.debug(str(mpool))

                logging.info("Syncing node1")
                largeBlock2 = self.nodes[0].generate(1)
                sync_blocks(self.nodes[0:2])
                mpool = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                logging.debug(str(mpool))
                self.expectHeights([base + 2, base + 2, base, base], 30)

                logging.info("Syncing node2")
                largeBlock3 = self.nodes[0].generate(1)
                sync_blocks(self.nodes[0:3])
                self.expectHeights([base + 3, base + 3, base + 3, base], 30)

                logging.info("Syncing node3")
                largeBlock4 = self.nodes[0].generate(1)
                sync_blocks(self.nodes)
                self.expectHeights([base + 4, base + 4, base + 4, base + 4], 30)

            # Put it back to the default
            self.nodes[0].set("net.excessiveTx=1000000")
            self.nodes[1].set("net.excessiveTx=1000000")
            self.nodes[2].set("net.excessiveTx=1000000")
            self.nodes[3].set("net.excessiveTx=1000000")

    def repeatTx(self, count, node, addr, amt=1.0):
        for i in range(0, count):
            node.sendtoaddress(addr, amt)

    def generateAndPrintBlock(self, node):
        hsh = node.generate(1)
        inf = node.getblock(hsh[0])
        logging.info("block %d size %d" % (inf["height"], inf["size"]))
        return hsh

    def testExcessiveBlockSize(self):

        # get spendable coins
        if 0:
            for n in self.nodes:
                n.generate(1)
                self.sync_all()
            self.nodes[0].generate(100)

        # Set the accept depth at 1, 2, and 3 and watch each nodes resist the chain for that long
        self.nodes[0].setminingmaxblock(5000)  # keep the generated blocks within 16*the EB so no disconnects
        self.nodes[1].setminingmaxblock(1000)
        self.nodes[2].setminingmaxblock(1000)
        self.nodes[3].setminingmaxblock(1000)

        self.nodes[1].setexcessiveblock(1000, 1)
        self.nodes[2].setexcessiveblock(1000, 2)
        self.nodes[3].setexcessiveblock(1000, 3)

        logging.info("Test excessively sized block, not propagating until accept depth is exceeded")
        addr = self.nodes[3].getnewaddress()
        # By using a very small value, it is likely that a single input is used.  This is important because
        # our mined block size is so small in this test that if multiple inputs are used the transactions
        # might not fit in the block.  This will give us a short block when the test expects a larger one.
        # To catch any of these short-block test malfunctions, the block size is printed out.
        self.repeatTx(8, self.nodes[0], addr, .001)
        counts = [x.getblockcount() for x in self.nodes]
        base = counts[0]
        logging.info("Starting counts: %s" % str(counts))
        logging.info("node0")
        self.generateAndPrintBlock(self.nodes[0])
        assert_equal(True, self.expectHeights([base + 1, base, base, base]))

        logging.info("node1")
        self.nodes[0].generate(1)
        assert_equal(True, self.expectHeights([base + 2, base + 2, base, base]))

        logging.info("node2")
        self.nodes[0].generate(1)
        assert_equal(True, self.expectHeights([base + 3, base + 3, base + 3, base]))

        logging.info("node3")
        self.nodes[0].generate(1)
        assert_equal(True, self.expectHeights([base + 4] * 4))

        # Now generate another excessive block, but all nodes should snap right to
        # it because they have an older excessive block
        logging.info("Test immediate propagation of additional excessively sized block, due to prior excessive")
        self.repeatTx(8, self.nodes[0], addr, .001)
        self.nodes[0].generate(1)
        assert_equal(True, self.expectHeights([base + 5] * 4))

        logging.info("Test daily excessive reset")
        # Now generate a day's worth of small blocks which should re-enable the
        # node's reluctance to accept a large block
        self.nodes[0].generate(6 * 24)
        sync_blocks(self.nodes)
        self.nodes[0].generate(5)  # plus the accept depths
        sync_blocks(self.nodes)
        self.repeatTx(8, self.nodes[0], addr, .001)
        base = self.nodes[0].getblockcount()
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 1, base, base, base])

        self.repeatTx(8, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        sync_blocks(self.nodes[0:2])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 2, base + 2, base, base])

        self.repeatTx(5, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        sync_blocks(self.nodes[0:3])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 3, base + 3, base + 3, base])

        self.repeatTx(5, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        sync_blocks(self.nodes)
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 4] * 4)

        self.repeatTx(5, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        sync_blocks(self.nodes)
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 5] * 4)

        if self.extended:
            logging.info("Test daily excessive reset #2")
            # Now generate a day's worth of small blocks which should re-enable the
            # node's reluctance to accept a large block + 10 because we have to get
            # beyond all the node's accept depths
            self.nodes[0].generate(6 * 24 + 10)
            sync_blocks(self.nodes)

            # counts = [ x.getblockcount() for x in self.nodes ]
            self.nodes[1].setexcessiveblock(100000, 1)  # not sure how big the txns will be but smaller than this
            self.nodes[1].setminingmaxblock(100000)  # not sure how big the txns will be but smaller than this
            self.repeatTx(20, self.nodes[0], addr, .001)
            base = self.nodes[0].getblockcount()
            self.generateAndPrintBlock(self.nodes[0])
            time.sleep(2)  # give blocks a chance to fully propagate
            sync_blocks(self.nodes[0:2])
            counts = [x.getblockcount() for x in self.nodes]
            assert_equal(counts, [base + 1, base + 1, base, base])

        if self.extended:
            logging.info("Random test")
            randomRange = 3
        else:
            randomRange = 0

        for i in range(0, randomRange):
            logging.info("round %d" % i)
            for n in self.nodes:
                size = random.randint(1, 1000) * 1000
                try:  # since miningmaxblock must be <= excessiveblock, raising/lowering may need to run these in different order
                    n.setminingmaxblock(size)
                    n.setexcessiveblock(size, random.randint(0, 10))
                except JSONRPCException:
                    n.setexcessiveblock(size, random.randint(0, 10))
                    n.setminingmaxblock(size)

            addrs = [x.getnewaddress() for x in self.nodes]
            ntxs = 0
            for i in range(0, random.randint(1, 20)):
                try:
                    n = random.randint(0, 3)
                    logging.info("%s: Send to %d" % (ntxs, n))
                    self.nodes[n].sendtoaddress(addrs[random.randint(0, 3)], .1)
                    ntxs += 1
                except JSONRPCException:  # could be spent all the txouts
                    pass
            logging.info("%d transactions" % ntxs)
            time.sleep(1)  # allow txns a chance to propagate
            self.nodes[random.randint(0, 3)].generate(1)
            logging.info("mined a block")
            # TODO:  rather than sleeping we should really be putting a check in here
            #       based on what the random excessive seletions were from above
            time.sleep(5)  # allow block a chance to propagate

        # the random test can cause disconnects if the block size is very large compared to excessive size
        # so reconnect
        interconnect_nodes(self.nodes)

if __name__ == '__main__':

    if "--extensive" in sys.argv:
        longTest = True
        # we must remove duplicate 'extensive' arg here
        while True:
            try:
                sys.argv.remove('--extensive')
            except:
                break
        logging.info("Running extensive tests")
    else:
        longTest = False

    ExcessiveBlockTest(longTest).main()

def info(type, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type, value, tb)
        print
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

sys.excepthook = info

def Test():
    t = ExcessiveBlockTest()
    t.drop_to_pdb = True
    bitcoinConf = {
        "debug": ["rpc", "net", "blk", "thin", "mempool", "req", "bench", "evict"],
        "blockprioritysize": 2000000,  # we don't want any transactions rejected due to insufficient fees...
        "blockminsize": 1000000
    }

    flags = standardFlags()
    t.main(flags, bitcoinConf, None)


text:
from bs4.dammit import EntitySubstitution

class Formatter(EntitySubstitution):
    """Describes a strategy to use when outputting a parse tree to a string.

    Some parts of this strategy come from the distinction between
    HTML4, HTML5, and XML. Others are configurable by the user.

    Formatters are passed in as the `formatter` argument to methods
    like `PageElement.encode`. Most people won't need to think about
    formatters, and most people who need to think about them can pass
    in one of these predefined strings as `formatter` rather than
    making a new Formatter object:

    For HTML documents:
     * 'html' - HTML entity substitution for generic HTML documents. (default)
     * 'html5' - HTML entity substitution for HTML5 documents.
     * 'minimal' - Only make the substitutions necessary to guarantee
                   valid HTML.
     * None - Do not perform any substitution. This will be faster
              but may result in invalid markup.

    For XML documents:
     * 'html' - Entity substitution for XHTML documents.
     * 'minimal' - Only make the substitutions necessary to guarantee
                   valid XML. (default)
     * None - Do not perform any substitution. This will be faster
              but may result in invalid markup.
    """
    # Registries of XML and HTML formatters.
    XML_FORMATTERS = {}
    HTML_FORMATTERS = {}

    HTML = 'html'
    XML = 'xml'

    HTML_DEFAULTS = dict(
        cdata_containing_tags=set(["script", "style"]),
    )

    def _default(self, language, value, kwarg):
        if value is not None:
            return value
        if language == self.XML:
            return set()
        return self.HTML_DEFAULTS[kwarg]

    def __init__(
            self, language=None, entity_substitution=None,
            void_element_close_prefix='/', cdata_containing_tags=None,
    ):
        """Constructor.

        :param language: This should be Formatter.XML if you are formatting
           XML markup and Formatter.HTML if you are formatting HTML markup.

        :param entity_substitution: A function to call to replace special
           characters with XML/HTML entities. For examples, see
           bs4.dammit.EntitySubstitution.substitute_html and substitute_xml.
        :param void_element_close_prefix: By default, void elements
           are represented as <tag/> (XML rules) rather than <tag>
           (HTML rules). To get <tag>, pass in the empty string.
        :param cdata_containing_tags: The list of tags that are defined
           as containing CDATA in this dialect. For example, in HTML,
           <script> and <style> tags are defined as containing CDATA,
           and their contents should not be formatted.
        """
        self.language = language
        self.entity_substitution = entity_substitution
        self.void_element_close_prefix = void_element_close_prefix
        self.cdata_containing_tags = self._default(
            language, cdata_containing_tags, 'cdata_containing_tags'
        )

    def substitute(self, ns):
        """Process a string that needs to undergo entity substitution.
        This may be a string encountered in an attribute value or as
        text.

        :param ns: A string.
        :return: A string with certain characters replaced by named
           or numeric entities.
        """
        if not self.entity_substitution:
            return ns
        from .element import NavigableString
        if (isinstance(ns, NavigableString)
            and ns.parent is not None
            and ns.parent.name in self.cdata_containing_tags):
            # Do nothing.
            return ns
        # Substitute.
        return self.entity_substitution(ns)

    def attribute_value(self, value):
        """Process the value of an attribute.

        :param ns: A string.
        :return: A string with certain characters replaced by named
           or numeric entities.
        """
        return self.substitute(value)

    def attributes(self, tag):
        """Reorder a tag's attributes however you want.

        By default, attributes are sorted alphabetically. This makes
        behavior consistent between Python 2 and Python 3, and preserves
        backwards compatibility with older versions of Beautiful Soup.
        """
        if tag.attrs is None:
            return []
        return sorted(tag.attrs.items())

class HTMLFormatter(Formatter):
    """A generic Formatter for HTML."""
    REGISTRY = {}
    def __init__(self, *args, **kwargs):
        return super(HTMLFormatter, self).__init__(self.HTML, *args, **kwargs)

class XMLFormatter(Formatter):
    """A generic Formatter for XML."""
    REGISTRY = {}
    def __init__(self, *args, **kwargs):
        return super(XMLFormatter, self).__init__(self.XML, *args, **kwargs)

# Set up aliases for the default formatters.
HTMLFormatter.REGISTRY['html'] = HTMLFormatter(
    entity_substitution=EntitySubstitution.substitute_html
)
HTMLFormatter.REGISTRY["html5"] = HTMLFormatter(
    entity_substitution=EntitySubstitution.substitute_html,
    void_element_close_prefix = None
)
HTMLFormatter.REGISTRY["minimal"] = HTMLFormatter(
    entity_substitution=EntitySubstitution.substitute_xml
)
HTMLFormatter.REGISTRY[None] = HTMLFormatter(
    entity_substitution=None
)
XMLFormatter.REGISTRY["html"] =  XMLFormatter(
    entity_substitution=EntitySubstitution.substitute_html
)
XMLFormatter.REGISTRY["minimal"] = XMLFormatter(
    entity_substitution=EntitySubstitution.substitute_xml
)
XMLFormatter.REGISTRY[None] = Formatter(
    Formatter(Formatter.XML, entity_substitution=None)
)


text:
import * as common from 'test/specs/commonTests'
import GridRow from 'src/collections/Grid/GridRow'

describe('GridRow', () => {
  common.isConformant(GridRow)
  common.rendersChildren(GridRow)

  common.propKeyAndValueToClassName(GridRow, 'only')
  common.propKeyAndValueToClassName(GridRow, 'reversed')

  common.propKeyOnlyToClassName(GridRow, 'centered')
  common.propKeyOnlyToClassName(GridRow, 'divided')
  common.propKeyOnlyToClassName(GridRow, 'stretched')

  common.propValueOnlyToClassName(GridRow, 'color')

  common.implementsTextAlignProp(GridRow)
  common.implementsVerticalAlignProp(GridRow)
  common.implementsWidthProp(GridRow, { propKey: 'columns', widthClass: 'column', canEqual: true })
})


text:
package gameView.userManagement;

import gameView.tools.ImageViewContainer;
import gamedata.VoogaImmutableObservableList;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javafx.scene.image.Image;

public class UserData {

	private String username;
	private String password;
	private String image;
	private HashMap<String, Double> myGameScores;
	private Set<String> myAchievements;
	private Collection<String> myGames;
	private HashMap<String, String> mySavedGameMap;

	public UserData(String name, String passwordString, String imageString) {
		username = name;
		password = passwordString;
		myGameScores = new HashMap<String, Double>();
		mySavedGameMap = new HashMap<String, String>();
		myAchievements = new HashSet<String>();
		myGames = new ArrayList<String>();
		image = imageString == null ? "" : imageString;
	}

	/**
	 * @return name of user
	 */
	public String getName(){
		return username;
	}

	/**
	 * Adds a new high score to a specific game
	 * @param game - current game being played
	 * @param points - corresponding score
	 */
	public void addPoints(String game, Double points) {
		if (mySavedGameMap.containsKey(game)) {
			addPoints(mySavedGameMap.get(game), points);
		} else if (myGameScores.get(game) == null || myGameScores.get(game) < points) {
			myGameScores.put(game, points);
		}
	}

	/**
	 * Adds new achievements
	 * @param achieve - list of achievements the user has accrued during playing session
	 */
	public void addAchievement(VoogaImmutableObservableList<String> achieve) {
		Iterator<String> it = achieve.iterator();
		while (it.hasNext()) {
			myAchievements.add(it.next());
		}
	}

	/**
	 * @return Iterator of all the games
	 */
	public Iterator<String> getGameScores() {
		return myGameScores.keySet().iterator();
	}

	/**
	 * @return iterator of all the achievements
	 */
	public Iterator<String> getAchievements() {
		return myAchievements.iterator();
	}

	/**
	 * @param key - a specific game
	 * @return - String value of the number of points for that game
	 */
	public String getPointValue(String key) {
		return new Double(myGameScores.get(key).doubleValue()).toString();
	}

	/**
	 * @return - user password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @return ImageViewContainer of users image
	 */
	public ImageViewContainer getProfilePicture() {
		return makeImage(image);
	}

	/**
	 * Changes the user's profile picture
	 * @param newImage - new picture
	 */
	public void changePicture(String newImage) {
		image = newImage;
	}

	/**
	 * Adds a user-specific game -- if a user saves during gameplay, it will add the current game to allow user to load and pick up
	 * where they left off
	 * @param file
	 */
	public void addGame(String originalGame, String newGame) {
		myGames.add(newGame);
		mySavedGameMap.put(newGame, originalGame);
	}

	/**
	 * @return an unmodifiable list of all the user's games
	 */
	public Collection<String> getGames() {
		return Collections.unmodifiableCollection(myGames);
	}

	private ImageViewContainer makeImage(String s) {
		if (s.equals("")) {
			return null;
		}
		ImageViewContainer toAdd = new ImageViewContainer(new Image(image), image);
		return toAdd;
	}
}


text:
import { Folder } from '../Folder.js';
import { Book } from '../../Book/Book.js';

Meteor.publish('getFoldersByBookId', function(bookId) {
  check(bookId, String);

  const userId = this.userId;

  if (!userId) {
    throw new Meteor.Error(403, 'Do not have permisson');
  }

  const book = Book.findOne(bookId);

  if (!book) {
    throw new Meteor.Error('error', 'Book do not exist');
  }

  if (!book.isSharedWith(userId)) {
    throw new Meteor.Error('not-allowd', 'Do not have permission');
  }

  // XXX: check other permisosn here

  return Folder.find({
    bookId,
  });
});


text:
<?php
/**
 * Created by PhpStorm.
 * User: Ант
 * Date: 19.01.2017
 * Time: 1:19
 */

namespace AmoCrm\Client\Exception;

class QueryAggregatorException extends \Exception {

}


text:
import "../vendor/angular/angular.min.js";
import "../vendor/angular-sanitize/angular-sanitize.min.js";
import "../vendor/bootbox/bootbox.js";
import "../vendor/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.js";
import "../vendor/select2/dist/js/select2.full.min.js";
import "../vendor/c3/c3.js";
import "../vendor/c3-angular/c3-angular.js";
import "../vendor/moment/min/moment-with-locales.js";
import "../js/bootstrap/bootstrap-fileupload.min.js";
import "../vendor/bootstrap-datepicker/dist/js/bootstrap-datepicker.js";
import "../vendor/bootstrap-datepicker/dist/locales/bootstrap-datepicker.fr.min.js";
import "../vendor/angular-promise-tracker/promise-tracker.js";
import "../vendor/angular-promise-tracker/promise-tracker-http-interceptor.js";
import "../vendor/angular-growl-v2/build/angular-growl.js";
import "../vendor/underscore/underscore.js";
import "../vendor/ui-router/release/angular-ui-router.js";
import "../vendor/angular-strap/dist/angular-strap.js";
import "../vendor/angular-strap/dist/angular-strap.tpl.js";
import "../vendor/angular-ui-select/dist/select.js";
import "../vendor/angular-ui-tinymce/src/tinymce.js";
import "../vendor/socket.io-client/socket.io.js";


text:
namespace MobileApp.Android.Binding
{
    using System;

    using Cirrious.MvvmCross.Binding;
    using Cirrious.MvvmCross.Binding.Droid.Target;

    using MobileApp.Core.Models;

    using global::Android.Widget;

    /// <summary>
    /// The favorites imageView binding.
    /// </summary>
    public class IsOnlineImageBinding : MvxAndroidTargetBinding
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="IsOnlineImageBinding"/> class.
        /// </summary>
        /// <param name="imageView">
        /// The imageView.
        /// </param>
        public IsOnlineImageBinding(IDisposable imageView)
            : base(imageView)
        {
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets the default mode.
        /// </summary>
        public override MvxBindingMode DefaultMode
        {
            get
            {
                return MvxBindingMode.TwoWay;
            }
        }

        /// <summary>
        /// Gets the target type.
        /// </summary>
        public override Type TargetType
        {
            get
            {
                return typeof(ContactStatus);
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the image view.
        /// </summary>
        protected ImageView ImageView
        {
            get
            {
                return (ImageView)this.Target;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// The dispose.
        /// </summary>
        /// <param name="isDisposing">
        /// The is disposing.
        /// </param>
        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                var button = this.ImageView;
                if (button != null)
                {
                    button.Dispose();
                }
            }

            base.Dispose(isDisposing);
        }

        /// <summary>
        /// The set value impl.
        /// </summary>
        /// <param name="target">
        /// The target.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        protected override void SetValueImpl(object target, object value)
        {
            ContactStatus status;
            var test = value.ToString();
            if (Enum.TryParse(test, true, out status))
            {
                this.SetImageResource(status);
            }
        }

        private void SetImageResource(ContactStatus status)
        {
            var resource = 0;
            switch (status)
            {
                case ContactStatus.EarlyInbound:
                    resource = Resource.Drawable.ic_status_early_incoming;
                    break;
                case ContactStatus.EarlyOutbound:
                    resource = Resource.Drawable.ic_status_early_outgoing;
                    break;
                case ContactStatus.Confirmed:
                    resource = Resource.Drawable.ic_status_in_talk;
                    break;
                case ContactStatus.Online:
                    resource = Resource.Drawable.ic_status_online;
                    break;
                case ContactStatus.Offline:
                    resource = Resource.Drawable.ic_status_offline;
                    break;
            }

            var button = this.ImageView as ImageButton;
            if (button != null)
            {
                button.SetImageResource(resource);
            }
            else
            {
                this.ImageView.SetImageResource(resource);
            }
        }

        #endregion
    }
}


text:
from django.conf.urls import patterns, url
from schemes.views import *

urlpatterns = patterns('',

    url(
        regex=r'^student_schemes/$',
        view=Schemes_class_wise_count.as_view(),
        name='student_schemes'
    ),

    url(
        regex=r'^schemes/(?P<cl_id>\d+?)/$',
        view=Student_schemesView.as_view(),
        name='student_schemes_class'
    ),

)


text:
package io.github.vcuswimlab.stackintheflow.controller;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import io.github.vcuswimlab.stackintheflow.controller.component.ToolWindowComponent;
import io.github.vcuswimlab.stackintheflow.controller.component.stat.terms.TermStatComponent;
import io.github.vcuswimlab.stackintheflow.view.JavaBridge;
import io.github.vcuswimlab.stackintheflow.view.SearchToolWindowGUI;

import java.util.List;

/**
 * Created by Chase on 1/7/2017.
 */
public class AutoQueryAction extends AnAction {

    private List<String> compilerMessages;

    @Override
    public void update(final AnActionEvent e) {
        //Get required data keys
        final Project project = e.getData(CommonDataKeys.PROJECT);
        final Editor editor = e.getData(CommonDataKeys.EDITOR);
        //Set visibility only in case of existing project and editor
        e.getPresentation().setVisible((project != null && editor != null));
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        //Get required data keys
        final Project project = e.getData(CommonDataKeys.PROJECT);
        final Editor editor = e.getData(CommonDataKeys.EDITOR);

        //Generate the autoQuery
        String autoQuery = project.getComponent(TermStatComponent.class).generateQuery(editor);

        //Execute Search and Open Tool Window
        ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("StackInTheFlow");
        SearchToolWindowGUI toolWindowGUI = project.getComponent(ToolWindowComponent.class).getSearchToolWindowGUI();
        toolWindowGUI.autoQuery(autoQuery, true, "action");
        toolWindow.activate(() -> {
        });
    }
}


text: <Message>Workload Management Test Message</Message>


text:
layout: page
title: Curso básico
excerpt: "Curso básico"
comments: false
---

## 1x01

### Instalación y configuración

Para empezar a utilizar Blender debemos obtener el archivo de instalación de la página de [www.blender.org](https://www.blender.org/), concretamente desde su sección de descargas. Seleccionaremos el archivo de instalación en función de nuestra plataforma y lo instalaremos ejecutando dicho archivo.

Una vez concluída la instalación iniciamos el programa y vemos la pantalla de bienvenida indicándonos: la versión del programa, enlaces de interés, el modo de interacción (que por defecto es Blender), la posibilidad de recuperar el estado de la última sesión, y en el caso de que exista una versión previa del programa instalada en el ordenador, nos permitiría recuperar su configuración para esta nueva versión:

![Pantalla de bienvenida](/AconB/projects/cursobasico/1x01-02.png)

![Preferencias de usuario](/AconB/projects/cursobasico/1x01-03.png)

![Preferencias de interfaz](/AconB/projects/cursobasico/1x01-04.png)

![Preferencias de edición](/AconB/projects/cursobasico/1x01-05.png)

![Preferencias de entrada](/AconB/projects/cursobasico/1x01-06.png)

![Preferencias de sistema](/AconB/projects/cursobasico/1x01-07.png)

![Motor de render](/AconB/projects/cursobasico/1x01-08.png)

![Dispositivo de renderizado](/AconB/projects/cursobasico/1x01-09.png)

![Unidades](/AconB/projects/cursobasico/1x01-10.png)

![Guardado del archivo de inicio](/AconB/projects/cursobasico/1x01-11.png)


text:
package org.apache.jmeter.protocol.mongodb.mongo;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;

/**
 */
public class MongoDB {

    private static final Logger log = LoggerFactory.getLogger(MongoDB.class);

    // Mongo is Thread Safe
    private Mongo mongo = null;

    public MongoDB(
            List<ServerAddress> serverAddresses,
            MongoClientOptions mongoOptions) {
        mongo = new MongoClient(serverAddresses, mongoOptions);
    }

    public DB getDB(String database, String username, String password) {

        if(log.isDebugEnabled()) {
            log.debug("username: " + username+", password: " + password+", database: " + database);
        }
        DB db = mongo.getDB(database);
        boolean authenticated = db.isAuthenticated();

        if(!authenticated) {
            if(username != null && password != null && username.length() > 0 && password.length() > 0) {
                authenticated = db.authenticate(username, password.toCharArray());
            }
        }
        if(log.isDebugEnabled()) {
            log.debug("authenticated: " + authenticated);
        }
        return db;
    }

    public void clear() {
        if(log.isDebugEnabled()) {
            log.debug("clearing");
        }

        mongo.close();
        //there is no harm in trying to clear up
        mongo = null;
    }
}


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

namespace Selenium.WebDriver.Equip.Extensions
{
    public static class FirefoxDriverExtension
    {

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="CURRENT ISOLATION" />
<meta content="Função CURRENT ISOLATION" name="DC.subject" />
<meta content="Função CURRENT ISOLATION" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj29026.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefcurrentisolation" name="DC.Identifier" />
<meta content="pt-br" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>CURRENT ISOLATION</title>

CURRENT ISOLATION

CURRENT ISOLATION retorna o nível de isolamento corrente como um valor
CHAR(2) contendo ""(branco), "UR", "CS", "RS" ou "RR".

Sintaxe

CURRENT ISOLATION

VALUES CURRENT ISOLATION

Tópico pai: Funções nativas


text:
package kieker.analysis.util;

import java.util.List;

import kieker.common.record.IMonitoringRecord;
import kieker.monitoring.core.controller.IMonitoringController;

/**
 *
 * @author Christian Wulf
 *
 * @since 1.13
 */
public class TestProbe {

	private final IMonitoringController monitoringController;

	public TestProbe(final IMonitoringController monitoringController) {
		super();
		this.monitoringController = monitoringController;
	}

	public void triggerRecords(final List<IMonitoringRecord> records) {
		for (final IMonitoringRecord record : records) {
			this.monitoringController.newMonitoringRecord(record);
		}
	}
}


text:
var assert = require('assert');
require('should');

var validator = require('../lib/validator');

function expectFailure(message, childName, childValue) {
  message.should.not.be.empty;
}

function expectSuccess() {
  throw new Error('fail');
}

describe('validator.isString', function () {
  it('should pass strings',
    function () {
      validator.isString().validate('', expectSuccess);
      validator.isString().validate('asdfasdf', expectSuccess);
    });

  it('should test regex options',
    function () {
      validator.isString({regex: /^[abc]+$/}).validate('', expectFailure);
      validator.isString({regex: /^[\w\d\-_].*$/}).validate('', expectFailure);
      validator.isString({regex: /^[\w\d\-_].*$/}).validate('asd', expectSuccess);
      validator.isString({regex: /^[abc]+$/}).validate('a', expectSuccess);
      validator.isString({regex: /^[abc]+$/}).validate('b', expectSuccess);
      validator.isString({regex: /^[abc]+$/}).validate('c', expectSuccess);
      validator.isString({regex: /^[abc]+$/}).validate('bca', expectSuccess);
      validator.isString({regex: /^[abc]+$/}).validate('d', expectFailure);
      validator.isString({regex: /^[abc]+$/}).validate('3', expectFailure);
    });

  it('should test fail regex match of empty child element',
    function (done) {
      var check = validator.isObject()
        .withRequired('test', validator.isString({regex: /^[abc]+$/}));

      var toValidate = {test:''};
      check.validate(toValidate, expectFailure);

      validator.run(check, toValidate, function(errorCount, errors) {
        errorCount.should.equal(1);
        errors.should.have.length(1);
        errors[0].message.should.equal('Invalid value. Value must match required pattern.');
        errors[0].parameter.should.equal('test');
        errors[0].value.should.equal('');
        done();
      });
    });

  it('should fail non-strings',
    function () {
      validator.isString().validate(true, expectFailure);
      validator.isString().validate(null, expectFailure);
      validator.isString().validate(0, expectFailure);
      validator.isString().validate(1, expectFailure);
      validator.isString().validate(123.5, expectFailure);
      validator.isString().validate({}, expectFailure);
      validator.isString().validate([], expectFailure);
      validator.isString().validate(function () {}, expectFailure);
    });

});


text:
package test.blog;

import org.junit.Test;

import blog.Main;

/**
 * @author awong
 * @since Mar 18, 2013
 *
 */
public class TestComparison {

  private static String[] args = { "-n", "1" };

  @Test
  public void testLessThan() {
    String code = "fixed Boolean x = 3 < 5;" +
    		"query x;";
    Main.runFromString(code, args);
  }

  @Test
  public void testLessThanOrEqual() {
    String code = "fixed Boolean x = 5 <= 5;" +
    		"query x;";
    Main.runFromString(code, args);
  }

  @Test
  public void testBounded() {
	String code = "fixed Integer c = 7;" +
			"fixed Boolean x = c > 5 & c >= 7 & c <= 7 & c < 11;" +
			"query x;";
	Main.runFromString(code, args);
  }
}


text: .. include:: ../../HISTORY.rst