text:
module GeoKit
  # Contains class and instance methods providing distance calcuation services.  This
  # module is meant to be mixed into classes containing lat and lng attributes where
  # distance calculation is desired.
  #
  # At present, two forms of distance calculations are provided:
  #
  # * Pythagorean Theory (flat Earth) - which assumes the world is flat and loses accuracy over long distances.
  # * Haversine (sphere) - which is fairly accurate, but at a performance cost.
  #
  # Distance units supported are :miles and :kms.
  module Mappable
    PI_DIV_RAD = 0.0174
    KMS_PER_MILE = 1.609
    EARTH_RADIUS_IN_MILES = 3963.19
    EARTH_RADIUS_IN_KMS = EARTH_RADIUS_IN_MILES * KMS_PER_MILE
    MILES_PER_LATITUDE_DEGREE = 69.1
    KMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * KMS_PER_MILE
    LATITUDE_DEGREES = EARTH_RADIUS_IN_MILES / MILES_PER_LATITUDE_DEGREE

    # Mix below class methods into the includer.
    def self.included(receiver) # :nodoc:
      receiver.extend ClassMethods
    end

    module ClassMethods #:nodoc:
      # Returns the distance between two points.  The from and to parameters are
      # required to have lat and lng attributes.  Valid options are:
      # :units - valid values are :miles or :kms (GeoKit::default_units is the default)
      # :formula - valid values are :flat or :sphere (GeoKit::default_formula is the default)
      def distance_between(from, to, options={})
        from=GeoKit::LatLng.normalize(from)
        to=GeoKit::LatLng.normalize(to)
        return 0.0 if from == to # fixes a "zero-distance" bug
        units = options[:units] || GeoKit::default_units
        formula = options[:formula] || GeoKit::default_formula
        case formula
        when :sphere
          units_sphere_multiplier(units) *
              Math.acos( Math.sin(deg2rad(from.lat)) * Math.sin(deg2rad(to.lat)) +
              Math.cos(deg2rad(from.lat)) * Math.cos(deg2rad(to.lat)) *
              Math.cos(deg2rad(to.lng) - deg2rad(from.lng)))
        when :flat
          Math.sqrt((units_per_latitude_degree(units)*(from.lat-to.lat))**2 +
              (units_per_longitude_degree(from.lat, units)*(from.lng-to.lng))**2)
        end
      end

      # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc)
      # from the first point to the second point. Typicaly, the instance methods will be used
      # instead of this method.
      def heading_between(from,to)
        from=GeoKit::LatLng.normalize(from)
        to=GeoKit::LatLng.normalize(to)

        d_lng=deg2rad(to.lng-from.lng)
        from_lat=deg2rad(from.lat)
        to_lat=deg2rad(to.lat)
        y=Math.sin(d_lng) * Math.cos(to_lat)
        x=Math.cos(from_lat)*Math.sin(to_lat)-Math.sin(from_lat)*Math.cos(to_lat)*Math.cos(d_lng)
        heading=to_heading(Math.atan2(y,x))
      end

      # Given a start point, distance, and heading (in degrees), provides
      # an endpoint. Returns a LatLng instance. Typically, the instance method
      # will be used instead of this method.
      def endpoint(start,heading, distance, options={})
        units = options[:units] || GeoKit::default_units
        radius = units == :miles ? EARTH_RADIUS_IN_MILES : EARTH_RADIUS_IN_KMS
        start=GeoKit::LatLng.normalize(start)
        lat=deg2rad(start.lat)
        lng=deg2rad(start.lng)
        heading=deg2rad(heading)
        distance=distance.to_f

        end_lat=Math.asin(Math.sin(lat)*Math.cos(distance/radius) +
                          Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading))

        end_lng=lng+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat),
                               Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat))

        LatLng.new(rad2deg(end_lat),rad2deg(end_lng))
      end

      # Returns the midpoint, given two points. Returns a LatLng.
      # Typically, the instance method will be used instead of this method.
      # Valid option:
      #   :units - valid values are :miles or :kms (:miles is the default)
      def midpoint_between(from,to,options={})
        from=GeoKit::LatLng.normalize(from)

        units = options[:units] || GeoKit::default_units

        heading=from.heading_to(to)
        distance=from.distance_to(to,options)
        midpoint=from.endpoint(heading,distance/2,options)
      end

      # Geocodes a location using the multi geocoder.
      def geocode(location)
        res = Geocoders::MultiGeocoder.geocode(location)
        return res if res.success
        raise GeoKit::Geocoders::GeocodeError
      end

      protected

      def deg2rad(degrees)
        degrees.to_f / 180.0 * Math::PI
      end

      def rad2deg(rad)
        rad.to_f * 180.0 / Math::PI
      end

      def to_heading(rad)
        (rad2deg(rad)+360)%360
      end

      # Returns the multiplier used to obtain the correct distance units.
      def units_sphere_multiplier(units)
        units == :miles ? EARTH_RADIUS_IN_MILES : EARTH_RADIUS_IN_KMS
      end

      # Returns the number of units per latitude degree.
      def units_per_latitude_degree(units)
        units == :miles ? MILES_PER_LATITUDE_DEGREE : KMS_PER_LATITUDE_DEGREE
      end

      # Returns the number units per longitude degree.
      def units_per_longitude_degree(lat, units)
        miles_per_longitude_degree = (LATITUDE_DEGREES * Math.cos(lat * PI_DIV_RAD)).abs
        units == :miles ? miles_per_longitude_degree : miles_per_longitude_degree * KMS_PER_MILE
      end
    end

    # -----------------------------------------------------------------------------------------------
    # Instance methods below here
    # -----------------------------------------------------------------------------------------------

    # Extracts a LatLng instance. Use with models that are acts_as_mappable
    def to_lat_lng
      return self if instance_of?(GeoKit::LatLng) || instance_of?(GeoKit::GeoLoc)
      return LatLng.new(send(self.class.lat_column_name),send(self.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable)
      return nil
    end

    # Returns the distance from another point.  The other point parameter is
    # required to have lat and lng attributes.  Valid options are:
    # :units - valid values are :miles or :kms (:miles is the default)
    # :formula - valid values are :flat or :sphere (:sphere is the default)
    def distance_to(other, options={})
      self.class.distance_between(self, other, options)
    end
    alias distance_from distance_to

    # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc)
    # to the given point. The given point can be a LatLng or a string to be Geocoded
    def heading_to(other)
      self.class.heading_between(self,other)
    end

    # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc)
    # FROM the given point. The given point can be a LatLng or a string to be Geocoded
    def heading_from(other)
      self.class.heading_between(other,self)
    end

    # Returns the endpoint, given a heading (in degrees) and distance.
    # Valid option:
    # :units - valid values are :miles or :kms (:miles is the default)
    def endpoint(heading,distance,options={})
      self.class.endpoint(self,heading,distance,options)
    end

    # Returns the midpoint, given another point on the map.
    # Valid option:
    # :units - valid values are :miles or :kms (:miles is the default)
    def midpoint_to(other, options={})
      self.class.midpoint_between(self,other,options)
    end

  end

  class LatLng
    include Mappable

    attr_accessor :lat, :lng

    # Accepts latitude and longitude or instantiates an empty instance
    # if lat and lng are not provided. Converted to floats if provided
    def initialize(lat=nil, lng=nil)
      lat = lat.to_f if lat && !lat.is_a?(Numeric)
      lng = lng.to_f if lng && !lng.is_a?(Numeric)
      @lat = lat
      @lng = lng
    end

    # Latitude attribute setter; stored as a float.
    def lat=(lat)
      @lat = lat.to_f if lat
    end

    # Longitude attribute setter; stored as a float;
    def lng=(lng)
      @lng=lng.to_f if lng
    end

    # Returns the lat and lng attributes as a comma-separated string.
    def ll
      "#{lat},#{lng}"
    end

    #returns a string with comma-separated lat,lng values
    def to_s
      ll
    end

    #returns a two-element array
    def to_a
      [lat,lng]
    end
    # Returns true if the candidate object is logically equal.  Logical equivalence
    # is true if the lat and lng attributes are the same for both objects.
    def ==(other)
      other.is_a?(LatLng) ? self.lat == other.lat && self.lng == other.lng : false
    end

    # A *class* method to take anything which can be inferred as a point and generate
    # a LatLng from it. You should use this anything you're not sure what the input is,
    # and want to deal with it as a LatLng if at all possible. Can take:
    #  1) two arguments (lat,lng)
    #  2) a string in the format "37.1234,-129.1234" or "37.1234 -129.1234"
    #  3) a string which can be geocoded on the fly
    #  4) an array in the format [37.1234,-129.1234]
    #  5) a LatLng or GeoLoc (which is just passed through as-is)
    #  6) anything which acts_as_mappable -- a LatLng will be extracted from it
    def self.normalize(thing,other=nil)
      # if an 'other' thing is supplied, normalize the input by creating an array of two elements
      thing=[thing,other] if other

      if thing.is_a?(String)
        thing.strip!
        if match=thing.match(/(\-?\d+\.?\d*)[, ] ?(\-?\d+\.?\d*)$/)
          return GeoKit::LatLng.new(match[1],match[2])
        else
          res = GeoKit::Geocoders::MultiGeocoder.geocode(thing)
          return res if res.success
          raise GeoKit::Geocoders::GeocodeError
        end
      elsif thing.is_a?(Array) && thing.size==2
        return GeoKit::LatLng.new(thing[0],thing[1])
      elsif thing.is_a?(LatLng) # will also be true for GeoLocs
        return thing
      elsif thing.class.respond_to?(:acts_as_mappable) && thing.class.respond_to?(:distance_column_name)
        return thing.to_lat_lng
      end

      throw ArgumentError.new("#{thing} (#{thing.class}) cannot be normalized to a LatLng. We tried interpreting it as an array, string, Mappable, etc., but no dice.")
    end

  end

  # This class encapsulates the result of a geocoding call
  # It's primary purpose is to homogenize the results of multiple
  # geocoding providers. It also provides some additional functionality, such as
  # the "full address" method for geocoders that do not provide a
  # full address in their results (for example, Yahoo), and the "is_us" method.
  class GeoLoc < LatLng
    # Location attributes.  Full address is a concatenation of all values.  For example:
    # 100 Spear St, San Francisco, CA, 94101, US
    attr_accessor :street_address, :city, :state, :zip, :country_code, :full_address
    # Attributes set upon return from geocoding.  Success will be true for successful
    # geocode lookups.  The provider will be set to the name of the providing geocoder.
    # Finally, precision is an indicator of the accuracy of the geocoding.
    attr_accessor :success, :provider, :precision
    # Street number and street name are extracted from the street address attribute.
    attr_reader :street_number, :street_name

    # Constructor expects a hash of symbols to correspond with attributes.
    def initialize(h={})
      @street_address=h[:street_address]
      @city=h[:city]
      @state=h[:state]
      @zip=h[:zip]
      @country_code=h[:country_code]
      @success=false
      @precision='unknown'
      super(h[:lat],h[:lng])
    end

    # Returns true if geocoded to the United States.
    def is_us?
      country_code == 'US'
    end

    # full_address is provided by google but not by yahoo. It is intended that the google
    # geocoding method will provide the full address, whereas for yahoo it will be derived
    # from the parts of the address we do have.
    def full_address
      @full_address ? @full_address : to_geocodeable_s
    end

    # Extracts the street number from the street address if the street address
    # has a value.
    def street_number
      street_address[/(\d*)/] if street_address
    end

    # Returns the street name portion of the street address.
    def street_name
       street_address[street_number.length, street_address.length].strip if street_address
    end

    # gives you all the important fields as key-value pairs
    def hash
      res={}
      [:success,:lat,:lng,:country_code,:city,:state,:zip,:street_address,:provider,:full_address,:is_us?,:ll,:precision].each { |s| res[s] = self.send(s.to_s) }
      res
    end
    alias to_hash hash

    # Sets the city after capitalizing each word within the city name.
    def city=(city)
      @city = city.titleize if city
    end

    # Sets the street address after capitalizing each word within the street address.
    def street_address=(address)
      @street_address = address.titleize if address
    end

    # Returns a comma-delimited string consisting of the street address, city, state,
    # zip, and country code.  Only includes those attributes that are non-blank.
    def to_geocodeable_s
      a=[street_address, city, state, zip, country_code].compact
      a.delete_if { |e| !e || e == '' }
      a.join(', ')
    end

    # Returns a string representation of the instance.
    def to_s
      "Provider: #{provider}\nStreet: #{street_address}\nCity: #{city}\nState: #{state}\nZip: #{zip}\nLatitude: #{lat}\nLongitude: #{lng}\nCountry: #{country_code}\nSuccess: #{success}"
    end
  end

  # Bounds represents a rectangular bounds, defined by the SW and NE corners
  class Bounds
    # sw and ne are LatLng objects
    attr_accessor :sw, :ne

    # provide sw and ne to instantiate a new Bounds instance
    def initialize(sw,ne)
      raise ArguementError if !(sw.is_a?(GeoKit::LatLng) && ne.is_a?(GeoKit::LatLng))
      @sw,@ne=sw,ne
    end

    #returns the a single point which is the center of the rectangular bounds
    def center
      @sw.midpoint_to(@ne)
    end

    # a simple string representation:sw,ne
    def to_s
      "#{@sw.to_s},#{@ne.to_s}"
    end

    # a two-element array of two-element arrays: sw,ne
    def to_a
      [@sw.to_a, @ne.to_a]
    end

    # Returns true if the bounds contain the passed point.
    # allows for bounds which cross the meridian
    def contains?(point)
      point=GeoKit::LatLng.normalize(point)
      res = point.lat > @sw.lat && point.lat < @ne.lat
      if crosses_meridian?
        res &= point.lng < @ne.lng || point.lng > @sw.lng
      else
        res &= point.lng < @ne.lng && point.lng > @sw.lng
      end
      res
    end

    # returns true if the bounds crosses the international dateline
    def crosses_meridian?
      @sw.lng > @ne.lng
    end

    # Returns true if the candidate object is logically equal.  Logical equivalence
    # is true if the lat and lng attributes are the same for both objects.
    def ==(other)
      other.is_a?(Bounds) ? self.sw == other.sw && self.ne == other.ne : false
    end

    class <<self

      # returns an instance of bounds which completely encompases the given circle
      def from_point_and_radius(point,radius,options={})
        point=LatLng.normalize(point)
        p0=point.endpoint(0,radius,options)
        p90=point.endpoint(90,radius,options)
        p180=point.endpoint(180,radius,options)
        p270=point.endpoint(270,radius,options)
        sw=GeoKit::LatLng.new(p180.lat,p270.lng)
        ne=GeoKit::LatLng.new(p0.lat,p90.lng)
        GeoKit::Bounds.new(sw,ne)
      end

      # Takes two main combinations of arguements to create a bounds:
      # point,point   (this is the only one which takes two arguments
      # [point,point]
      # . . . where a point is anything LatLng#normalize can handle (which is quite a lot)
      #
      # NOTE: everything combination is assumed to pass points in the order sw, ne
      def normalize (thing,other=nil)
        # maybe this will be simple -- an actual bounds object is passed, and we can all go home
        return thing if thing.is_a? Bounds

        # no? OK, if there's no "other," the thing better be a two-element array
        thing,other=thing if !other && thing.is_a?(Array) && thing.size==2

        # Now that we're set with a thing and another thing, let LatLng do the heavy lifting.
        # Exceptions may be thrown
        Bounds.new(GeoKit::LatLng.normalize(thing),GeoKit::LatLng.normalize(other))
      end
    end
  end
end


text: var pathb = true

redpajama_set_name: RedPajamaGithub


text:
layout: single
title: "Terraform with vSphere - Part 3"
date: 2017-10-12
category: [VMware,Terraform]
excerpt: "This is Part 3 on how to use Terraform with vSphere. Let's look at using Variables with Terraform"
---
# Introduction
In [Part 1]({{ site.baseurl }}{% post_url 2017-10-01-Terraform-Part-1 %}) and [Part 2]({{ site.baseurl }}{% post_url 2017-10-08-Terraform-Part-2 %}) we downloaded, setup, and then created a simple VM using Terraform. Let's look how to use variables and the files required for this.

# Existing Code

Let's look at the code from Part 2:

~~~ ruby
provider "vsphere" {
    user = "username@corp.contoso.com" # You need to use this format, not example\username
    password = "Password1"
    vsphere_server = "vcenter.corp.contoso.com"

    # If you use self-signed certificates
    allow_unverified_ssl = true
}

resource "vsphere_virtual_machine" "webserver" {
    name = "webserver1"
    vcpu = 1
    memory = 2048

network_interface {
    label = "VM Network"
}

disk {
   datastore = "datastore"
   template = "MicroCore-Linux"
}

}
~~~

We have hard coded the login details and vCenter name. These are great candidates to convert to variables. We do this by replacing them with a ```"${var.variablename}"```:

~~~ ruby
provider "vsphere" {
    user = "${var.username}" # You need to use this format, not example\username
    password = "${var.password}"
    vsphere_server = "${var.vcenter}"

    # If you use self-signed certificates
    allow_unverified_ssl = true
}
~~~

So our three variables are ```username```, ```password``` and ```vcenter```.

# Variable File

We now need to create a new file in ```C:\Terraform``` called, for example, vars.tf.  This file defines our variables:

~~~ ruby
variable "username" {}
variable "password" {}
variable "vcenter" {}
~~~

You can enter a description if you like such as:

~~~ ruby
variable "username" {
    description = "Enter the username for vCenter"
}
~~~

# Terraform Plan

By default, Terraform will look for any file that has variables defined and use them. Notice we have not actually defined our values for username, password or the vCenter, so when you run Terraform Plan you will be prompted for the details:

~~~ ruby
C:\Terraform>terraform plan
var.username
  Enter a value: username@corp.contoso.com

var.password
  Enter a value: Password

var.vcenter
  Enter a value: vcenter.corp.contoso.com

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
~~~

I've snipped the above. You can see we were prompted for the details. A step backwards you would rightly think!

# terraform.tfvars File

We should place our actual variable values in a file called ```terraform.tfvars```. If a file called exactly that is in the same folder as our code file and the variables file, Terraform will auto load the ```terraform.tfvars``` file and use the value in it.

So for our example, ```terraform.tfvars``` will look like:

~~~ ruby
username = "username@corp.contoso.com"
password = "Password1"
vcenter = "vcenter.corp.contoso.com"
~~~

Now if you run Terraform it will look at the main code file, see we have variables, look in the other vars.tf file for the definition of them and finally automatically look in terraform.tfvars

# terraform.tfvars and Source Control

Now as I am sure you are storing your Terraform files in source control such as GitHub, but think about ```terraform.tfvars```. That's your precious credentials. You don't want them up on Github available for anyone to see.

**If you are using GitHub I would highly recommend you add ```terraform.tfvars``` to your ```.gitignore``` file. This will make GitHub ignore the file and not upload it to the web.**

# More with Variables

Of course I have done something simple here and just changed the connection information to vSphere into variables. You can do much more such as making the datastore name we are using, the VM name, the template, etc. into variables. Have a look at the [documentation](https://www.terraform.io/intro/getting-started/variables.html) for more information. I have given you the building blocks, you can decide how to use them.

# Part 4
In the wrap up [Part 4]({{ site.baseurl }}{% post_url 2017-10-15-Terraform-Part-4 %}) I will point you in the direction of some great resources for learning more about Terraform.


text:
YUI().use('calendar', 'datatype-date', 'datatype-date-math', function(Y) {

    // Switch the calendar main template to the included two pane template

    // Create a new instance of calendar, setting the showing of previous
    // and next month's dates to true, and the selection mode to multiple
    // selected dates. Additionally, set the disabledDatesRule to a name of
    // the rule which, when matched, will force the date to be excluded
    // from being selected. Also configure the initial date on the calendar
    // to be July of 2011.

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth(); //January is 0!
    var yyyy = today.getFullYear();

    var calendar = new Y.Calendar({
        contentBox: "#mycalendar",
        width:"305px",
        showPrevMonth: true,
        showNextMonth: true,
        selectionMode: 'multiple',
        disabledDatesRule: "disables",

        date: new Date(yyyy,mm,dd)

        //date: new Date(2016,10,25)

    }).render();

// Create a set of rules to match specific dates. In this case,
// the "sundays" rule will match any sunday,

    var rules = {

        "all": {
            "all": {
                "all":{
                    "0":"disables"
                }
            },
            "9": {
                "28": "disables",
                "1":"disables"
            },
            "2":{
                "25":"disables"
            },
            "11":{
                "25":"disables"
            },
            "0":{
                "1":"disables"
            }
        }

    };

// Set the calendar customRenderer, provides the rules defined above,
// as well as a filter function. The filter function receives a reference
// to the node corresponding to the DOM element of the date that matched
// one or more rule, along with the list of rules. Check if one of the
// rules is "all_weekends", and if so, apply a custom CSS class to the
// node.
    calendar.set("customRenderer", {
        rules: rules,
        filterFunction: function (date, node, rules) {
            if (Y.Array.indexOf(rules, 'argia') >= 0) {
                node.addClass("redtext");
            }
        }
    });
    var dtdate = Y.DataType.Date;

// When selection changes, output the fired event to the
// console. the newSelection attribute in the event facade
// will contain the list of currently selected dates (or be
// empty if all dates have been deselected).
    calendar.on("selectionChange", function (ev) {

        // Get the date from the list of selected
        // dates returned with the event (since only
        // single selection is enabled by default,
        // we expect there to be only one date)
        var newDate = ev.newSelection[0];

        var user = "/admin.php?appointment=";
        var newSite = user.concat(dtdate.format(newDate));

        window.location.href = newSite;

        // Format the date and output it to a DOM
        // element.
        Y.one("#selecteddate").setContent(dtdate.format(newDate));
    });

});


text:
/*===-- llvm-c/Target.h - Target Lib C Iface --------------------*- C++ -*-===*/
/*                                                                            */
/*                     The LLVM Compiler Infrastructure                       */
/*                                                                            */
/* This file is distributed under the University of Illinois Open Source      */
/* License. See LICENSE.TXT for details.                                      */
/*                                                                            */
/*===----------------------------------------------------------------------===*/
/*                                                                            */
/* This header declares the C interface to libLLVMTarget.a, which             */
/* implements target information.                                             */
/*                                                                            */
/* Many exotic languages can interoperate with C code but have a harder time  */
/* with C++ due to name mangling. So in addition to C, this interface enables */
/* tools written in such languages.                                           */
/*                                                                            */
/*===----------------------------------------------------------------------===*/

#ifndef LLVM_C_TARGET_H
#define LLVM_C_TARGET_H

#include "llvm-c/Types.h"
#include "llvm/Config/llvm-config.h"

#if defined(_MSC_VER) && !defined(inline)
#define inline __inline
#endif

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup LLVMCTarget Target information
 * @ingroup LLVMC
 *
 * @{
 */

enum LLVMByteOrdering { LLVMBigEndian, LLVMLittleEndian };

typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
typedef struct LLVMOpaqueTargetLibraryInfotData *LLVMTargetLibraryInfoRef;

/* Declare all of the target-initialization functions that are available. */
#define LLVM_TARGET(TargetName) \
  void LLVMInitialize##TargetName##TargetInfo(void);
#include "llvm/Config/Targets.def"
#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */

#define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(void);
#include "llvm/Config/Targets.def"
#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */

#define LLVM_TARGET(TargetName) \
  void LLVMInitialize##TargetName##TargetMC(void);
#include "llvm/Config/Targets.def"
#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */

/* Declare all of the available assembly printer initialization functions. */
#define LLVM_ASM_PRINTER(TargetName) \
  void LLVMInitialize##TargetName##AsmPrinter(void);
#include "llvm/Config/AsmPrinters.def"
#undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */

/* Declare all of the available assembly parser initialization functions. */
#define LLVM_ASM_PARSER(TargetName) \
  void LLVMInitialize##TargetName##AsmParser(void);
#include "llvm/Config/AsmParsers.def"
#undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */

/* Declare all of the available disassembler initialization functions. */
#define LLVM_DISASSEMBLER(TargetName) \
  void LLVMInitialize##TargetName##Disassembler(void);
#include "llvm/Config/Disassemblers.def"
#undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */

/** LLVMInitializeAllTargetInfos - The main program should call this function if
    it wants access to all available targets that LLVM is configured to
    support. */
static inline void LLVMInitializeAllTargetInfos(void) {
#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo();
#include "llvm/Config/Targets.def"
#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
}

/** LLVMInitializeAllTargets - The main program should call this function if it
    wants to link in all available targets that LLVM is configured to
    support. */
static inline void LLVMInitializeAllTargets(void) {
#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target();
#include "llvm/Config/Targets.def"
#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
}

/** LLVMInitializeAllTargetMCs - The main program should call this function if
    it wants access to all available target MC that LLVM is configured to
    support. */
static inline void LLVMInitializeAllTargetMCs(void) {
#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
#include "llvm/Config/Targets.def"
#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
}

/** LLVMInitializeAllAsmPrinters - The main program should call this function if
    it wants all asm printers that LLVM is configured to support, to make them
    available via the TargetRegistry. */
static inline void LLVMInitializeAllAsmPrinters(void) {
#define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter();
#include "llvm/Config/AsmPrinters.def"
#undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
}

/** LLVMInitializeAllAsmParsers - The main program should call this function if
    it wants all asm parsers that LLVM is configured to support, to make them
    available via the TargetRegistry. */
static inline void LLVMInitializeAllAsmParsers(void) {
#define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser();
#include "llvm/Config/AsmParsers.def"
#undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
}

/** LLVMInitializeAllDisassemblers - The main program should call this function
    if it wants all disassemblers that LLVM is configured to support, to make
    them available via the TargetRegistry. */
static inline void LLVMInitializeAllDisassemblers(void) {
#define LLVM_DISASSEMBLER(TargetName) \
  LLVMInitialize##TargetName##Disassembler();
#include "llvm/Config/Disassemblers.def"
#undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
}

/** LLVMInitializeNativeTarget - The main program should call this function to
    initialize the native target corresponding to the host.  This is useful
    for JIT applications to ensure that the target gets linked in correctly. */
static inline LLVMBool LLVMInitializeNativeTarget(void) {
  /* If we have a native target, initialize it to ensure it is linked in. */
#ifdef LLVM_NATIVE_TARGET
  LLVM_NATIVE_TARGETINFO();
  LLVM_NATIVE_TARGET();
  LLVM_NATIVE_TARGETMC();
  return 0;
#else
  return 1;
#endif
}

/** LLVMInitializeNativeTargetAsmParser - The main program should call this
    function to initialize the parser for the native target corresponding to the
    host. */
static inline LLVMBool LLVMInitializeNativeAsmParser(void) {
#ifdef LLVM_NATIVE_ASMPARSER
  LLVM_NATIVE_ASMPARSER();
  return 0;
#else
  return 1;
#endif
}

/** LLVMInitializeNativeTargetAsmPrinter - The main program should call this
    function to initialize the printer for the native target corresponding to
    the host. */
static inline LLVMBool LLVMInitializeNativeAsmPrinter(void) {
#ifdef LLVM_NATIVE_ASMPRINTER
  LLVM_NATIVE_ASMPRINTER();
  return 0;
#else
  return 1;
#endif
}

/** LLVMInitializeNativeTargetDisassembler - The main program should call this
    function to initialize the disassembler for the native target corresponding
    to the host. */
static inline LLVMBool LLVMInitializeNativeDisassembler(void) {
#ifdef LLVM_NATIVE_DISASSEMBLER
  LLVM_NATIVE_DISASSEMBLER();
  return 0;
#else
  return 1;
#endif
}

/*===-- Target Data -------------------------------------------------------===*/

/**
 * Obtain the data layout for a module.
 *
 * @see Module::getDataLayout()
 */
LLVMTargetDataRef LLVMGetModuleDataLayout(LLVMModuleRef M);

/**
 * Set the data layout for a module.
 *
 * @see Module::setDataLayout()
 */
void LLVMSetModuleDataLayout(LLVMModuleRef M, LLVMTargetDataRef DL);

/** Creates target data from a target layout string.
    See the constructor llvm::DataLayout::DataLayout. */
LLVMTargetDataRef LLVMCreateTargetData(const char *StringRep);

/** Deallocates a TargetData.
    See the destructor llvm::DataLayout::~DataLayout. */
void LLVMDisposeTargetData(LLVMTargetDataRef TD);

/** Adds target library information to a pass manager. This does not take
    ownership of the target library info.
    See the method llvm::PassManagerBase::add. */
void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,
                              LLVMPassManagerRef PM);

/** Converts target data to a target layout string. The string must be disposed
    with LLVMDisposeMessage.
    See the constructor llvm::DataLayout::DataLayout. */
char *LLVMCopyStringRepOfTargetData(LLVMTargetDataRef TD);

/** Returns the byte order of a target, either LLVMBigEndian or
    LLVMLittleEndian.
    See the method llvm::DataLayout::isLittleEndian. */
enum LLVMByteOrdering LLVMByteOrder(LLVMTargetDataRef TD);

/** Returns the pointer size in bytes for a target.
    See the method llvm::DataLayout::getPointerSize. */
unsigned LLVMPointerSize(LLVMTargetDataRef TD);

/** Returns the pointer size in bytes for a target for a specified
    address space.
    See the method llvm::DataLayout::getPointerSize. */
unsigned LLVMPointerSizeForAS(LLVMTargetDataRef TD, unsigned AS);

/** Returns the integer type that is the same size as a pointer on a target.
    See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrType(LLVMTargetDataRef TD);

/** Returns the integer type that is the same size as a pointer on a target.
    This version allows the address space to be specified.
    See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrTypeForAS(LLVMTargetDataRef TD, unsigned AS);

/** Returns the integer type that is the same size as a pointer on a target.
    See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrTypeInContext(LLVMContextRef C, LLVMTargetDataRef TD);

/** Returns the integer type that is the same size as a pointer on a target.
    This version allows the address space to be specified.
    See the method llvm::DataLayout::getIntPtrType. */
LLVMTypeRef LLVMIntPtrTypeForASInContext(LLVMContextRef C, LLVMTargetDataRef TD,
                                         unsigned AS);

/** Computes the size of a type in bytes for a target.
    See the method llvm::DataLayout::getTypeSizeInBits. */
unsigned long long LLVMSizeOfTypeInBits(LLVMTargetDataRef TD, LLVMTypeRef Ty);

/** Computes the storage size of a type in bytes for a target.
    See the method llvm::DataLayout::getTypeStoreSize. */
unsigned long long LLVMStoreSizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);

/** Computes the ABI size of a type in bytes for a target.
    See the method llvm::DataLayout::getTypeAllocSize. */
unsigned long long LLVMABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);

/** Computes the ABI alignment of a type in bytes for a target.
    See the method llvm::DataLayout::getTypeABISize. */
unsigned LLVMABIAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);

/** Computes the call frame alignment of a type in bytes for a target.
    See the method llvm::DataLayout::getTypeABISize. */
unsigned LLVMCallFrameAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);

/** Computes the preferred alignment of a type in bytes for a target.
    See the method llvm::DataLayout::getTypeABISize. */
unsigned LLVMPreferredAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);

/** Computes the preferred alignment of a global variable in bytes for a target.
    See the method llvm::DataLayout::getPreferredAlignment. */
unsigned LLVMPreferredAlignmentOfGlobal(LLVMTargetDataRef TD,
                                        LLVMValueRef GlobalVar);

/** Computes the structure element that contains the byte offset for a target.
    See the method llvm::StructLayout::getElementContainingOffset. */
unsigned LLVMElementAtOffset(LLVMTargetDataRef TD, LLVMTypeRef StructTy,
                             unsigned long long Offset);

/** Computes the byte offset of the indexed struct element for a target.
    See the method llvm::StructLayout::getElementContainingOffset. */
unsigned long long LLVMOffsetOfElement(LLVMTargetDataRef TD,
                                       LLVMTypeRef StructTy, unsigned Element);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif /* defined(__cplusplus) */

#endif


text:
/*
 * CubicConvolutionInterpolationTest.cpp
 *
 *  Created on: Mar 3, 2020
 *      Author: Edo Jelavic
 *      Institute: ETH Zurich, Robotic Systems Lab
 */

#include "test_helpers.hpp"

#include "grid_map_core/GridMap.hpp"

// gtest
#include <gtest/gtest.h>

namespace gm = grid_map;
namespace gmt = grid_map_test;

TEST(CubicConvolutionInterpolation, FlatWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(2.0, 2.0), 0.1, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createFlatWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 100);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, FlatWorld failed with seed: " << seed
              << std::endl;
  }
}

TEST(CubicConvolutionInterpolation, RationalFunctionWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(3.0, 3.0), 0.01, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createRationalFunctionWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 1000);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, RationalFunctionWorld failed with seed: "
              << seed << std::endl;
  }
}

TEST(CubicConvolutionInterpolation, SaddleWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(3.0, 3.0), 0.1, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createSaddleWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 1000);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, SaddleWorld failed with seed: " << seed
              << std::endl;
  }
}

TEST(CubicConvolutionInterpolation, SecondOrderPolyWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(3.0, 3.0), 0.1, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createSecondOrderPolyWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 1000);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, SecondOrderPolyWorld failed with seed: "
              << seed << std::endl;
  }
}

TEST(CubicConvolutionInterpolation, SineWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(3.0, 3.0), 0.01, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createSineWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 1000);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, SineWorld failed with seed: " << seed
              << std::endl;
  }
}

TEST(CubicConvolutionInterpolation, TanhWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(2.5, 2.5), 0.02, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createTanhWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 1000);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, TanhWorld failed with seed: " << seed
              << std::endl;
  }
}

TEST(CubicConvolutionInterpolation, GaussianWorld)
{
  const int seed = rand();
  gmt::rndGenerator.seed(seed);
  auto map = gmt::createMap(gm::Length(3.0, 3.0), 0.02, gm::Position(0.0, 0.0));
  auto trueValues = gmt::createGaussianWorld(&map);
  const auto queryPoints = gmt::uniformlyDitributedPointsWithinMap(map, 1000);

  verifyValuesAtQueryPointsAreClose(map, trueValues, queryPoints, gm::InterpolationMethods::INTER_CUBIC_CONVOLUTION);

  if (::testing::Test::HasFailure()) {
    std::cout << "\n Test CubicConvolutionInterpolation, GaussianWorld failed with seed: " << seed
              << std::endl;
  }
}


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Linq;

namespace RelationScaffolding
{
    public class RelationHelper
    {
        private ViewDataDictionary _viewDataDictionary;
        private RelationMemberLookup _cachedRelationMemberLookup = null;

        public RelationHelper(ViewDataDictionary viewDataDictionary)
        {
            _viewDataDictionary = viewDataDictionary;
        }

        public RelationMemberLookup GetLookup()
        {
            if (_cachedRelationMemberLookup == null)
            {
                _cachedRelationMemberLookup = new RelationMemberLookup(_viewDataDictionary.Model, _viewDataDictionary.ModelMetadata.ModelType);
            }

            return _cachedRelationMemberLookup;
        }

        public static TResult GetCustomAttributesFromContainer<TResult>(Type container, string memberName)
        {
            var customAttribute = container.GetMembers().FirstOrDefault(x => x.Name == memberName).GetCustomAttributes(typeof(TResult), true).OfType<TResult>().FirstOrDefault();

            if (customAttribute == null)
            {
                // Check the metadata type
                var metadataType = container.GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
                if (metadataType != null)
                {
                    return GetCustomAttributesFromContainer<TResult>(metadataType.MetadataClassType, memberName);
                }
            }

            return customAttribute;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Basic Porfolio - About</title>

    <link rel="stylesheet" href="assets/css/reset.css">
    <link rel="stylesheet" href="assets/css/style.css">

Jeff Lowy

About |

Portfolio |

Contact

Connect with Me

Contact

            <form action="#">
                Name
                <input type="text" name="name" placeholder="John Smith">
                Email
                <input type="email" name="email" placeholder="example@gmail.com">
                Message
                <textarea name="message" id="message" rows="10"></textarea>
                <input type="submit" value="Submit">
            </form>

© 2017 Jeff Lowy


text: <input type="hidden" id="msg_test3_input" value="123"/>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cercospora ononidicola Unamuno

### Remarks
null


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

package com.azure.resourcemanager.mediaservices.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Configures Unknown output handling settings of the license. */
public final class ContentKeyPolicyPlayReadyUnknownOutputPassingOption
    extends ExpandableStringEnum<ContentKeyPolicyPlayReadyUnknownOutputPassingOption> {
    /** Static value Unknown for ContentKeyPolicyPlayReadyUnknownOutputPassingOption. */
    public static final ContentKeyPolicyPlayReadyUnknownOutputPassingOption UNKNOWN = fromString("Unknown");

    /** Static value NotAllowed for ContentKeyPolicyPlayReadyUnknownOutputPassingOption. */
    public static final ContentKeyPolicyPlayReadyUnknownOutputPassingOption NOT_ALLOWED = fromString("NotAllowed");

    /** Static value Allowed for ContentKeyPolicyPlayReadyUnknownOutputPassingOption. */
    public static final ContentKeyPolicyPlayReadyUnknownOutputPassingOption ALLOWED = fromString("Allowed");

    /** Static value AllowedWithVideoConstriction for ContentKeyPolicyPlayReadyUnknownOutputPassingOption. */
    public static final ContentKeyPolicyPlayReadyUnknownOutputPassingOption ALLOWED_WITH_VIDEO_CONSTRICTION =
        fromString("AllowedWithVideoConstriction");

    /**
     * Creates or finds a ContentKeyPolicyPlayReadyUnknownOutputPassingOption from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ContentKeyPolicyPlayReadyUnknownOutputPassingOption.
     */
    @JsonCreator
    public static ContentKeyPolicyPlayReadyUnknownOutputPassingOption fromString(String name) {
        return fromString(name, ContentKeyPolicyPlayReadyUnknownOutputPassingOption.class);
    }

    /**
     * Gets known ContentKeyPolicyPlayReadyUnknownOutputPassingOption values.
     *
     * @return known ContentKeyPolicyPlayReadyUnknownOutputPassingOption values.
     */
    public static Collection<ContentKeyPolicyPlayReadyUnknownOutputPassingOption> values() {
        return values(ContentKeyPolicyPlayReadyUnknownOutputPassingOption.class);
    }
}


text:
package com.andbase.demo.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.ab.activity.AbActivity;
import com.ab.view.chart.CategorySeries;
import com.ab.view.chart.ChartFactory;
import com.ab.view.chart.DefaultRenderer;
import com.ab.view.chart.SimpleSeriesRenderer;
import com.ab.view.titlebar.AbTitleBar;
import com.andbase.R;
import com.andbase.global.MyApplication;
/**
 * © 2012 amsoft.cn。
 * 名称:PieChartActivity
 * 描述:饼图
 * @author 还如一梦中
 * @date 2011-12-13
 * @version
 */
public class PieChartActivity extends AbActivity {

	private MyApplication application;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setAbContentView(R.layout.chart);

        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(R.string.chart_pie);
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.drawable.line);

        application = (MyApplication)abApplication;

    	//要显示图形的View
		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.chart01);

		//每个块的颜色
		int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA, Color.YELLOW, Color.CYAN };
		//渲染器
		DefaultRenderer renderer = new DefaultRenderer();
		//图表标题
	    renderer.setChartTitle("我是图表的标题");
	    //图形标题文字大小
  		renderer.setChartTitleTextSize(25);
  		//轴线上标签文字大小
  		renderer.setLabelsTextSize(15);
  		//说明文字大小
  		renderer.setLegendTextSize(15);
  	    //设置图表上标题与X轴与Y轴的说明文字颜色
	    renderer.setLabelsColor(Color.GRAY);
		//说明文字大小
		renderer.setLegendTextSize(15);
		for (int color : colors) {
			  //创建SimpleSeriesRenderer对象
		      SimpleSeriesRenderer r = new SimpleSeriesRenderer();
		      r.setColor(color);
		      renderer.addSeriesRenderer(r);
		}
		//创建数据填充器
		CategorySeries series = new CategorySeries("支出情况");
		series.add("住房", 28);
		series.add("食物", 25);
		series.add("水电", 2);
		series.add("娱乐", 20);
		series.add("服装", 25);

		//设置图表的背景颜色
	    renderer.setApplyBackgroundColor(true);
	    renderer.setBackgroundColor(Color.rgb(222, 222, 200));
	    //renderer.setMargins(new int[]{5,5,5,5});
		//获取图表View
	    View chart = ChartFactory.getPieChartView(this,series,renderer);
        linearLayout.addView(chart);

      }

}


text:
package simplebft

import "time"

func (s *SBFT) sendViewChange() {
	s.view = s.nextView()
	s.cur.timeout.Cancel()
	s.activeView = false
	for src := range s.replicaState {
		state := &s.replicaState[src]
		if state.viewchange != nil && state.viewchange.View < s.view {
			state.viewchange = nil
		}
	}
	log.Noticef("replica %d: sending viewchange for view %d", s.id, s.view)

	var q, p []*Subject
	if s.cur.prepared {
		p = append(p, &s.cur.subject)
	}
	if s.cur.preprep != nil {
		q = append(q, &s.cur.subject)
	}

	// TODO fix batches synchronization as we send no payload here
	checkpoint := *s.sys.LastBatch(s.chainId)
	checkpoint.Payloads = nil // don't send the big payload

	vc := &ViewChange{
		View:       s.view,
		Qset:       q,
		Pset:       p,
		Checkpoint: &checkpoint,
	}
	svc := s.sign(vc)
	s.viewChangeTimer.Cancel()
	s.cur.timeout.Cancel()

	s.sys.Persist(s.chainId, viewchange, svc)
	s.broadcast(&Msg{&Msg_ViewChange{svc}})
}

func (s *SBFT) cancelViewChangeTimer() {
	s.viewChangeTimer.Cancel()
	s.viewChangeTimeout = time.Duration(s.config.RequestTimeoutNsec) * 2
}

func (s *SBFT) handleViewChange(svc *Signed, src uint64) {
	vc := &ViewChange{}
	err := s.checkSig(svc, src, vc)
	if err == nil {
		_, err = s.checkBatch(vc.Checkpoint, false, true)
	}
	if err != nil {
		log.Noticef("replica %d: invalid viewchange: %s", s.id, err)
		return
	}
	if vc.View < s.view {
		log.Debugf("replica %d: old view change from %d for view %d, we are in view %d", s.id, src, vc.View, s.view)
		return
	}
	if ovc := s.replicaState[src].viewchange; ovc != nil && vc.View <= ovc.View {
		log.Noticef("replica %d: duplicate view change for %d from %d", s.id, vc.View, src)
		return
	}

	log.Infof("replica %d: viewchange from %d: %v", s.id, src, vc)
	s.replicaState[src].viewchange = vc
	s.replicaState[src].signedViewchange = svc

	min := vc.View

	//amplify current primary abdication
	if s.view == min-1 && s.primaryID() == src {
		s.sendViewChange()
		return
	}

	quorum := 0
	for _, state := range s.replicaState {
		if state.viewchange != nil {
			quorum++
			if state.viewchange.View < min {
				min = state.viewchange.View
			}
		}
	}

	if quorum == s.oneCorrectQuorum() {
		// catch up to the minimum view
		if s.view < min {
			log.Noticef("replica %d: we are behind on view change, resending for newer view", s.id)
			s.view = min - 1
			s.sendViewChange()
			return
		}
	}

	if quorum == s.viewChangeQuorum() {
		log.Noticef("replica %d: received view change quorum, starting view change timer", s.id)
		s.viewChangeTimer = s.sys.Timer(s.viewChangeTimeout, func() {
			s.viewChangeTimeout *= 2
			log.Noticef("replica %d: view change timed out, sending next", s.id)
			s.sendViewChange()
		})
	}

	if s.isPrimary() {
		s.maybeSendNewView()
	}
}


text:
## TABLE OF CONTENTS
* [Introduction](#introduction)
* [(Not) Modular](#not-modular)
* [Base Classes](#base-classes)
  * [MY\_controller](#my-controller)
  * [Public\_controller](#public-controller)
  * [Private\_controller](#private-controller)
  * [Admin\_controller](#admin-controller)
  * [API\_controller](#api-controller)
  * [Understanding Includes](#understanding-includes)
* [Core Files](#core-files)
  * [Core Config](#core-config)
  * [Core Language](#core-language)
  * [Core Helper](#core-helper)
* [Internationalization](#i18n)
  * [Jsi18n Library](#jsi18n-library)
* [User Management](#user-management)
* [Settings](#settings)
* [Themes](#themes)
  * [Theme Functions](#theme-functions)
* [APIs](#apis)
* [System Requirements](#system-requirements)
* [Installation](#installation)
* [Updates](#updates)
* [Conclusion](#conclusion)
* [What's New](#whats-new)
* [Fork It!](#forkit)

## INTRODUCTION

CI3 Fire Starter is a CodeIgniter3 skeleton application that includes [jQuery](https://jquery.com/) and
[Twitter Bootstrap](http://getbootstrap.com/). It is intended to be light weight, minimalistic and not
get in your way of building great CodeIgniter 3 applications. It is also intended for new CodeIgniter
developers who want a simple, easy platform for learning the framework.

* CodeIgniter 3.x
* Base controllers for Public, Private, Admin and API classes
* Internationalization (translations) support
    + Jsi18n Library to support internationalization in your JS files
* The latest version of [jQuery](https://jquery.com/)
* The latest version of [Twitter Bootstrap](http://getbootstrap.com/)
* The latest version of [Font Awesome](https://fortawesome.github.io/Font-Awesome/)
* Independent responsive admin and frontend themes
* [Summernote](http://summernote.org/ "Summernote") WYSIWYG editor
* Auto-loaded core config file
* Auto-loaded core language file (based on selected language)
* Auto-loaded core helper files
    + Human-readable JSON string output for API functions
    + Array to CSV exporting
    + Enhanced CAPTCHA
    + Random password generator
    + Available languages fetcher
* Simple user authentication with registration, forgot password and profile editor
* Contact Us page with enhanced CAPTCHA
* Basic admin tool with dashboard, user management, settings and Contact Us message list
* File-based sessions

That should cover the basic needs for kickstarting many small CodeIgniter 3 projects. While there are some
great CodeIgniter CMS applications ([see below](#conclusion)), sometimes you don't need a full CMS or you
need a completely customizable solution. That's why I created CI3 Fire Starter. I was tired of always
having to do the same things over and over again. So I took some best practices, included all the addons and
functions I most commonly use, and this was the end result, which I use to start many of my smaller projects.

I hope you find it useful. **Please [fork it on Github](https://github.com/JasonBaier/ci3-fire-starter/fork "Fork It")
and help make it better!**

NOTE: This documentation assumes you are already familiar with PHP and CodeIgniter. To learn more about PHP,
visit [php.net](http://php.net/). If you need to learn more about CodeIgniter, visit the
[CodeIgniter User Guide](http://www.codeigniter.com/userguide3/index.html).

![Welcome Screen](http://s13.postimg.org/ci5nj384n/Screen_Shot_2015_12_19_at_9_47_56_AM.png?raw=true)

## (NOT) MODULAR

The former versions of CI Fire Starter (prior to v3.0.0) used to utilize wiredesign's
[Modular Extensions](https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc). At this
time I have opted not to include it, however, if you have an argument in support of reimplementing it,
just let me know and we can open it up for discussion.

## BASE CLASSES

Phil Sturgeon wrote a very helpful blog post years ago called
["CodeIgniter Base Classes: Keeping it DRY"](http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY).
The methods he described in that article have been implemented in CI3 Fire Starter. All base classes
are located in the /application/core folder.

#### MY_Controller

This is the main core class used for loading settings, defining includes that get passed to the views,
loading logged-in user data, setting the configured timezone, and turning the profiler on or off. All
other classes extend this class.

#### Public_Controller

This extends MY\_Controller and drives all your public pages (home page, etc). Any controller that
extends Public\_Controller will be open for the whole world to see.

#### Private_Controller

This extends MY\_Controller and drives all your private pages (user profile, etc). Any controller that
extends Private\_Controller will require authentication. Specific page requests are stored in session
and will redirect upon successful authentication.

![Profile Screen](http://s14.postimg.org/3xmw5l4f5/Screen_Shot_2015_12_19_at_9_51_23_AM.png?raw=true)

#### Admin_Controller

This extends MY\_Controller and drives all your administration pages. Any controller that extends
Admin\_Controller will require authentication from a user with administration privileges. Specific
page requests are stored in session and will redirect upon successful authentication.

#### API_Controller

This extends MY\_Controller and drives all your API functions. Any controller that extends
API\_Controller will be open for the whole world to see ([see below for details](#apis)).

#### Understanding Includes

* page\_title    : the title of the page which gets inserted into the document head
* css\_files     : an array of css files to insert into the document head
* js\_files      : an array of javascript libraries to insert into the document body
* js\_files\_i18n : an array of javascript files with internationalization to insert into the document body (see more about these below)

Includes can be appended and/or overwritten from any controller function.

## CORE FILES

Several core files have been included to simplify customizations:

#### Core Config

In /application/config there is a file core.php. This file allows you to set site-wide variables. It
is set up with site version, default templates, pagination settings, login attempt settings,
enable/disable the profiler and default form validation error delimiters.

#### Core Language

In /application/language/english is a file core\_lang.php. This file allows you to set language
variables that could be used throughout the entire site (such as the words Home or Logout).

#### Core Helper

In /application/helpers is a file core\_helper.php. This includes the following useful functions:

* display\_json($array) - used to output an array as JSON in a human-readable format - used by the API
* json\_indent($array) - this is the function that actually creates the human-readable JSON string
* array\_to\_csv($array, $filename) - exports an array into a CSV file (see admin user list)
* generate\_random\_pasword() - used to reset password for users who forgot password
* get\_languages() - retrieves a list of all language folders

## INTERNATIONALIZATION

Thanks to contributions from the community, the list of language translations is growing:

* Chinese (Simplified)
* Dutch
* English (default)
* Indonesian
* Russian
* Spanish
* Turkish

Registered users can set their own preferred language, admins can set preferred languauges for each user, and
non-registered users can use the language selector to render the site in their preferred language. The application
looks for a session variable (_$this->session->langauge_) to determine which language to show. If one is not found in the
session, the default defined in the main config file is used. If the user is logged in, then their assigned language is
used instead. If a user selects a different languauge other than what is configured, the selected languauge will be used
during their session.

All available languages are also stored in the session to improve performance.
They are available in _$this->session->languages_.

> If a translated language file is missing, the application will use English as the fall back using the extended MY_Lang class.

#### Jsi18n Library

This library allows you to internationalize your JavaScript files through CI language files and was
inspired by Alexandros D on [coderwall.com](https://coderwall.com/p/j88iog). It is included in /application/libraries.

Load this library in the autoload.php file or manually in your controller:

    $this->load->library('jsi18n');

In your language file:

    $lang['alert_message'] = "This is my alert message!";

In your JS files, place your language key inside double braces:

    function myFunction() {
        alert("{{alert_message}}");
    }

Render the Javascript file in your template file:

OR in your includes array:

    $this->includes = array_merge_recursive($this->includes, array(
        'js_files_i18n' => array(
            $this->jsi18n->translate("/themes/admin/js/my_javascript_i18n.js")
        )
    ));

## USER MANAGEMENT

CI3 Fire Starter comes with a simple user management tool in the administration tool. It uses a database
table called 'users'. This tool demonstrates a lot of basic but important functionality:

* Sortable list columns
* Search filters
* Pagination with user-changeable items/page
* Exporting lists to CSV
* Form validation
* Harnessing the power of Twitter Bootstrap to accelerate development

![User Administration](http://s27.postimg.org/orbhgea1f/Screen_Shot_2015_12_19_at_9_52_44_AM.png?raw=true)

IMPORTANT NOTE: user id 1 is the main administrator - DO NOT MANUALLY DELETE. You can not delete this
user from within the admin tool.

## SETTINGS

Adding additional site owner-configurable setting fields couldn't be any easier. Simply add a new entry in the 'settings'
table of the database with the information below. The script then does all the work and adds the
setting fields to the form automatically. There's no need to modify the form yourself!

* name: this will be the actual input name in the settings form (Ex: site\_name)
* input\_type: type of input to use - options are: input, textarea, radio, dropdown, timezones
* options: optional field for declaring radio and dropdown values - key/value pair - each on its own line
* is\_numeric: 0 or 1 - forces numeric keypad on mobile devices and validates numbers only on form submission
* show\_editor: 0 or 1 - use only on textarea field types to utilize the WYSIWYG editor
* input\_size: use to specify width of input field - options are: small, medium, large
* translate: 0 or 1 - set to 1 if you want inputs for each language - multiple translated values are then stored as a serialized array
* help\_text: optional field for displaying help/info about the input
* validation: specifies how to validate the input values - uses the pipe-delimited rules from CI's Form
Validation Library - see [Rule Reference](https://codeigniter.com/user_guide/libraries/form_validation.html#rule-reference)
* sort\_order: use to sort the order of input fields
* label: text to display as the input's label
* value: this is the actual value stored for this setting - be sure to set something as the default value - NOTE: if you enable translation,
just enter a non-serialized value for your default language - the script will handle the rest
* last\_update: datetimestamp of when the settings field was updated
* updated\_by: reference to the 'users'.'id'

Settings are loaded in MY_Controller and are accessible in every controller, model and view file.

**Non-translated Example:**

    $this->settings->site_version

**Translated Example:**

    $this->settings->welcome_message[$this->session->language]

![Settings Screen](http://s22.postimg.org/9wq5ngx01/Screen_Shot_2015_12_22_at_10_46_23_AM.png?raw=true)

## THEMES

There are 2 responsive themes provided with CI3 Fire Starter: 'admin' and 'default'. There is also a
'core' theme for global assets. To keep the application light-weight, I did not include a templating
library, such as Smarty, nor did I utilize CI's built-in parser. If you really wanted to include one,
you could check out Phil Sturgeon's [CI-Dwoo extension](https://github.com/philsturgeon/codeigniter-dwoo).

#### Theme Functions

***add_css_theme($css_files)***

This function is used to easily add css files to be included in a template. With this function, you
can just add the css file name as a parameter and it will use the default css path for the active theme.
You can add one or more css files as the parameter, either as a string or an array. If using parameter
as a string, it must use comma separation between each css file name.

	 1. Using string as parameter
	     $this->add_css_theme("bootstrap.min.css, style.css, admin.css");

	 2. Using array as parameter
	     $this->add_css_theme(array("bootstrap.min.css", "style.css", "admin.css"));

***add_js_theme($js_files, $is_i18n)***

This function is used to easily add Javascript files to be included in a template. With this function,
you can just add the js file name as a parameter and it will use the default js path for the active theme.
You can add one or more js files as the parameter, either as a string or an array. If using the parameter
as a string, it must use comma separation between each js file name.

The second parameter is used to indicate that the js file supports internationalization using the i18n library. Default is FALSE.

	 1. Using string as parameter
	     $this->add_js_theme("jquery-1.11.1.min.js, bootstrap.min.js, another.js");

	 2. Using array as parameter
	     $this->add_js_theme(array("jquery-1.11.1.min.js", "bootstrap.min.js,", "another.js"));

***add_jsi18n_theme($js_files)***

This function is used to easily add Javascript files that support internationalization to be included
in a template. With this function, you can just add the js file name as the parameter and it will use
the default js path for the active theme. You also can add one or more js files as the parameter,
either as a string or an array. If using the parameter as a string, it must use comma separation
between each js file name.

    1. Using string as parameter
	    $this->add_jsi18n_theme("dahboard_i18n.js, contact_i18n.js");

	2. Using array as parameter
	    $this->add_jsi18n_theme(array("dahboard_i18n.js", "contact_i18n.js"));

	3. Or we can use add_js_theme function, and add TRUE for second parameter
	    $this->add_js_theme("dahboard_i18n.js, contact_i18n.js", TRUE);
	    	- or -
	    $this->add_js_theme(array("dahboard_i18n.js", "contact_i18n.js"), TRUE);

***add_external_css($css_files, $path)***

This function is used to easily add css files from external sources or outside the theme folder to be
included in a template. With this function, you can just add the css file name and their external path
as the parameter, or add css complete with path. See example below:

    1. Using string as first parameter
	    $this->add_external_css("global.css, color.css", "http://example.com/assets/css/");
	 	- or -
	    $this->add_external_css("http://example.com/assets/css/global.css, http://example.com/assets/css/color.css");

	2. Using array as first parameter
	    $this->add_external_css(array("global.css", "color.css"), "http://example.com/assets/css/");
		- or -
	    $this->add_external_css(array("http://example.com/assets/css/global.css", "http://example.com/assets/css/color.css"));

***add_external_js($js_files, $path)***

This function is used to easily add js files from external sources or outside the theme folder to be
included in a template. With this function, you can just add the js file name and their external path
as the parameter, or add js complete with path. See example below:

    1. Using string as first parameter
	    $this->add_external_js("global.js, color.js", "http://example.com/assets/js/");
	 	- or -
	    $this->add_external_js("http://example.com/assets/js/global.js, http://example.com/assets/js/color.js");

	2. Using array as first parameter
	    $this->add_external_js(array("global.js", "color.js"), "http://example.com/assets/js/");
		- or -
	    $this->add_external_js(array("http://example.com/assets/js/global.js", "http://example.com/assets/js/color.js"));

***Chaining***

These methods can also be chained like this:

    $this
        ->add_css_theme("bootstrap.min.css, style.css, admin.css")
		->add_external_css("global.css, color.css", "http://example.com/assets/css/")
        ->add_js_theme("jquery-1.11.1.min.js, bootstrap.min.js, another.js")
		->add_js_theme("dahboard_i18n.js, contact_i18n.js", TRUE)
		->add_external_js("global.js, color.js", "http://example.com/assets/js/");

***set_template($template_file)***

Sometimes you might want to use a different template for different pages, for example, 404 template,
login template, full-width template, sidebar template, etc. You can simply load a different template
using this function.

## APIS

With the API class, you can easily create API functions for external applications. There is no
security on these, so if you need a more robust solution, such as authentication and API keys, check
out Phil Sturgeon's [CI Rest Server](https://github.com/philsturgeon/codeigniter-restserver). You
could also just set your own request authentication headers to the code that's already there.

![Sample JSON String](http://s8.postimg.org/nx4x1tdlx/ci3_fire_starter_sample_api.png?raw=true)

## SYSTEM REQUIREMENTS

* PHP version 5.4+
* MySQL 5.1+
* PHP GD extension for CAPTCHA to work
* PHP Mcrypt extension if you want to use the Encryption class

See CodeIgniter's [Server Requirements](https://codeigniter.com/user_guide/general/requirements.html)
for the complete list.

## INSTALLATION

* Create a new database and import the included sql file from the /assets folder
    + default administrator username/password is **admin/admin**
* Modify the /application/config/config.php
    + line 26: set your base site URL (new requirement as of CI v3.0.3)
    + line 220: set your log threshold - I usually set it to 1 for production environments
    + line 314: set your encryption key using the [recommended method](http://www.codeigniter.com/user_guide/libraries/encryption.html#setting-your-encryption-key "Encryption Library: Setting your encryption key")
* Modify /application/config/database.php and connect to your database
* Modify /application/config/core.php and set $config['root_folder'] to match your server's webroot (htdocs, public_html, etc.)
* Upload all files to your server - for security, /application and /system must go above your webroot and all the files and subfolders in /htdocs will go inside your webroot
* Make sure the /captcha folder inside your webroot has write permission
* Set /application/sessions permission to 0600
* Visit your new URL
* The default welcome page includes links to the admin tool and the private user profile page
* Make sure you log in to admin and change the administrator password!

## UPDATES

Since version 3.2.4, anytime changes to the database are required, you'll find SQL files in /assets/schema\_updates.

##CONCLUSION

As I mentioned earlier, CI3 Fire Starter does not attempt to be a full-blown CMS. You would need
to build that functionality yourself. If you're looking for a great CMS built on CodeIgniter,
or need a more robust starting point, then check out one of these great applications:

* [HeroFramework](https://github.com/electricfunction/hero/): this project appears to no longer be active, however, the source is still available
* [Halogy](http://www.halogy.com/): not sure if development is still active on this project
* [Expression Engine](http://ellislab.com/expressionengine/): from the original creators of CodeIgniter
* [GoCart](http://gocartdv.com/): shopping cart
* [Bonfire](http://cibonfire.com/)
* [FuelCMS](http://getfuelcms.com/)
* [CMS Canvas](http://www.cmscanvas.com/)

## WHAT'S NEW

#### Version 3.2.4
02/29/2016

* Security Updates
    + Limit login requests
    + Improved encryption key (you still should replace it with your own)
    + Set username and password lengths
* Added 'email' form input fields where applicable for better mobile support
* Added new 'schema\_updates' folder in the 'assets' folder - includes SQL for new 'login\_attempt' table

#### Version 3.2.3
01/20/2016

Thanks [klavatron](https://github.com/klavatron "klavatron") for your Russian translation.

* Upgraded to CI 3.0.4
* Included pull requests
    + Russian translation
* Fixed Issue #21 for locating translation folders on Windows (thanks [Everterstraat](https://github.com/Everterstraat "Everterstraat") for finding the source of the problem)

#### Version 3.2.2
12/23/2015

* Added configurable webroot in core.php config file

#### Version 3.2.1
12/22/2015

* Site owner-configurable settings now translatable (requires update to settings table)

#### Version 3.2.0
12/19/2015

* Added language selector
* Users are now assigned a language (requires update to users table)
* Setup English as a fall back when translated language files are missing

#### Version 3.1.7
12/17/2015

* Added pagination config file

#### Version 3.1.6
12/11/2015

Thanks [TowerX](https://github.com/TowerX "TowerX") for your Spanish translation.
Thanks [yinlianwei](https://github.com/yinlianwei "yinlianwei") for your Simplified Chinese translation.

* Included pull requests
    + Spanish translation
    + Simplified Chinese translation

#### Version 3.1.5
11/10/2015

* Moved CAPTCHA font, Bromine, to core theme folder

#### Version 3.1.4
11/09/2015

* Moved the base classes into their own files
* Added [Table of Contents](#toc) to README.md
* Added new section for [Settings](#settings) in README.md

#### Version 3.1.3
11/02/2015

* Upgraded to CI 3.0.3
    + Requires you to now set your base URL in config.php
* Upgraded jQuery to 1.11.3
* Upgraded Font Awesome to 4.4.0

#### Version 3.1.2
08/25/2015

Thanks [DeeJaVu](https://github.com/DeeJaVu "DeeJaVu") for your Turkish and Dutch translations.

* Included pull requests
    + Turkish translation
    + Dutch translation
* Upgraded to CI 3.0.1

#### Version 3.1.1
06/16/2015

Thanks [arif-rh](https://github.com/arif-rh "Arif RH") and [simogeo](https://github.com/simogeo "Simon Georget")
for your contributions.

* Included pull requests
    + Added base\_url to links
    + Improved theme functions
    + Indonesian translation
    + Repeat Password error fix
* Fixed email validation check during account registration
* Links to this Github page in theme footers

#### Version 3.1.0
04/15/2015

* Upgraded to CI 3.0.0

#### Version 3.0.5
03/11/2015

* Upgraded to CI 3.0rc3

#### Version 3.0.4
02/17/2015

* Upgraded to CI 3.0rc2

#### Version 3.0.3
01/31/2015

* Added missing glyphicon halfling fonts
* Added favicon transparency
* Fixed favicon bug in main template files

#### Version 3.0.2
01/31/2015

* Updated site name in footers

#### Version 3.0.1
01/31/2015

* Upgraded to CI 3.0rc

#### Version 3.0.0
01/31/2015

* Started as a whole new repository (retiring former repo)
* Upgraded to CI 3.0dev
* Stripped out HMVC pattern
* Removed database navigation
* Replaced TinyMCE with Summernote WYSIWYG editor
* Lots of code cleanup and other improvements

#### Version 2.0.0
05/06/2014

Too many to list them all, but here are some of the major changes:

* Added database-driven settings administration
* Included TinyMCE WYSIWYG editor
* Included Bootstrap DatePicker and modified to work with Bootstrap 3.x
* Removed separate auth module and merged into user module
* Added user self-registration and forgot password functionality to the user module
* Removed separate login template
* Added database-driven menus with sub-menu capabilities and built-in Bootstrap formatting
* Added a CAPTCHA-protected contact page with an admin tool to view messages
* Enabled CSRF protection on all forms
* Enabled database session handling
* Tons of code cleanup and miscellaneous improvements

#### Version 1.0.1
10/10/2013

* Removed admin template includes
* Made login more secure using salt
* Modified users table to handle the login change
    + password field is now char(128)
    + added salt field char(128)

#### Version 1.0.0
10/08/2013

* Initial version

## FORK IT!

**Please [fork CI3 Fire Starter on Github](https://github.com/JasonBaier/ci3-fire-starter/fork "Fork It")
and help make it better!**


text:
/*
 * Rule: Total number of rules should not exceed x.
 */

CSSLint.addRule({

    // rule information
    id: "rules-count",
    name: "Rules Count",
    desc: "Track how many rules there are.",
    browsers: "All",

    // initialization
    init: function(parser, reporter) {
        "use strict";
        var count = 0;

        // count each rule
        parser.addListener("startrule", function() {
            count++;
        });

        parser.addListener("endstylesheet", function() {
            reporter.stat("rule-count", count);
        });
    }

});


text:
import java.util.ArrayList;
import java.lang.Throwable;

public class ALStack<Item> {

    private ArrayList<Item> a;
    private int top; // pointer to top of Stack

    public ALStack(){
        a = new ArrayList<Item>();
        top = 0;
    }

    void push(Item i){ //will only push an Item to the Stack if there is room.
            a.add(i);
            top++;
    }

    Item pop() { //will only pop an Item from the stack if there is something to pop.
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("Index " + top + " is out of bounds!!!");
        } else {
            --top;
            return a.get(top);
        }
    }

    boolean isEmpty(){ //returns true if is empty
        return top == 0;
    }

    int size(){ //returns the current number of elements in the stack and the array index
        return top;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
%BOOK_ENTITIES;
]>
<chapter id="validator-bootstrapping">
  <title>Bootstrapping</title>

  <para>We already seen in <xref linkend="section-validator-instance" /> the
  easiest way to create a <classname>Validator</classname> instance -
  <methodname>Validation.buildDefaultValidatorFactory</methodname>. In this
  chapter we have a look at the other methods in
  <classname>javax.validation.Validation</classname> and how they allow to
  configure several aspects of Bean Validation at bootstrapping time.</para>

  <para>The different bootstrapping options allow, amongst other things, to
  bootstrap any Bean Validation implementation on the classpath. Generally, an
  available provider is discovered by the <ulink
  url="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider">Java
  Service Provider</ulink> mechanism. A Bean Validation implementation
  includes the file
  <filename>javax.validation.spi.ValidationProvider</filename> in
  <filename>META-INF/services</filename>. This file contains the fully
  qualified classname of the <classname>ValidationProvider</classname> of the
  implementation. In the case of Hibernate Validator this is
  <classname>org.hibernate.validator.HibernateValidator</classname>.</para>

  <note>
    <para>If there are more than one Bean Validation implementation providers
    in the classpath and
    <methodname>Validation.buildDefaultValidatorFactory()</methodname> is
    used, there is no guarantee which provider will be chosen. To enforce the
    provider <methodname>Validation.byProvider()</methodname> should be
    used.</para>
  </note>

    <title><classname>Configuration</classname> and
    <classname>ValidatorFactory</classname></title>

    <para>There are three different methods in the Validation class to create
    a Validator instance. The easiest in shown in <xref
    linkend="example-build-default-validator-factory" />.</para>

    <example id="example-build-default-validator-factory">
      <title>Validation.buildDefaultValidatorFactory()</title>

      <programlisting language="JAVA" role="JAVA">ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();</programlisting>
    </example>

    <para>You can also use the method
    <methodname>Validation.byDefaultProvider()</methodname> which will allow
    you to configure several aspects of the created Validator instance:</para>

    <example>
      <title>Validation.byDefaultProvider()</title>

      <programlisting language="JAVA" role="JAVA">Configuration<?> config = Validation.byDefaultProvider().configure();
config.messageInterpolator(new MyMessageInterpolator())
    .traversableResolver( new MyTraversableResolver())
    .constraintValidatorFactory(new MyConstraintValidatorFactory());

ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();
</programlisting>
    </example>

    <para>We will learn more about <classname>MessageInterpolator</classname>,
    <classname>TraversableResolver</classname> and
    <classname>ConstraintValidatorFactory</classname> in the following
    sections.</para>

    <para>Last but not least you can ask for a Configuration object of a
    specific Bean Validation provider. This is useful if you have more than
    one Bean Validation provider in your classpath. In this situation you can
    make an explicit choice about which implementation to use. In the case of
    Hibernate Validator the <classname>Validator</classname> creation looks
    like:</para>

    <example>
      <title>Validation.byProvider( HibernateValidator.class )</title>

      <programlisting language="JAVA" role="JAVA">HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure();
config.messageInterpolator(new MyMessageInterpolator())
    .traversableResolver( new MyTraversableResolver())
    .constraintValidatorFactory(new MyConstraintValidatorFactory());

ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();</programlisting>
    </example>

    <para><tip>
        <para>The generated <classname>Validator</classname> instance is
        thread safe and can be cached.</para>
      </tip></para>

    <title><classname>ValidationProviderResolver</classname></title>

    <para>In the case that the Java Service Provider mechanism does not work
    in your environment or you have a special classloader setup, you are able
    to provide a custom <classname>ValidationProviderResolver</classname>. An
    example in an OSGi environment you could plug your custom provider
    resolver like seen in <xref linkend="example-provider-resolver" />.</para>

    <example id="example-provider-resolver">
      <title>Providing a custom ValidationProviderResolver</title>

      <programlisting language="JAVA" role="JAVA">Configuration<?> config = Validation.byDefaultProvider()
    .providerResolver( new OSGiServiceDiscoverer() )
    .configure();

ValidatorFactory factory = config.buildValidatorFactory();
Validator validator = factory.getValidator();
</programlisting>
    </example>

    <para>Your <classname>OSGiServiceDiscoverer</classname> must in this case
    implement the interface
    <classname>ValidationProviderResolver</classname>:</para>

    <example>
      <title>ValidationProviderResolver interface</title>

      <programlisting language="JAVA" role="JAVA">public interface ValidationProviderResolver {
    /**
     * Returns a list of ValidationProviders available in the runtime environment.
     *
     * @return list of validation providers.
     */
    List<ValidationProvider<?>> getValidationProviders();
}
</programlisting>
    </example>

    <title><classname>MessageInterpolator</classname></title>

    <para><xref linkend="section-message-interpolation" /> already discussed
    the default message interpolation algorithm. If you have special
    requirements for your message interpolation you can provide a custom
    interpolator using
    <methodname>Configuration.messageInterpolator()</methodname>. This message
    interpolator will be shared by all validators generated by the
    <classname>ValidatorFactory</classname> created from this
    <classname>Configuration</classname>. <xref
    linkend="example-message-interpolator" /> shows an interpolator (available
    in Hibernate Validator) which can interpolate the value being validated in
    the constraint message. To refer to this value in the constraint message
    you can use: <itemizedlist>
        <listitem>
          <para>${validatedValue}: this will call <methodname>String.valueOf
          </methodname>on the validated value.</para>
        </listitem>

        <listitem>
          <para>${validatedValue:<format>}: provide your own format
          string which will be passed to String.format together
          with the validated value. Refer to the javadoc of
          String.format for more information about the format
          options.</para>
        </listitem>
      </itemizedlist></para>

    <example id="example-message-interpolator">
      <title>Providing a custom MessageInterpolator</title>

      <programlisting language="JAVA" role="JAVA">Configuration<?> configuration = Validation.byDefaultProvider().configure();
ValidatorFactory factory = configuration
    .messageInterpolator(new ValueFormatterMessageInterpolator(configuration.getDefaultMessageInterpolator()))
    .buildValidatorFactory();

Validator validator = factory.getValidator();
</programlisting>
    </example>

    <tip>
      <para>It is recommended that <classname>MessageInterpolator</classname>
      implementations delegate final interpolation to the Bean Validation
      default <classname>MessageInterpolator</classname> to ensure standard
      Bean Validation interpolation rules are followed. The default
      implementation is accessible through
      <methodname>Configuration.getDefaultMessageInterpolator()</methodname>.</para>
    </tip>

      <title>ResourceBundleLocator</title>

      <para>A common use case is the ability to specify your own resource
      bundles for message interpolation. The default
      <classname>MessageInterpolator</classname> implementation in Hibernate
      Validator is called
      <classname>ResourceBundleMessageInterpolator</classname> and per default
      loads resource bundles via
      <methodname>ResourceBundle.getBundle</methodname>. However,
      <classname>ResourceBundleMessageInterpolator</classname> also allows you
      to specify a custom implementation of
      <classname>ResourceBundleLocator</classname> allowing you to provide
      your own resource bundles. <xref
      linkend="example-resource-bundle-locator" /> shows an example. In the
      example<methodname>
      HibernateValidatorConfiguration.getDefaultResourceBundleLocator</methodname>
      is used to retrieve the default
      <classname>ResourceBundleLocator</classname> which then can be passed to
      the custom implementation in order implement delegation.</para>

      <example id="example-resource-bundle-locator">
        <title>Providing a custom ResourceBundleLocator</title>

        <programlisting language="JAVA" role="JAVA">HibernateValidatorConfiguration configure = Validation.byProvider(HibernateValidator.class).configure();

ResourceBundleLocator defaultResourceBundleLocator = configure.getDefaultResourceBundleLocator();
ResourceBundleLocator myResourceBundleLocator = new MyCustomResourceBundleLocator(defaultResourceBundleLocator);

configure.messageInterpolator(new ResourceBundleMessageInterpolator(myResourceBundleLocator));
</programlisting>
      </example>

      <para>Hibernate Validator provides the following implementation of
      <classname>ResourceBundleLocator</classname> -
      <classname>PlatformResourceBundleLocator</classname> (the default) and
      <classname>AggregateResourceBundleLocator</classname>. The latter can be
      used to specify a list of resource bundle names which will get loaded
      and merged into a single resource bundle. Refer to the JavaDoc
      documentation for more information.</para>

    <title><classname>TraversableResolver</classname></title>

    <para>The usage of the <classname>TraversableResolver</classname> has so
    far not been discussed. The idea is that in some cases, the state of a
    property should not be accessed. The most obvious example for that is a
    lazy loaded property or association of a Java Persistence provider.
    Validating this lazy property or association would mean that its state
    would have to be accessed triggering a load from the database. Bean
    Validation controls which property can and cannot be accessed via the
    <classname>TraversableResolver</classname> interface (see <xref
    linkend="example-traversable-resolver" />). In the example
    HibernateValidatorConfiguration.</para>

    <example id="example-traversable-resolver">
      <title>TraversableResolver interface</title>

      <programlisting language="JAVA" role="JAVA">/**
 * Contract determining if a property can be accessed by the Bean Validation provider
 * This contract is called for each property that is being either validated or cascaded.
 *
 * A traversable resolver implementation must be thread-safe.
 *
 */
public interface TraversableResolver {
    /**
     * Determine if the Bean Validation provider is allowed to reach the property state
     *
     * @param traversableObject object hosting <code>traversableProperty</code> or null
     *                          if validateValue is called
     * @param traversableProperty the traversable property.
     * @param rootBeanType type of the root object passed to the Validator.
     * @param pathToTraversableObject path from the root object to
     *        <code>traversableObject</code>
     *        (using the path specification defined by Bean Validator).
     * @param elementType either <code>FIELD</code> or <code>METHOD</code>.
     *
     * @return <code>true</code> if the Bean Validation provider is allowed to
     *         reach the property state, <code>false</code> otherwise.
     */
     boolean isReachable(Object traversableObject,
                         Path.Node traversableProperty,
                         Class<?> rootBeanType,
                         Path pathToTraversableObject,
                         ElementType elementType);

    /**
     * Determine if the Bean Validation provider is allowed to cascade validation on
     * the bean instance returned by the property value
     * marked as <code>@Valid</code>.
     * Note that this method is called only if isReachable returns true for the same set of
     * arguments and if the property is marked as <code>@Valid</code>
     *
     * @param traversableObject object hosting <code>traversableProperty</code> or null
     *                          if validateValue is called
     * @param traversableProperty the traversable property.
     * @param rootBeanType type of the root object passed to the Validator.
     * @param pathToTraversableObject path from the root object to
     *        <code>traversableObject</code>
     *        (using the path specification defined by Bean Validator).
     * @param elementType either <code>FIELD</code> or <code>METHOD</code>.
     *
     * @return <code>true</code> if the Bean Validation provider is allowed to
     *         cascade validation, <code>false</code> otherwise.
     */
     boolean isCascadable(Object traversableObject,
                          Path.Node traversableProperty,
                          Class<?> rootBeanType,
                          Path pathToTraversableObject,
                          ElementType elementType);
}
</programlisting>
    </example>

    <para>Hibernate Validator provides two
    <classname>TraversableResolver</classname>s out of the box which will be
    enabled automatically depending on your environment. The first is the
    <classname>DefaultTraversableResolver</classname> which will always return
    true for <methodname>isReachable()</methodname> and
    <methodname>isTraversable()</methodname>. The second is the
    <classname>JPATraversableResolver</classname> which gets enabled when
    Hibernate Validator gets used in combination with JPA 2. In case you have
    to provide your own resolver you can do so again using the
    <classname>Configuration</classname> object as seen in <xref
    linkend="example-traversable-resolver-config" />.</para>

    <example id="example-traversable-resolver-config">
      <title>Providing a custom TraversableResolver</title>

      <programlisting language="JAVA" role="JAVA">Configuration<?> configuration = Validation.byDefaultProvider().configure();
ValidatorFactory factory = configuration
    .traversableResolver(new MyTraversableResolver())
    .buildValidatorFactory();

Validator validator = factory.getValidator();
</programlisting>
    </example>

    <title><classname>ConstraintValidatorFactory</classname></title>

    <para>Last but not least, there is one more configuration option to
    discuss, the <classname>ConstraintValidatorFactory</classname>. The
    default <classname>ConstraintValidatorFactory</classname> provided by
    Hibernate Validator requires a public no-arg constructor to instantiate
    <classname>ConstraintValidator</classname> instances (see <xref
    linkend="section-constraint-validator" />). Using a custom
    <classname>ConstraintValidatorFactory</classname> offers for example the
    possibility to use dependency injection in constraint implementations. The
    configuration of the custom factory is once more via the
    <classname>Configuration</classname> (<xref
    linkend="example-constraint-validator-factory" />).</para>

    <example id="example-constraint-validator-factory">
      <title>Providing a custom ConstraintValidatorFactory</title>

      <programlisting language="JAVA" role="JAVA">Configuration<?> configuration = Validation.byDefaultProvider().configure();
ValidatorFactory factory = configuration
    .constraintValidatorFactory(new IOCConstraintValidatorFactory())
    .buildValidatorFactory();

Validator validator = factory.getValidator();
</programlisting>
    </example>

    <para>The interface you have to implement is:</para>

    <example>
      <title>ConstraintValidatorFactory interface</title>

      <programlisting language="JAVA" role="JAVA">public interface ConstraintValidatorFactory {
    /**
     * @param key The class of the constraint validator to instantiate.
     *
     * @return A constraint validator instance of the specified class.
     */
     <T extends ConstraintValidator<?,?>> T getInstance(Class<T> key);
}
</programlisting>
    </example>

    <warning>
      <para>Any constraint implementation relying on
      <classname>ConstraintValidatorFactory</classname> behaviors specific to
      an implementation (dependency injection, no no-arg constructor and so
      on) are not considered portable.</para>
    </warning>

    <note>
      <para>ConstraintValidatorFactory should not cache instances as the state
      of each instance can be altered in the initialize method.</para>
    </note>

</chapter>


text:
#ifndef _CoordData_h_
#define _CoordData_h_

typedef struct _POLY_COORDDATA {
	const float* coords;
	const float* texcoords;
}POLY_COORDDATA;

#endif