text:
WithOMy=true

#| The prefix. Equal to the PREFIX environment variable
try
  if $(not $(defined PREFIX)):
    PREFIX=$(getenv PREFIX)
default
  eprintln(Specify PREFIX or prefix environment variable.)
  exit 1

# Misc tools
# ======================================================================

#|ditto.
mkdir_if_not_exists(dir) =
  if $(not $(test -e $(dir))):
    mkdir -p $(dir)
  return

# OCaml
# ========================================================================

#| OCAMLANY is either byte or native
OCAMLANY =
    if $(OCAMLC_EXISTS)
        value $(OCAMLC)
    else
        value $(OCAMLOPT)

#|Path to the OCaml library directory
OCAML_WHERE = $(shell $(OCAMLANY) -where)

#|Version without extensions
OCAML_VERSION = $(shell $(OCAMLANY) -version | sed -e 's/^\([0-9.]*\).*/\1/')

#|OMy requires OCamlFind!
USE_OCAMLFIND = true
OCAMLFIND_DESTDIR= $(shell ocamlfind printconf destdir)

OCAMLFIND_QUERY(name) =
    return $(shell ocamlfind query $(name))

#|Set NATIVE_ENABLED false locally if a project does not requre opt compilation.
NATIVE_SHARED_ENABLED = $(OCAMLOPT_EXISTS)

#|BYTE_ENABLED = true by default
BYTE_ENABLED = true

#|The default warning and errors. If you want to use different warning and error switches, use redefine the variable.
OCAMLFLAGS = -g

#|Warnings not to be printed separted with space
OCAMLWARNING_IGNORE[] = 3 4 9 40 42 44 45 48 50

#|Warnings treated as non errors
OCAMLWARNING_NON_ERROR[] = 4 9 40 42 44 45 48 50

#|If it is false, warnings do not stop the compilation even if they are listed in OCAMLWARNING_NON_ERROR
#If you are in developing something, override it to true!
OCAMLWARNING_STOP_AT_ERROR_WARNING=false

#|The maximum warning value.
# This is the maximum warning ID NOT of the current OCaml compiler,
#                                BUT of the OCaml compiler used by the author of OMyMakefile.
OCAMLWARNING_MAX= 50

#|Function to build warning switches
OCAMLWARNING_MAKE()=
    if $(OCAMLWARNING_STOP_AT_ERROR_WARNING)
        return -w $(concat -,A $(OCAMLWARNING_IGNORE)) -warn-error +1..$(concat -, $(OCAMLWARNING_MAX) $(OCAMLWARNING_NON_ERROR))
    else
        return -w $(concat -,A $(OCAMLWARNING_IGNORE)) -warn-error a

#|OMyMakefile assumes installation with .cmt files
OCAMLANNOTFLAGS = -annot -bin-annot

#|Global variable to be defined as empty
OCAMLPACKAGEFLAGS=

#|Preinstalled libraries which are always available for normal ocaml.
#
# You may want to add the required packages which are built and installed out of OMy framework:
#
#::
#
#   include OMyMakefile
#
#   OCAML_PREINSTALLED_PACKS += llvm # llvm has been installed already, independently
#
#   Subdirs()
#
# It includes "findlib" by default. If you want to build findlib in OMy framework, you have to remove it from the list.
OCAML_PREINSTALLED_PACKS[]= bigarray camlp4 dbm dynlink graphics num num-top stdlib str threads unix findlib compiler-libs compiler-libs.common compiler-libs.bytecomp compiler-libs.optcomp compiler-libs.toplevel

#|Redefinition of compiler commands
public.OCamlC() =
    value $(OCAMLFIND) $(OCAMLC) \
        $(OCAMLANNOTFLAGS) \
        $(OCAMLPACKAGEFLAGS) \
        $(LAZY_OCAMLFINDFLAGS) \
        $(PREFIXED_OCAMLPACKS) \
        $(OCAMLFLAGS) \
        $(OCAMLWARNING_MAKE) \
        $(OCAMLCFLAGS) \
        $(OCAMLPPFLAGS) \
        $(PREFIXED_OCAMLINCLUDES)
# Why we need "public." ?

public.OCamlOpt() =
    value $(OCAMLFIND) $(OCAMLOPT) $(OCAMLANNOTFLAGS) $(OCAMLPACKAGEFLAGS) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS)\
              $(OCAMLWARNING_MAKE) \
              $(OCAMLOPTFLAGS) $(OCAMLPPFLAGS) $(PREFIXED_OCAMLINCLUDES)

if $(and $(not $(NATIVE_ENABLED)) $(not $(BYTE_ENABLED)))
   err. =
       extends $(UnbuildableException)
       message = $(string $"You must turn on either NATIVE_ENABLED or BYTE_ENABLED")
       raise $(err)

#|Additional implicit rules by file extensions
# annot, cmt, cmti files
%.annot %.cmt: %.ml %.cmi
	$(OCamlC) -c $<

%.cmti: %.mli
	$(OCamlC) -c $<

#| We recommend to have OCAMLPARAM=_,g=1,annot=1,bin-annot=1,short-paths=1

#|Enable the backtrace
setenv(OCAMLRUNPARAM, b)

# Common phonies
# ==================================================================
.PHONY: all install uninstall clean veryclean

# Very clean
# ======================================================================

#| OCaml object files which are not real targets of OMake are not be
# auto-cleaned away by ``omake clean``. This is not good in some situations
# at linking.
WithOCamlVeryClean() =
    veryclean:
        rm -f *.cm* *.annot *.o *.a *.so *.exe *.byt *.opt *.run

# Directories
# =====================================================================

#| The build root directory
BIG_ROOT=$(dir .)

# Installation mark files
# =======================================================================

#| To enable the installation mark files, you must define INSTALLED path variable
# for the mark file directory like INSTALLED=$(BIG_ROOT)/installed and make sure
# the directory $(INSTALLED) exists. This preparation must be done outside of
# this OMyMakefile.

#|Returns the installation mark files of $(packs)
Installed(packs) =
  if $(defined INSTALLED)
      return $(addprefix $(INSTALLED)/, $(packs))
  else
      return $(array)

#|Create md5 sum file of files $(targets)
CreateCheckSum(pack, targets)=
    chan=$(fopen $(pack), w)
    fprintln($(chan), $(string $(targets)))
    fprintln($(chan), $(string $(digest $(targets))))
    close($(chan))

#|Create $(Installed $(pack)) file from the digests of $(targets)
CreateInstalled(pack, targets)=
    if $(defined INSTALLED)
        println(dump md5 $(INSTALLED)/$(pack))
        CreateCheckSum($(INSTALLED)/$(pack), $(targets))

# Packages
# =========================================================

#| OCaml packages required for compilation. MyCaml* functions automatically add necessary dependencies over packages in $(OCAMLPACKS).
#
# .. note:: They are also required for dependency analysis.
public.OCAMLPACKS[]=

#| CamlP4 syntax extension packages required for parsing. MyCaml* functions automatically add necessary dependencies over packages in $(CAMLP4PACKS).
public.CAMLP4PACKS[]=

# Dependencies
# =========================================================================

#|Returns packages managed by OMy framework
OMyManagedPackages(packages) =
   # need to rename camlimages.jpeg => camlimages
   packages_prefix=
   foreach(x, $(packages))
       match $(x)
       case $"^\([^.]+\).*"
          packages_prefix += $1
          export
       default
          packages_prefix += $(x)
          export
       export
   return $(set-diff $(packages_prefix), $(OCAML_PREINSTALLED_PACKS))

#|Add dependencies of OCaml compiled files (cmx, cmo, etc.) over $(files).
#
# .. note:: These functions introduce implicit rules: *you may need to export it, if you use this function in a local context.*
OCamlRequire(files) =
    %.cmx %.cmo %.cmi %.cma %.cmxa %.annot %.cmt %.cmti: $(files)
    export

#|Add dependencies of OCaml compiled files (cmx, cmo, etc.) over $(packages).
# $(packages) listed in OCAML_PREINSTALLED_PACKS are ignored.
#
# .. note:: These functions introduce implicit rules: *you may need to export it, if you use this function in a local context.*
#
# .. note:: Usually you do not need to call this function. Use OCAMLPACKS variable instead.
OCamlRequirePackages(packages) =
    required_packs = $(OMyManagedPackages $(packages))
    if $(defined INSTALLED)
      %.cmx %.cmo %.cmi %.cma %.cmxa %.annot %.cmt %.cmti: $(Installed $(required_packs))
      export
    export

#|Add dependencies of OCaml dependency analysis and build over $(packages).
# Use this for adding dependencies for CamlP4 extensions.
# $(packages) listed in OCAML_PREINSTALLED_PACKS are ignored.
#
# .. note:: These functions introduce implicit rules: *you may need to export it, if you use this function in a local context.*
#
# .. note:: Usually you do not need to call this function. Use CAML4PACKS variable instead.
OCamlRequireCamlP4Packages(packages) =
    required_packs = $(OMyManagedPackages $(packages))
    if $(defined INSTALLED)
      .SCANNER: scan-ocaml-%: $(Installed $(required_packs))
      %.cmx %.cmo %.cmi %.cma %.cmxa %.annot : $(Installed $(required_packs))
      export
    export

#|``omake xxx.auto.mli`` generates .mli file from xxx.ml
%.auto.mli: %.ml
	$(OCamlC) -i -c $< > $@

# Build rules
# ==========================================================

public.OCamlLibrary(name, files) =
   # XXX: JYH: these variables should be marked private in 0.9.9
   protected.name = $(file $(name))

   protected.OFILES   = $(addsuffix $(EXT_OBJ), $(files))
   protected.CMOFILES = $(addsuffix .cmo, $(files))
   protected.CMXFILES = $(addsuffix .cmx, $(files))

   protected.CLIB      = $(file $(name)$(EXT_LIB))
   protected.BYTELIB   = $(file $(name).cma)
   protected.NATIVELIB = $(file $(name).cmxa)
   protected.NATIVESHAREDLIB = $(file $(name).cmxs)

   #
   # Link commands
   #
   $(BYTELIB): $(CMOFILES)
        $(OCAMLFIND) $(OCAMLLINK) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) $(OCAMLCFLAGS) \
                $(OCAML_LIB_FLAGS) -a -o $@ $(OCamlLinkSort $(CMOFILES))

   $(NATIVELIB) $(CLIB): $(CMXFILES) $(OFILES)
        $(OCAMLFIND) $(OCAMLOPTLINK) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) $(OCAMLOPTFLAGS) \
                $(OCAML_LIB_FLAGS) -a -o $(NATIVELIB) $(OCamlLinkSort $(CMXFILES))

   $(NATIVESHAREDLIB): $(CMXFILES) $(OFILES)
         $(OCAMLFIND) $(OCAMLOPTLINK) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) $(OCAMLOPTFLAGS) \
                 $(OCAML_LIB_FLAGS) -shared -o $(NATIVESHAREDLIB) $(OCamlLinkSort $(CMXFILES))

   return $(array $(if $(NATIVE_ENABLED), $(NATIVELIB)), \
                  $(if $(NATIVE_ENABLED), $(CLIB)), \
                  $(if $(NATIVE_SHARED_ENABLED), $(NATIVESHAREDLIB)), \
                  $(if $(BYTE_ENABLED), $(BYTELIB)))

public.OCAML_BYTE_LINK_FLAGS =

public.OCamlPackage(name, files) =
   # XXX: JYH: these variables should be marked private in 0.9.9
   protected.OFILES   = $(addsuffix $(EXT_OBJ), $(files))
   protected.CMOFILES = $(addsuffix .cmo, $(files))
   protected.CMXFILES = $(addsuffix .cmx, $(files))

   protected.OBJ       = $(file $(name)$(EXT_OBJ))
   protected.CMO       = $(file $(name).cmo)
   protected.CMX       = $(file $(name).cmx)
   protected.CMI       = $(file $(name).cmi)
   protected.MLI       = $(file $(name).mli)

   protected.BYTE_TARGETS   = $(CMO)
   protected.NATIVE_TARGETS = $(CMX) $(OBJ)

   if $(BYTE_ENABLED)
      BYTE_TARGETS += $(file $(name).cmt)
      export
   else
      NATIVE_TARGETS += $(file $(name).cmt)
      export
   export

   protected.TARGETS = $(CMI)
   if $(NATIVE_ENABLED)
       TARGETS += $(NATIVE_TARGETS)
       export

   if $(BYTE_ENABLED)
       TARGETS += $(BYTE_TARGETS)
       export

   #
   # Link commands
   #
   protected.BYTE_DEPS = $(CMOFILES)
   $(BYTE_TARGETS): $(CMOFILES)
      section rule
         if $(or $(NATIVE_ENABLED), $(target-exists $(MLI)))
             BYTE_DEPS += $(CMI)
             export
         else
             BYTE_TARGETS += $(CMI)
             export
         $(BYTE_TARGETS): $(BYTE_DEPS)
            $(OCAMLFIND) $(OCAMLC) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) \
                $(OCAMLCFLAGS) $(OCAML_LIB_FLAGS) -pack $(OCAMLANNOTFLAGS) -o $(CMO) $(OCamlLinkSort $(CMOFILES))

   protected.NATIVE_DEPS = $(CMXFILES) $(OFILES)
   $(NATIVE_TARGETS): $(NATIVE_DEPS)
      section rule
         if $(target-exists $(MLI))
            NATIVE_DEPS += $(CMI)
            export
         else
            NATIVE_TARGETS += $(CMI)
            export
         $(NATIVE_TARGETS): $(NATIVE_DEPS)
            $(OCAMLFIND) $(OCAMLOPTLINK) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) \
                $(OCAMLOPTFLAGS) $(OCAML_LIB_FLAGS) -pack $(OCAMLANNOTFLAGS) -o $(CMX) $(OCamlLinkSort $(CMXFILES))

   $(CMI):
      section rule
         if $(target-exists $(MLI))
            $(CMI): $(MLI) :scanner: scan-ocaml-$(name).mli
                $(OCamlC) -c $<
         elseif $(NATIVE_ENABLED)
            $(NATIVE_TARGETS) $(CMI): $(NATIVE_DEPS)
               $(OCAMLFIND) $(OCAMLOPTLINK) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) \
                   $(OCAMLOPTFLAGS) $(OCAML_LIB_FLAGS) -pack -o $(CMX) $(OCamlLinkSort $(CMXFILES))
         else
            $(BYTE_TARGETS) $(CMI): $(BYTE_DEPS)
               $(OCAMLFIND) $(OCAMLC) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) \
                   $(OCAMLCFLAGS) $(OCAML_LIB_FLAGS) -pack -o $(CMO) $(OCamlLinkSort $(CMOFILES))

   return $(TARGETS)

# Add implicit dependencies over the packages declared in OCAMLPACKS and CAMLP4PACKS
# If this function is used in a local scope, you may want to export.
AddLocalOCamlPackageDependencies() =
  # We make sure the required libraries are installed
  OCamlRequirePackages($(OCAMLPACKS)) # must be exported!
  OCamlRequireCamlP4Packages($(OCAMLPACKS) $(CAMLP4PACKS))
  export

#| Add a rule for OCaml package $(library_name).cmo, $(library_name).cmx and etc.
#     library_name
#         target package name
#     files
#         ML module names (without .ml)
#     cmodules
#         C source files (without .c)
#     linkopts
#         C library link option (without OCaml -cclib options)
#
#  You can specify MyOCamlPackageExtras before using this function to install files out of the scope of this rule.
#
#  If $(NO_INSTALL) is defined, omake install does not install the package
#
#  Example::
#
#      MyOCamlPackage(foo, alpha beta, $(EMPTY), $(EMPTY))
#
#  Todo: external C library
MyOCamlPackage(library_name, files, cmodules, linkopts) =
  WithOCamlVeryClean()
  AddLocalOCamlPackageDependencies()
  export # The above thing is local: need to be exported

  CSTUBS=$(addsuffix .o,$(cmodules))
  CMO_S=$(addsuffix .cmo,$(library_name))
  CMX_S=$(addsuffix .cmx,$(library_name))
  CMA=$(library_name).cma
  CMXA=$(library_name).cmxa
  CMXS=$(library_name).cmxs

  if $(not $(defined PACKAGE_NAME))
    findlib_name=$(lowercase $(library_name))
    export
  else
    findlib_name=$(PACKAGE_NAME)
    export

  if $(not $(defined MyOCamlPackageExtras))
      MyOCamlPackageExtras[]=
      export

  CSTUBLIBRARIES=
  if $(not $(equal $(cmodules), $(EMPTY)))
      CSTUBLIBRARIES= dll$(library_name).so lib$(library_name).a
      export

  # CR jfuruse: I guess we do not need the following
  # export # export the implicit rule above

  .PHONY: install-lib
  install-lib: $(library_name).cmo $(library_name).cmx $(library_name).cma $(library_name).cmxa $(MyOCamlPackageExtras)

  $(CMA) $(CMXA) $(CMXS) $(library_name).a $(CSTUBLIBRARIES) : $(CSTUBS) $(CMO_S) $(CMX_S)
      if $(not $(equal $(cmodules), $(EMPTY)))
          ocamlmklib -verbose -o $(library_name) $(CSTUBS) $(linkopts) $(CMO_S) $(CMX_S)
          $(OCamlOpt) -shared -o $(CMXS) $(CMX_S) # CR jfuruse: right?
      else
          $(OCamlC) -a -o $(CMA) $(CMO_S)
          $(OCamlOpt) -a -o $(CMXA) $(CMX_S)
          $(OCamlOpt) -shared -o $(CMXS) $(CMX_S)

  ## the followings are necessary for packing

  OCAMLPACKAGEFLAGS += -for-pack $(capitalize $(library_name))
  # export OCAMLPACKAGEFLAGS

  ## build rule

  .DEFAULT: $(OCamlPackage $(library_name), $(files))

  ## clean
  AutoClean()
  clean:
	rm -f $(library_name).cmt

  ## install

  # CR jfuruse: x.cmi is required if x.mli does not exist!
  sub_targets[]= $(glob i, *.mli) $(library_name).cmi $(library_name).cmo $(library_name).cmx $(library_name).cma $(library_name).cmxa $(library_name).cmxs $(library_name).o $(library_name).a $(CSTUBLIBRARIES) $(MyOCamlPackageExtras)

  sub_targets[]+= $(library_name).cmt

  targets[]= META $(sub_targets)

  if $(defined SUB_INSTALL)
    install: $(sub_targets) $(SUB_INSTALL)
      mkdir_if_not_exists($(SUB_INSTALL))
      /bin/rm -rf $(SUB_INSTALL)/$(findlib_name)
      mkdir $(SUB_INSTALL)/$(findlib_name)
      cp $(sub_targets) $(SUB_INSTALL)/$(findlib_name)
    export

  if $(and $(not $(defined NO_INSTALL)) $(not $(defined SUB_INSTALL)))
    if $(defined INSTALLED)
      $(Installed $(findlib_name)): $(targets)
        $(OCAMLFIND) remove $(findlib_name)
        section:
              $(OCAMLFIND) install $(findlib_name) $(targets)
              CreateInstalled($(findlib_name), $(targets))

      install: $(Installed $(findlib_name))

      uninstall:
        rm -f $(Installed $(findlib_name))
        $(OCAMLFIND) remove $(findlib_name)
      export
    else
      install: $(targets)
        $(OCAMLFIND) remove $(findlib_name)
        $(OCAMLFIND) install $(findlib_name) $(targets)

      uninstall:
	$(OCAMLFIND) remove $(findlib_name)
      export
    export

############################################################## build ocaml exec

MyOCamlGenericProgram(name, files) =
  WithOCamlVeryClean()
  AddLocalOCamlPackageDependencies()
  export # The above thing is local: need to be exported

  # We must write these two separately, or something messy happens!
  $(name).run: $(Installed $(OMyManagedPackages $(OCAMLPACKS)))
  $(name).opt: $(Installed $(OMyManagedPackages $(OCAMLPACKS)))

  # CR jfuruse: forgot to add the deps over the packages!
  .DEFAULT: $(OCamlProgram $(name), $(files))

  # The following clean the files twice if MyOCamlPackge coexists,
  # but who cases ?
  AutoClean()

#| Add a rule to build a test program $(name)
#      name
#          Name of the program
#      files
#          OCaml module names (without .ml)
MyOCamlTestProgram(name, files) =
  # We need -linkall not to miss any module for test
  OCAML_LINK_FLAGS += -linkall
  MyOCamlGenericProgram($(name), $(files))

#| Add a rule to build a program $(name)
#      name
#          Name of the program
#      files
#          OCaml module names (without .ml)
#  In addition to MyOCamlTestProgram, the binary is installed by omake install
MyOCamlProgram(name, files) =
  WithOCamlVeryClean()
  MyOCamlGenericProgram($(name), $(files))
  export # The above thing is local: need to be exported # really?

  if $(not $(defined NO_INSTALL))
    install: $(name)$(EXE) $(name).run $(name).opt
      install $(name)$(EXE) $(name).run $(name).opt $(PREFIX)/bin
    uninstall:
      rm -f $(PREFIX)/bin/$(name)$(EXE) $(PREFIX)/bin/$(name).run $(PREFIX)/bin/$(name).opt
    export

MyOCamlApplication(name, files) =
  MyOCamlProgram($(name), $(files))

# This does not install exe
MyOCamlPPX(name, files) =
  WithOCamlVeryClean()
  MyOCamlGenericProgram($(name), $(files))
  export
  TARGETS[]=$(name).opt $(name).run $(name)$(EXE)
  return $(TARGETS)

# This does not install exe
MyOCamlPPXTargets(name) =
  return $(name).run $(name).opt $(name)$(EXE)

MyOCamlFindPackage(findlib_name, files) =
    targets[]= META $(files)

    if $(defined INSTALLED)
      $(Installed $(findlib_name)): $(targets)
        $(OCAMLFIND) remove $(findlib_name)
        section:
              $(OCAMLFIND) install $(findlib_name) $(targets)
              CreateInstalled($(findlib_name), $(targets))

      install: $(Installed $(findlib_name))

      uninstall:
        rm -f $(Installed $(findlib_name))
        $(OCAMLFIND) remove $(findlib_name)
      export
    else
      install: $(targets)
        $(OCAMLFIND) remove $(findlib_name)
        $(OCAMLFIND) install $(findlib_name) $(targets)

      uninstall:
	$(OCAMLFIND) remove $(findlib_name)
      export
    export

#| Add a rule to build a toplevel $(name)
#      name
#          Name of the program
#      files
#          OCaml module names (without .ml)
OCamlTop(name, files) =
   # XXX: JYH: these variables should be marked private in 0.9.9
   protected.CMOFILES  = $(addsuffix .cmo, $(files))
   # protected.CMXFILES  = $(addsuffix .cmx, $(files))
   # protected.OFILES    = $(addsuffix $(EXT_OBJ), $(files))

   protected.CMAFILES  = $(addsuffix .cma,  $(OCAML_LIBS))
   # protected.CMXAFILES = $(addsuffix .cmxa, $(OCAML_LIBS))
   protected.ARFILES   = $(addsuffix $(EXT_LIB), $(OCAML_LIBS))
   protected.CMA_OTHER_FILES = $(addsuffix .cma, $(OCAML_OTHER_LIBS))
   # protected.CMXA_OTHER_FILES = $(addsuffix .cmxa, $(OCAML_OTHER_LIBS))

   protected.CLIBS = $(addsuffix $(EXT_LIB), $(OCAML_CLIBS))

   protected.name = $(file $(name))

   protected.PROG     = $(file $(name)$(EXE))
   protected.BYTEPROG = $(file $(name).run)
   # protected.OPTPROG  = $(file $(name).opt)

   #
   # Rules to build byte-code and native targets
   #
   $(BYTEPROG): $(CMAFILES) $(CMOFILES) $(CLIBS)
        $(OCAMLFIND) $(OCAMLMKTOP) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLFLAGS) $(OCAMLCFLAGS)\
                $(OCAMLWARNING_MAKE) \
                $(PREFIXED_OCAMLINCLUDES) $(OCAML_BYTE_LINK_FLAGS)\
                -o $@ $(CMA_OTHER_FILES) $(CMAFILES) $(OCamlLinkSort $(CMOFILES))\
                $(CLIBS) $(OCAML_LINK_FLAGS)

   $(PROG): $(BYTEPROG)
        ln-or-cp $< $@

   return $(array $(PROG), $(BYTEPROG))

MyOCamlTop(name, files) =
  WithOCamlVeryClean()
  AddLocalOCamlPackageDependencies()
  export # The above thing is local: need to be exported

  $(name): $(Installed $(OMyManagedPackages $(OCAMLPACKS)))

  # CR jfuruse: forgot to add the deps over the packages!
  .DEFAULT: $(OCamlTop $(name), $(files))

  # The following clean the files twice if MyOCamlPackge coexists,
  # but who cases ?
  AutoClean()
  export # The above thing is local: need to be exported

  if $(not $(defined NO_INSTALL))
    install: $(name) $(name).run
      install $(name) $(name).run $(PREFIX)/bin
    uninstall:
      rm -f $(PREFIX)/bin/$(name) $(PREFIX)/bin/$(name).run
    export

#|  Add rules to build OCaml library $(name)
#        name
#            Name of the library
#        files
#            OCaml module name (without .ml)
#
#   .. note :: Probably you should use MyOCamlPackage
MyOCamlLibrary(library_name, files) =
  WithOCamlVeryClean()
  AddLocalOCamlPackageDependencies()
  protected.CMIFILES = $(addsuffix .cmi, $(files))
  targets = $(OCamlLibrary $(library_name), $(files)) $(CMIFILES) $(glob i, *.mli)

  if $(not $(defined PACKAGE_NAME))
    findlib_name=$(lowercase $(library_name))
    export
  else
    findlib_name=$(PACKAGE_NAME)
    export

  .DEFAULT: $(targets)

  export # The above thing is local: need to be exported

  if $(not $(defined NO_INSTALL))
    targets[] += META
    cmts =  $(addsuffix .cmt,  $(removesuffix $(glob i, *.cmo)))
    cmts += $(addsuffix .cmti, $(removesuffix $(glob i, *.mli)))
    if $(defined INSTALLED)
      $(Installed $(findlib_name)): $(targets)
        $(OCAMLFIND) remove $(findlib_name)
        section:
              $(OCAMLFIND) install $(findlib_name) $(targets) $(cmts)
              CreateInstalled($(findlib_name), $(targets))

      install: $(Installed $(findlib_name))

      uninstall:
        rm -f $(Installed $(findlib_name))
        $(OCAMLFIND) remove $(findlib_name)
      export
    else
      install: $(targets)
        $(OCAMLFIND) remove $(findlib_name)
        $(OCAMLFIND) install $(findlib_name) $(targets) $(cmts)

      uninstall:
	$(OCAMLFIND) remove $(findlib_name)
      export
    export

  # The following clean the files twice if MyOCamlPacakge coexists,
  # but who cases ?
  AutoClean()

# Auto clean
# ====================================================================

#| Install clean command which cleans all the target files exists under the directory. Use with care.
AutoClean()=
    .PHONY: clean
    clean:
        rm -f $(filter-proper-targets $(ls R, .))

# Subdir traversal
# =====================================================================

#| Recursively traverse the subdirs except $(dirs)
Subdirs_except(dirs) =
  # println(PWD: $(shell pwd))

  # need to export since .SUBDIRS is evaluated in the global scope
  export VISIT_SUBDIRS

  sub_omakefiles = $(glob i, */OMakefile)
  subdirs = $(sub_omakefiles.map $(dirname))

  VISIT_SUBDIRS=$(set-diff $(subdirs), $(dirs))

  # println(SUBDIRS: $(string $(VISIT_SUBDIRS)))

  # The rule
  .SUBDIRS: $(VISIT_SUBDIRS)

#| Recursively traverse all the subdirs
Subdirs() =
  Subdirs_except($(array))

#| Recursively traverse the given subdirs $(dirs)
Subdirs_only(dirs) =
 .SUBDIRS: $(dirs)

# Dependency dot files for Graphviz
# ======================================================================

#| Add a rule for ``depend.dot`` for a dependency graph of OCaml files in the current directory
Dot() =
	depend.dot: $(ls *.ml *.mli)
	    $(OCAMLFIND) ocamldoc -I +threads $(OCAMLPACKAGEFLAGS) $(LAZY_OCAMLFINDFLAGS) $(PREFIXED_OCAMLPACKS) $(OCAMLPPFLAGS) $(PREFIXED_OCAMLINCLUDES) -dot -dot-include-all -dot-reduce $+ -o $@

#| filter list
#  example::
#     is_url(file) =
#       match $(file)
#       case $'://'
#         return true
#       default
#         return false
#
#     DOWNLOAD_URLS[]=$(list_filter $(fun x, $(is_url $(x))), $(URLS))
list_filter(pred, list) =
  result=
  foreach(x, $(list))
    if $(apply $(pred), $(x))
      result+=$(x)
      export
    export
  return $(result)

#| Obtain files installed as PACK
GET_OCAMLFIND_OBJS(pack)=
    return $(Files $(OCAMLFIND_DESTDIR)/$(pack))

# Pa_ounit test
# =======================================================================

#| Test with Pa_ounit. Pretty version dependent.
# Thinking from the implementation Pa_ounit_lib.Runtime, it should be
# pretty unstable in future releases of Pa_ounit. Sigh.

MyOCamlOUnitTest(LIB) =
    name=ounittest_$(LIB)
    $(name).ml:
        section:
            chan=$(fopen $@, w)
            fprintln($(chan), module M = $(capitalize $(LIB)))
            fprintln($(chan), let \(\) = Pa_ounit_lib.Runtime.summarize \(\))
            close($(chan))

    section:
        OCAML_LIBS=$(LIB)
        MyOCamlTestProgram($(name), $(name))

    inline_tests.log: $(name)
        println(Check inline_tests.log for test results)
        ./$(name) inline-test-runner $(capitalize $(LIB)) -verbose -log -strict

    .PHONY:test

    test: inline_tests.log

WithMerlin() =
  .merlin:
    section:
      chan=$(fopen $@, w)
      fprintln($(chan), "PKG $(string $(OCAMLPACKS))")
      foreach(x, $(OCAMLINCLUDES))
        fprintln($(chan), "S $(x)")
      fprintln($(chan), FLG $(OCAMLWARNING_MAKE))
      close($(chan))
  .DEFAULT: .merlin
  export


text:
package br.com.objectos.concurrent;

/**
 * A {@code CpuWorker} that can be started and stopped.
 *
 * @since 2
 */
public abstract class CpuWorkerService extends AbstractConcurrentService implements CpuWorker {

  /**
   * Sole constructor
   */
  protected CpuWorkerService() {}

}

redpajama_set_name: RedPajamaGithub


text:
title: "Merb: flash"
lang: pl
---

UPDATE: Zamiast calej zabawy - plugin [merb-flash](http://github.com/teamon/merb-flash/tree/master) :)

Kontynuując [serię](http://teamon.eu/2008/10/31/merb-kolorowy-logger/) o sztuczkach w [Merbie](http://merbivore.com)
tym razem przedstawię coś, czego najbardziej mi zabrakło - railsowego flasha.

Twórcy Merba zrezygnowali z takiego rozwiązania, i postawili na dodatkowy parametr `_message`
przekazywany w url jako zakodowany ciąg znaków.

```ruby
redirect resource(@product), :message => "Product was successfully created"
```

Jednak według mnie to rozwiązanie jest po prostu brzydkie. Podpatrując nieco z pluginu
[merb\_has\_flash](http://github.com/ivey/merb_has_flash/tree/master) zamieniłem ów `:message`
na wersję wykorzystującą sesje bez zmieniania API.

```ruby
# lib/flash.rb

class Flash
  def initialize(*args)
    @attrs = Mash.new(*args)
    @keepers = []
  end

  def []=(key, value)
    @attrs[key] = value
    keep key
  end

  def update(hash)
    @attrs.update(hash)
    hash.keys.each {|key| keep key}
  end

  def method_missing(method_name, *args, &block)
    @attrs.send(method_name, *args, &block)
  end

  def keep(key)
    key = key.to_s
    @keepers << key unless @keepers.include?(key)
  end

  def sweep
    @attrs.keys.each {|key| @attrs.delete(key) unless @keepers.include?(key)}
    @keepers = []
  end
end

class Merb::Request
  def message
    session['flash'] || {}
  end
end

class Merb::Controller
  after :sweep_flash
  def sweep_flash
    session["flash"].sweep if session["flash"]
  end

  def redirect(url, opts = {})
    default_redirect_options = { :message => nil, :permanent => false }
    opts = default_redirect_options.merge(opts)
    if opts[:message]
      opts[:message] = {:notice => opts[:message]} unless opts[:message].is_a?(Hash)
      session['flash'] = Flash.new unless session['flash'].is_a?(Flash)
      session['flash'].update(opts[:message])
    end
    self.status = opts[:permanent] ? 301 : 302
    Merb.logger.info("Redirecting to: #{url} (#{self.status})")
    headers['Location'] = url
    "<html><body>You are being <a href=\"#{url}\">redirected</a>.</body></html>"
  end
end
```

Jak już wspomniałem, sposób użycia się w zasadzie nie zmienia. Jedyną zmianą jest to, że gdy podamy jako parametr `:message` ciąg znaków to zamieni się on na `{:notice => "nasza wiadomosc"}`. Dzięki temu nie musimy pisać: `redirect resource(@product), :message => {:notice => "Product was successfully created" aby odróżnić potem typ wiadomości. Jeśli chcemy wyświetlić error to nic nie stoi na przeszkodzie aby zapisać: `redirect url(:default), :message => {:error => "Product not found"}`

Wyświetlanie wiadomości podobnie jak w Rails: (wersja haml)
```haml
- message.each_pair do |type, msg|
  = tag :div, msg, :class => type.to_s, :id => "flash"
```

W celu załadowania tej "poprawki" dopisujemy do pliku `conifg/init.rb` `require "lib/flash.rb"` lub `Merb.push_path(:lib, Merb.root / "lib")`
 Przy drugim sposobie zostaną automatycznie załadowane wszystkie pliki z katalogu `lib`

Warto jeszcze wspomnieć, że patch działa razem z merb-auth.

Do zobaczenia w następnym odcinku :P


text:
package com.azure.resourcemanager.mediaservices.implementation;

import com.azure.core.util.Context;
import com.azure.resourcemanager.mediaservices.fluent.models.PrivateEndpointConnectionInner;
import com.azure.resourcemanager.mediaservices.models.PrivateEndpoint;
import com.azure.resourcemanager.mediaservices.models.PrivateEndpointConnection;
import com.azure.resourcemanager.mediaservices.models.PrivateEndpointConnectionProvisioningState;
import com.azure.resourcemanager.mediaservices.models.PrivateLinkServiceConnectionState;

public final class PrivateEndpointConnectionImpl
    implements PrivateEndpointConnection, PrivateEndpointConnection.Definition, PrivateEndpointConnection.Update {
    private PrivateEndpointConnectionInner innerObject;

    private final com.azure.resourcemanager.mediaservices.MediaServicesManager serviceManager;

    public String id() {
        return this.innerModel().id();
    }

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

    public String type() {
        return this.innerModel().type();
    }

    public PrivateEndpoint privateEndpoint() {
        return this.innerModel().privateEndpoint();
    }

    public PrivateLinkServiceConnectionState privateLinkServiceConnectionState() {
        return this.innerModel().privateLinkServiceConnectionState();
    }

    public PrivateEndpointConnectionProvisioningState provisioningState() {
        return this.innerModel().provisioningState();
    }

    public String resourceGroupName() {
        return resourceGroupName;
    }

    public PrivateEndpointConnectionInner innerModel() {
        return this.innerObject;
    }

    private com.azure.resourcemanager.mediaservices.MediaServicesManager manager() {
        return this.serviceManager;
    }

    private String resourceGroupName;

    private String accountName;

    private String name;

    public PrivateEndpointConnectionImpl withExistingMediaservice(String resourceGroupName, String accountName) {
        this.resourceGroupName = resourceGroupName;
        this.accountName = accountName;
        return this;
    }

    public PrivateEndpointConnection create() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getPrivateEndpointConnections()
                .createOrUpdateWithResponse(resourceGroupName, accountName, name, this.innerModel(), Context.NONE)
                .getValue();
        return this;
    }

    public PrivateEndpointConnection create(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getPrivateEndpointConnections()
                .createOrUpdateWithResponse(resourceGroupName, accountName, name, this.innerModel(), context)
                .getValue();
        return this;
    }

    PrivateEndpointConnectionImpl(
        String name, com.azure.resourcemanager.mediaservices.MediaServicesManager serviceManager) {
        this.innerObject = new PrivateEndpointConnectionInner();
        this.serviceManager = serviceManager;
        this.name = name;
    }

    public PrivateEndpointConnectionImpl update() {
        return this;
    }

    public PrivateEndpointConnection apply() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getPrivateEndpointConnections()
                .createOrUpdateWithResponse(resourceGroupName, accountName, name, this.innerModel(), Context.NONE)
                .getValue();
        return this;
    }

    public PrivateEndpointConnection apply(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getPrivateEndpointConnections()
                .createOrUpdateWithResponse(resourceGroupName, accountName, name, this.innerModel(), context)
                .getValue();
        return this;
    }

    PrivateEndpointConnectionImpl(
        PrivateEndpointConnectionInner innerObject,
        com.azure.resourcemanager.mediaservices.MediaServicesManager serviceManager) {
        this.innerObject = innerObject;
        this.serviceManager = serviceManager;
        this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups");
        this.accountName = Utils.getValueFromIdByName(innerObject.id(), "mediaservices");
        this.name = Utils.getValueFromIdByName(innerObject.id(), "privateEndpointConnections");
    }

    public PrivateEndpointConnection refresh() {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getPrivateEndpointConnections()
                .getWithResponse(resourceGroupName, accountName, name, Context.NONE)
                .getValue();
        return this;
    }

    public PrivateEndpointConnection refresh(Context context) {
        this.innerObject =
            serviceManager
                .serviceClient()
                .getPrivateEndpointConnections()
                .getWithResponse(resourceGroupName, accountName, name, context)
                .getValue();
        return this;
    }

    public PrivateEndpointConnectionImpl withPrivateEndpoint(PrivateEndpoint privateEndpoint) {
        this.innerModel().withPrivateEndpoint(privateEndpoint);
        return this;
    }

    public PrivateEndpointConnectionImpl withPrivateLinkServiceConnectionState(
        PrivateLinkServiceConnectionState privateLinkServiceConnectionState) {
        this.innerModel().withPrivateLinkServiceConnectionState(privateLinkServiceConnectionState);
        return this;
    }
}


text:
namespace gameplay
{

PhysicsVehicleWheel::PhysicsVehicleWheel(Node* node, const PhysicsCollisionShape::Definition& shape, const PhysicsRigidBody::Parameters& parameters)
    : PhysicsCollisionObject(node), _host(NULL), _indexInHost(0)
    , _initialOffset( 0.0f, 0.0f, 0.0f ), _positionDelta( 0.0f, 0.0f, 0.0f )
{
    findAncestorAndBind();
}

PhysicsVehicleWheel::PhysicsVehicleWheel(Node* node)
    : PhysicsCollisionObject(node), _host(NULL), _indexInHost(0)
{
    findAncestorAndBind();
}

PhysicsVehicleWheel* PhysicsVehicleWheel::create(Node* node, Properties* properties)
{
    PhysicsVehicleWheel* wheel = new PhysicsVehicleWheel(node);

    // Load the defined wheel parameters.
    properties->rewind();
    Vector3 v;
    const char* name;
    while ((name = properties->getNextProperty()) != NULL)
    {
        if (strcmp(name, "steerable") == 0)
        {
            wheel->setSteerable(properties->getBool(name));
        }
        else if (strcmp(name, "wheelDirection") == 0 && properties->getVector3(name, &v))
        {
            wheel->setWheelDirection(v);
        }
        else if (strcmp(name, "wheelAxle") == 0 && properties->getVector3(name, &v))
        {
            wheel->setWheelAxle(v);
        }
        else if (strcmp(name, "strutConnectionOffset") == 0 && properties->getVector3(name, &v))
        {
            wheel->setStrutConnectionOffset(v);
        }
        else if (strcmp(name, "strutRestLength") == 0)
        {
            wheel->setStrutRestLength(properties->getFloat(name));
        }
        else if (strcmp(name, "strutTravelMax") == 0)
        {
            wheel->setStrutTravelMax(properties->getFloat(name));
        }
        else if (strcmp(name, "strutStiffness") == 0)
        {
            wheel->setStrutStiffness(properties->getFloat(name));
        }
        else if (strcmp(name, "strutDampingCompression") == 0)
        {
            wheel->setStrutDampingCompression(properties->getFloat(name));
        }
        else if (strcmp(name, "strutDampingRelaxation") == 0)
        {
            wheel->setStrutDampingRelaxation(properties->getFloat(name));
        }
        else if (strcmp(name, "strutForceMax") == 0)
        {
            wheel->setStrutForceMax(properties->getFloat(name));
        }
        else if (strcmp(name, "frictionBreakout") == 0)
        {
            wheel->setFrictionBreakout(properties->getFloat(name));
        }
        else if (strcmp(name, "wheelRadius") == 0)
        {
            wheel->setWheelRadius(properties->getFloat(name));
        }
        else if (strcmp(name, "rollInfluence") == 0)
        {
            wheel->setRollInfluence(properties->getFloat(name));
        }
        else
        {
            // Ignore this case (we've already parsed the rigid body parameters).
        }
    }

    return wheel;
}

PhysicsVehicleWheel::~PhysicsVehicleWheel()
{
}

btCollisionObject* PhysicsVehicleWheel::getCollisionObject() const
{
    GP_ASSERT(_host);

    return _host->getCollisionObject();
}

PhysicsCollisionObject::Type PhysicsVehicleWheel::getType() const
{
    return PhysicsCollisionObject::VEHICLE_WHEEL;
}

void PhysicsVehicleWheel::setEnabled(bool enable)
{
    GP_ERROR("Operation not supported (PhysicsVehicleWheel::setEnabled(bool)). Use host vehicle instead.");
}

void PhysicsVehicleWheel::findAncestorAndBind()
{
    GP_ASSERT(getNode());

    // Search for the first PhysicsVehicle that shares a common ancestor, and
    // bind with it. The following code performs a naive search; nothing more
    // sophisticated is deemed necessary because:
    // (a) The root of the scene is NOT a node
    // (b) Scene graphs tend to be relatively flat.
    //
    // The search ends when a vehicle is found or n is null:
    // 1: Let n = this node
    // 2: Visit each sibling of n and perform a breadth-first search of its descendants
    // 3: Let n = the parent of n
    // 4: Go to 2.
    PhysicsVehicle* host = NULL;
    Node* m;
    for (Node* n = getNode(); n && !host; n = n->getParent())
    {
        // Visit previous siblings starting with n
		for (m = n; m && !host; m = m->getPreviousSibling())
        {
            host = findVehicle(m);
        }

        // Visit siblings after n
        for (m = n->getNextSibling(); m && !host; m = m->getNextSibling())
        {
            host = findVehicle(m);
        }
    }

    // Note: Currently this method is silent on failure to find a host.
    if (host)
    {
        host->addWheel(this);
        _initialOffset = _node->getTranslation() - host->_node->getTranslation();
    }
}

PhysicsVehicle* PhysicsVehicleWheel::findVehicle(Node* node)
{
    PhysicsCollisionObject* collisionObject = node->getCollisionObject();
    if (collisionObject && collisionObject->getType() == PhysicsCollisionObject::VEHICLE)
    {
        return static_cast<PhysicsVehicle*>(collisionObject);
    }

    PhysicsVehicle* result = NULL;
    for (Node* p = node->getFirstChild(); p && !result; p = p->getNextSibling())
    {
        result = findVehicle(p);
    }
    return result;
}

void PhysicsVehicleWheel::setHost(PhysicsVehicle* host, unsigned int indexInHost)
{
    _host = host;
    _indexInHost = indexInHost;
}

void PhysicsVehicleWheel::addToVehicle(btRaycastVehicle* vehicle)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->getWheelCount() == vehicle->getNumWheels() + 1);

    // Use safe defaults for now. Properties are assigned elsewhere.
    btRaycastVehicle::btVehicleTuning tuning;
    vehicle->addWheel(
        btVector3(0, 0, 0),
        btVector3(0, -1, 0),
        btVector3(-1, 0, 0),
        0.6f,
        0.5f,
        tuning,
        false);
}

void PhysicsVehicleWheel::transform(Node* node) const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_node);

    node->setRotation(_orientation);

    // Use only the component parallel to the defined strut line
    Vector3 strutLine;
    getWheelDirection(&strutLine);
    _host->_node->getMatrix().transformVector(&strutLine);
    Vector3 wheelPos;
    getWheelPos(&wheelPos);
    node->setTranslation(wheelPos + strutLine*(strutLine.dot(_positionDelta) / strutLine.lengthSquared()));
}

void PhysicsVehicleWheel::update(float elapsedTime)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    const btTransform& trans = _host->_vehicle->getWheelInfo(_indexInHost).m_worldTransform;
    const btQuaternion& rot = trans.getRotation();
    const btVector3& pos = trans.getOrigin();
    _orientation.set(rot.x(), rot.y(), rot.z(), rot.w());

    Vector3 commandedPosition(pos.x(), pos.y(), pos.z());
    Vector3 wheelPos;
    getWheelPos(&wheelPos);
    commandedPosition -= wheelPos;

    // Filter out noise from Bullet
    Vector3 delta(_positionDelta, commandedPosition);
    float threshold = getStrutRestLength() * 2.0f;
    float responseTime = (delta.lengthSquared() > threshold*threshold) ? 0 : 60;
    _positionDelta.smooth(commandedPosition, elapsedTime, responseTime);
}

void PhysicsVehicleWheel::getConnectionDefault(Vector3* result) const
{
    // projected strut length
    getWheelDirection(result);
    result->normalize();
    float length = 0.58f * getStrutRestLength();
    *result *= -length;

    // nudge wheel contact point to outer edge of tire for stability
    Vector3 nudge;
    getWheelAxle(&nudge);
    nudge *= nudge.dot(_initialOffset);
    nudge.normalize();
    *result += nudge * 0.068f * getWheelRadius(); // rough-in for tire width

    // offset at bind time
    *result += _initialOffset;
}

void PhysicsVehicleWheel::getWheelPos(Vector3* result) const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_node);

    *result = _initialOffset;
    _host->_node->getMatrix().transformPoint(result);
}

bool PhysicsVehicleWheel::isSteerable() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_bIsFrontWheel;
}

void PhysicsVehicleWheel::setSteerable(bool steerable)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_bIsFrontWheel = steerable;
}

void PhysicsVehicleWheel::getWheelDirection(Vector3* wheelDirection) const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    const btVector3& v = _host->_vehicle->getWheelInfo(_indexInHost).m_wheelDirectionCS;
    wheelDirection->set(v.x(), v.y(), v.z());
}

void PhysicsVehicleWheel::setWheelDirection(const Vector3& wheelDirection)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_wheelDirectionCS.setValue(wheelDirection.x, wheelDirection.y, wheelDirection.z);
}

void PhysicsVehicleWheel::getWheelAxle(Vector3* wheelAxle) const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    const btVector3& v = _host->_vehicle->getWheelInfo(_indexInHost).m_wheelAxleCS;
    wheelAxle->set(v.x(), v.y(), v.z());
}

void PhysicsVehicleWheel::setWheelAxle(const Vector3& wheelAxle)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_wheelAxleCS.setValue( wheelAxle.x, wheelAxle.y, wheelAxle.z);
}

void PhysicsVehicleWheel::getStrutConnectionOffset(Vector3* strutConnectionOffset) const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    const btVector3& v = _host->_vehicle->getWheelInfo(_indexInHost).m_chassisConnectionPointCS;
    strutConnectionOffset->set(v.x(), v.y(), v.z());
    Vector3 strutConnectionDefault;
    getConnectionDefault(&strutConnectionDefault);
    *strutConnectionOffset -= strutConnectionDefault;
}

void PhysicsVehicleWheel::setStrutConnectionOffset(const Vector3& strutConnectionOffset)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    Vector3 strutConnectionPoint;
    getConnectionDefault(&strutConnectionPoint);
    strutConnectionPoint += strutConnectionOffset;
    _host->_vehicle->getWheelInfo(_indexInHost).m_chassisConnectionPointCS.setValue(strutConnectionPoint.x,
                                                                                strutConnectionPoint.y,
                                                                                strutConnectionPoint.z);
}

float PhysicsVehicleWheel::getStrutRestLength() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_suspensionRestLength1;
}

void PhysicsVehicleWheel::setStrutRestLength(float strutRestLength)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_suspensionRestLength1 = strutRestLength;
}

float PhysicsVehicleWheel::getStrutTravelMax() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_maxSuspensionTravelCm / 100.0f;
}

void PhysicsVehicleWheel::setStrutTravelMax(float strutTravelMax)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_maxSuspensionTravelCm = strutTravelMax * 100.0f;
}

float PhysicsVehicleWheel::getStrutStiffness() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_suspensionStiffness;
}

void PhysicsVehicleWheel::setStrutStiffness(float strutStiffness)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_suspensionStiffness = strutStiffness;
}

float PhysicsVehicleWheel::getStrutDampingCompression() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_wheelsDampingCompression;
}

void PhysicsVehicleWheel::setStrutDampingCompression(float strutDampingCompression)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_wheelsDampingCompression = strutDampingCompression;
}

float PhysicsVehicleWheel::getStrutDampingRelaxation() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_wheelsDampingRelaxation;
}

void PhysicsVehicleWheel::setStrutDampingRelaxation(float strutDampingRelaxation)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_wheelsDampingRelaxation = strutDampingRelaxation;
}

float PhysicsVehicleWheel::getStrutForceMax() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_maxSuspensionForce;
}

void PhysicsVehicleWheel::setStrutForceMax(float strutForceMax)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_maxSuspensionForce = strutForceMax;
}

float PhysicsVehicleWheel::getFrictionBreakout() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_frictionSlip;
}

void PhysicsVehicleWheel::setFrictionBreakout(float frictionBreakout)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_frictionSlip = frictionBreakout;
}

float PhysicsVehicleWheel::getWheelRadius() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_wheelsRadius;
}

void PhysicsVehicleWheel::setWheelRadius(float wheelRadius)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_wheelsRadius = wheelRadius;
}

float PhysicsVehicleWheel::getRollInfluence() const
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    return _host->_vehicle->getWheelInfo(_indexInHost).m_rollInfluence;
}

void PhysicsVehicleWheel::setRollInfluence(float rollInfluence)
{
    GP_ASSERT(_host);
    GP_ASSERT(_host->_vehicle);

    _host->_vehicle->getWheelInfo(_indexInHost).m_rollInfluence = rollInfluence;
}

}


text:
#import "KGOToolbar.h"
#import "KGOSegmentedControl.h"
#import "UIKit+KGOAdditions.h"
#import "AnalyticsWrapper.h"
#import "TourOverviewController.h"
#import "TourMapController.h"
#import "TourDataManager.h"
#import "TourWalkingPathViewController.h"
#import "TourLense.h"
#import "KGOAppDelegate+ModuleAdditions.h"
#import "TourModule.h"

#define CellThumbnailViewTag 1
#define CellStopTitleTag 3
#define CellStopSubtitleTag 4
#define CellStopStatusImageTag 5

@interface TourOverviewController (Private)
- (void)showMapAnimated:(BOOL)animated;
- (void)showListAnimated:(BOOL)animated;
- (void)deallocViews;
- (UIToolbar *)mapToolbar;

- (void)startTourAtStop:(TourStop *)stop;
- (void)startTour;
- (void)continueTourAtStop:(TourStop *)stop;
- (void)continueTour;

- (void)previousStop;
- (void)nextStop;

@end

@implementation TourOverviewController
@synthesize selectedStop;
@synthesize tourStops;
@synthesize mode;
@synthesize tourMapController;
@synthesize contentView = _contentView;
@synthesize stopsTableView = _stopsTableView;
@synthesize stopCell;
@synthesize mapContainerView;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tourMapController = [[[TourMapController alloc] initWithNibName:@"TourMapController" bundle:nil] autorelease];
        self.tourMapController.showMapTip = YES;
    }
    return self;
}

- (void)dealloc
{
    [self deallocViews];
    self.delegate = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    self.mapContainerView = [[[UIView alloc] initWithFrame:self.contentView.bounds] autorelease];
    self.mapContainerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    UIToolbar *mapToolbar = [self mapToolbar];
    self.tourMapController.selectedStop = self.selectedStop;
    self.tourMapController.view.frame = CGRectMake(0, 0,
        self.contentView.frame.size.width, self.contentView.frame.size.height - mapToolbar.frame.size.height);
    mapToolbar.frame = CGRectMake(0, self.contentView.frame.size.height - mapToolbar.frame.size.height,
                            self.contentView.frame.size.width, mapToolbar.frame.size.height);
    [self.mapContainerView addSubview:self.tourMapController.view];
    [self.mapContainerView addSubview:mapToolbar];

    self.stopsTableView.rowHeight = 50;
    if(!self.tourStops) {
        self.tourStops = [[TourDataManager sharedManager] getAllTourStops];
    }
    [self showMapAnimated:NO];

    NSString *title = @"";
    if (self.mode == TourOverviewModeStart) {
        title = @"Pick a Starting Point";
        self.navigationItem.leftBarButtonItem =
        [TourModule
         customToolbarButtonWithImageNamed:@"modules/tour/navbar-back"
         pressedImageNamed:@"modules/tour/navbar-back-pressed"
         target:self action:@selector(backButtonTapped:)];
    } else if(self.mode == TourOverviewModeContinue) {
        title = @"Tour Overview";
        UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *doneImage = [UIImage imageWithPathName:@"modules/tour/navbar-done"];
        [doneButton setImage:doneImage forState:UIControlStateNormal];
        [doneButton setImage:[UIImage imageWithPathName:@"modules/tour/navbar-done-pressed"] forState:UIControlStateHighlighted];
        doneButton.frame = CGRectMake(0, 0, doneImage.size.width, doneImage.size.height);
        [doneButton addTarget:self action:@selector(continueTour) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:doneButton] autorelease];
    }
    TourModule *module =
    (TourModule *)[KGO_SHARED_APP_DELEGATE() moduleForTag:@"home"];
    [module setUpNavBarTitle:title navItem:self.navigationItem];

    KGOSegmentedControl *mapListControl = [[[KGOSegmentedControl alloc] initWithFrame:CGRectMake(0, 0, 76, 30)] autorelease];
    mapListControl.tabFont = [UIFont boldSystemFontOfSize:12];
    mapListControl.tabPadding = 4;
    [mapListControl insertSegmentWithTitle:@"map" atIndex:0 animated:NO];
    [mapListControl insertSegmentWithTitle:@"list" atIndex:1 animated:NO];

    mapListControl.selectedSegmentIndex = 0;
    mapListControl.delegate = self;

    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:mapListControl] autorelease];

    [pool release];
}

- (void)deallocViews {
    self.mapContainerView = nil;
    self.contentView = nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self deallocViews];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)tabbedControl:(KGOTabbedControl *)contol didSwitchToTabAtIndex:(NSInteger)index {
    if(index == 0) {
        [self showMapAnimated:YES];
    } else if(index == 1) {
        [self showListAnimated:YES];
    }
}

- (IBAction)backButtonTapped:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showMapAnimated:(BOOL)animated {
    if([self.mapContainerView superview] != _contentView) {
        self.mapContainerView.frame = _contentView.bounds;
        NSTimeInterval duration = animated ? 0.75 : -1;
        [UIView transitionFromView:_stopsTableView
            toView:self.mapContainerView duration:duration
            options:UIViewAnimationOptionTransitionFlipFromRight
            completion:NULL];
    }
}

- (void)showListAnimated:(BOOL)animated {
    if([self.stopsTableView superview] != _contentView) {
        self.stopsTableView.frame = _contentView.bounds;
        NSTimeInterval duration = animated ? 0.75 : -1;
        [UIView transitionFromView:self.mapContainerView
                            toView:_stopsTableView
                          duration:duration
                           options:UIViewAnimationOptionTransitionFlipFromLeft
                        completion:NULL];
    }
}

- (UIToolbar *)mapToolbar {
    UIToolbar *toolbar = [[[KGOToolbar alloc] initWithFrame:CGRectMake(0, 0, 100, 44)] autorelease];
    toolbar.barStyle = UIBarStyleDefault;
    toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    if(self.mode == TourOverviewModeStart) {
        UIButton *startButtonView = [UIButton buttonWithType:UIButtonTypeCustom];
        [startButtonView setImage:[UIImage imageWithPathName:@"modules/tour/toolbar-next.png"] forState:UIControlStateNormal];
        startButtonView.frame = CGRectMake(0, 0, 44, 44);
        UIBarButtonItem *startButton = [[[UIBarButtonItem alloc] initWithCustomView:startButtonView] autorelease];
        [startButtonView addTarget:self action:@selector(startTour) forControlEvents:UIControlEventTouchUpInside];

        UIButton *labelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        labelButton.frame = CGRectMake(0, 0, 64, 44);
        [labelButton setTitle:@"Start Here" forState:UIControlStateNormal];
        [labelButton setTitle:@"Start Here" forState:UIControlStateHighlighted];
        labelButton.titleLabel.font = [UIFont boldSystemFontOfSize:12.0f];
        labelButton.titleLabel.shadowColor =
        [UIColor colorWithWhite:0.0f alpha:0.6f];
        labelButton.titleLabel.shadowOffset = CGSizeMake(0, 1.0f);
        [labelButton addTarget:self action:@selector(startTour)
              forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *labelButtonItem =
        [[[UIBarButtonItem alloc] initWithCustomView:labelButton] autorelease];

        UIBarItem *leftMargin =
        [[[UIBarButtonItem alloc]
          initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
          target:nil action:nil]
         autorelease];

        toolbar.items = [NSArray arrayWithObjects:leftMargin, labelButtonItem,
                         startButton, nil];
    } else if(self.mode == TourOverviewModeContinue) {
        UIButton *previousButtonView = [UIButton buttonWithType:UIButtonTypeCustom];
        [previousButtonView setImage:[UIImage imageWithPathName:@"modules/tour/toolbar-previous.png"] forState:UIControlStateNormal];
        [previousButtonView addTarget:self action:@selector(previousStop) forControlEvents:UIControlEventTouchUpInside];
        previousButtonView.frame = CGRectMake(0, 0, 44, 44);
        UIBarItem *previousButton = [[[UIBarButtonItem alloc] initWithCustomView:previousButtonView] autorelease];

        UIBarItem *middleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];

        UIButton *nextButtonView = [UIButton buttonWithType:UIButtonTypeCustom];
        [nextButtonView setImage:[UIImage imageWithPathName:@"modules/tour/toolbar-next.png"] forState:UIControlStateNormal];
        [nextButtonView addTarget:self action:@selector(nextStop) forControlEvents:UIControlEventTouchUpInside];
        nextButtonView.frame = CGRectMake(0, 0, 44, 44);
        UIBarItem *nextButton = [[[UIBarButtonItem alloc] initWithCustomView:nextButtonView] autorelease];

        toolbar.items = [NSArray arrayWithObjects:previousButton, middleSpace, nextButton, nil];
    }
    return toolbar;
}

#pragma mark - TableView dataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *tourStopCellIdentifier = @"TourStepCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tourStopCellIdentifier];
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"TourStopCell" owner:self options:nil];
        cell = self.stopCell;
        self.stopCell = nil;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    UIImageView *thumbnailView = (UIImageView *)[cell viewWithTag:CellThumbnailViewTag];
    TourStop *stop = [self.tourStops objectAtIndex:indexPath.row];
    thumbnailView.image = [(TourMediaItem *)stop.thumbnail image];
    UILabel *stopTitleLabel = (UILabel *)[cell viewWithTag:CellStopTitleTag];
    stopTitleLabel.text = stop.title;
    UILabel *stopSubtitleLabel = (UILabel *)[cell viewWithTag:CellStopSubtitleTag];
    stopSubtitleLabel.text = stop.subtitle;

    if(self.mode == TourOverviewModeContinue) {
        UIImageView *statusImageView = (UIImageView *)[cell viewWithTag:CellStopStatusImageTag];
        if (stop == self.selectedStop) {
            statusImageView.image = [UIImage imageWithPathName:@"modules/tour/map-pin-current"];
        } else if([stop.visited boolValue]) {
            statusImageView.image = [UIImage imageWithPathName:@"modules/tour/map-pin-past"];
        } else {
            statusImageView.image = nil;
        }
    }

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tourStops.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TourStop *stop = [self.tourStops objectAtIndex:indexPath.row];
    if (self.mode == TourOverviewModeStart) {
        [self startTourAtStop:stop];
    } else if (self.mode == TourOverviewModeContinue) {
        [self continueTourAtStop:stop];
    }
}

# pragma mark - class methods used by the map and list controller
+ (void)layoutLensesLegend:(UIView *)legendView forStop:(TourStop *)stop withIconSize:(CGFloat)size {
    [[TourDataManager sharedManager] populateTourStopDetails:stop];
    for(UIView *subviews in legendView.subviews) {
        [subviews removeFromSuperview];
    }

    CGFloat rightEdge = legendView.frame.size.width;
    for(TourLense *lense in [[stop orderedLenses] reverseObjectEnumerator]) {
        CGRect iconFrame = CGRectMake(rightEdge-size, 0, size, size);
        UIImageView *iconView = [[[UIImageView alloc] initWithFrame:iconFrame] autorelease];
        iconView.contentMode = UIViewContentModeScaleAspectFit;
        iconView.image = [UIImage
                          imageWithPathName:[NSString stringWithFormat:@"modules/tour/lens-%@", lense.lenseType]];
        [legendView addSubview:iconView];
        rightEdge -= size;
    }
}

# pragma mark - user actions
- (void)startTourAtStop:(TourStop *)stop {
    TourWalkingPathViewController *walkingPathViewController = [[TourWalkingPathViewController alloc] initWithNibName:@"TourWalkingPathViewController" bundle:nil];
    walkingPathViewController.initialStop = stop;
    walkingPathViewController.currentStop = stop;
    [self.navigationController pushViewController:walkingPathViewController animated:YES];
    [walkingPathViewController release];
    [[AnalyticsWrapper sharedWrapper] trackEvent:@"Select Starting Point" action:@"Start Tour" label:stop.title];
}

- (void)startTour {
    [self startTourAtStop:self.tourMapController.selectedStop];
}

- (void)continueTourAtStop:(TourStop *)stop {
    [self.delegate tourOverview:self stopWasSelected:stop];
}

- (void)continueTour {
    [self continueTourAtStop:self.tourMapController.selectedStop];
}

- (void)nextStop {
    TourStop *nextStop = [[TourDataManager sharedManager] nextStopForTourStop:self.tourMapController.selectedStop];
    self.tourMapController.selectedStop = nextStop;
}

- (void)previousStop {
    TourStop *previousStop = [[TourDataManager sharedManager] previousStopForTourStop:self.tourMapController.selectedStop];
    self.tourMapController.selectedStop = previousStop;
}

@end


text:
#region copyright
// Copyright 2013-2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using LAIR.Extensions;
using LAIR.IO;

namespace PTL.ATT.GUI
{
    public class LogWriter : StandardOutWriter
    {
        private TextBoxBase _textBox;
        private bool _scrollTextBox;

        public LogWriter(TextBoxBase textBox, string path, bool writeTimestamp, bool append, params TextWriter[] otherOutputs)
            : base(path, writeTimestamp, append, otherOutputs)
        {
            _textBox = textBox;
            _scrollTextBox = true;
            _textBox.MouseWheel += new MouseEventHandler(textBox_MouseWheel);
        }

        public override void Clear()
        {
            base.Clear();

            lock (_textBox)
            {
                if (_textBox.InvokeRequired)
                    _textBox.BeginInvoke(new Action(_textBox.Clear));
                else
                    _textBox.Clear();
            }
        }

        private void textBox_MouseWheel(object sender, MouseEventArgs args)
        {
            _scrollTextBox = _textBox.TextLength == _textBox.GetCharIndexFromPosition(new System.Drawing.Point(_textBox.ClientRectangle.Right, _textBox.ClientRectangle.Bottom)) + 1;
        }

        protected override string Write(string value, bool newLine)
        {
            if (_textBox.InvokeRequired)
            {
                _textBox.BeginInvoke(new Func<string, bool, string>(Write), value, newLine);
                return null;
            }
            else
            {
                if (newLine)
                    value = value.Trim('.') + ".";

                value = base.Write(value, newLine);

                lock (_textBox)
                {
                    _textBox.AppendText(value);
                    if (_scrollTextBox)
                        _textBox.ScrollToCaret();
                }

                return value;
            }
        }
    }
}


text:
@interface UIViewController(InformUser)

// app wide way to inform user (currently TSMessages)
-(void)informUserWithErrorMessage:(NSString*)errorString withTitle:(NSString*)title;
-(void)informUserWithWarnMessage:(NSString*)warningString withTitle:(NSString*)title;
-(void)informUserWithInfoMessage:(NSString*)infoString withTitle:(NSString*)title;
-(void)informUserWithSuccessMessage:(NSString*)successString withTitle:(NSString*)title;

@end


text:
JDK_PATH=/usr/lib/jvm/jdk1.7.0_09/bin/
CURRENT_PWD=`pwd`
MANIFEST=$CURRENT_PWD/manifestaddition.txt
EXT_DIR=$CURRENT_PWD/extlibs
EXT_SRC_DIR=$EXT_DIR/src/com/twister/
EXTLIBS=$CURRENT_PWD/extlibs/Twister.jar:\
$CURRENT_PWD/extlibs/jcalendar-1.4.jar:\
$CURRENT_PWD/extlibs/gson-2.2.1.jar:\
$CURRENT_PWD/extlibs/ws-commons-util-1.0.2.jar:\
$CURRENT_PWD/extlibs/commons-vfs-1.0.jar:\
$CURRENT_PWD/extlibs/jgoodies-looks-2.5.1.jar:\
$CURRENT_PWD/extlibs/jgoodies-common-1.3.1.jar:\
$CURRENT_PWD/extlibs/jxl.jar:\
$CURRENT_PWD/extlibs/runner.jar:\
$CURRENT_PWD/extlibs/ControlPanel.jar:\
$CURRENT_PWD/extlibs/UserManagement.jar:\
$CURRENT_PWD/extlibs/ws-commons-util-1.0.2.jar:\
$CURRENT_PWD/extlibs/xmlrpc-client-3.1.3.jar:\
$CURRENT_PWD/extlibs/xmlrpc-common-3.1.3.jar

TMP_TEST_EXEC_DIR=`echo $CURRENT_PWD | rev | cut -d '/' -f4- | rev`
TEST_EXEC_DIR="$TMP_TEST_EXEC_DIR/plugins/TestCaseExecution"
USR_MGMT_DIR="$TMP_TEST_EXEC_DIR/plugins/UserManagement"

# build the sources from extlibs
echo $EXT_DIR
echo $EXT_SRC_DIR
mkdir $EXT_DIR/classes
mkdir $EXT_DIR/classes/com
mkdir $EXT_DIR/classes/com/twister
cp $EXT_SRC_DIR/*.png $EXT_DIR/classes/com/twister

EXT_DIR_CLS=$EXT_DIR/classes/com/twister:\
$EXT_DIR/classes/com/twister/plugin/baseplugin:\
$EXT_DIR/classes/com/twister/plugin/twisterinterface

cd $EXT_SRC_DIR
$JDK_PATH/javac  -deprecation -d $EXT_DIR/classes -source 1.7 -target 1.7 -cp $EXTLIBS $EXT_SRC_DIR/*.java
cd "$EXT_SRC_DIR/plugin/twisterinterface"
$JDK_PATH/javac  -deprecation -d $EXT_DIR/classes -source 1.7 -target 1.7 -cp $EXTLIBS:$EXT_DIR_CLS *.java
cd "$EXT_SRC_DIR/plugin/baseplugin/"
$JDK_PATH/javac  -deprecation -d $EXT_DIR/classes -source 1.7 -target 1.7 -cp $EXTLIBS:$EXT_DIR_CLS *.java
#cp $EXT_DIR/classes/com/twister/*.class $EXT_DIR/classes
#p $EXT_DIR/classes/com/twister/plugin/baseplugin/*.class $EXT_DIR/classes
#p $EXT_DIR/classes/com/twister/plugin/twisterinterface/*.class $EXT_DIR/classes
cd $EXT_DIR/classes
$JDK_PATH/jar cfm $EXT_DIR/Twister.jar $MANIFEST com/twister/ com/twister/plugin/baseplugin/*.class com/twister/plugin/twisterinterface/*.class
#rm -r $TEST_EXEC_DIR/classes

# need to build runner.jar first from
cd $TEST_EXEC_DIR
rm target/runner.jar
mkdir classes
$JDK_PATH/javac  -deprecation -d classes -source 1.7 -target 1.7  -cp $EXTLIBS *.java
cd classes
$JDK_PATH/jar  cfm ../target/runner.jar ../manifestaddition.txt Icons/ *.class
cp ../target/runner.jar $CURRENT_PWD/extlibs

cd $USR_MGMT_DIR
mkdir classes
mkdir target
$JDK_PATH/javac  -deprecation -d classes -source 1.7 -target 1.7  -cp $EXTLIBS *.java
cd classes
cp ../back.png back.png
$JDK_PATH/jar  cfm ../target/UserManagement.jar ../manifestaddition.txt back.png *.class
cp ../target/UserManagement.jar $CURRENT_PWD/extlibs

cd $CURRENT_PWD
# Compile sources
$JDK_PATH/javac  -deprecation -d classes -source 1.7 -target 1.7  -cp $EXTLIBS src/*.java

# Generate JAR file
cd classes;
$JDK_PATH/jar  cfm ../target/applet.jar ../manifestaddition.txt Icons/ *.class

# Sign the JAR file using the keystore
cd ../target
echo "Signing jar file applet.jar"
$JDK_PATH/jarsigner applet.jar Twister -storepass password
echo "Signing jar file gson-2.2.1.jar"
$JDK_PATH/jarsigner ../extlibs/gson-2.2.1.jar Twister -storepass password
echo "Signing jar file commons-logging-1.1.1.jar"
$JDK_PATH/jarsigner ../extlibs/commons-logging-1.1.1.jar Twister -storepass password
echo "Signing jar file commons-vfs-1.0.jar"
$JDK_PATH/jarsigner ../extlibs/commons-vfs-1.0.jar Twister -storepass password
echo "Signing jar file jxl.jar"
$JDK_PATH/jarsigner ../extlibs/jxl.jar Twister -storepass password
echo "Signing jar file ws-commons-util-1.0.2.jar"
$JDK_PATH/jarsigner ../extlibs/ws-commons-util-1.0.2.jar Twister -storepass password
echo "Signing jar file xmlrpc-client-3.1.3.jar"
$JDK_PATH/jarsigner ../extlibs/xmlrpc-client-3.1.3.jar Twister -storepass password
echo "Signing jar file xmlrpc-common-3.1.3.jar"
$JDK_PATH/jarsigner ../extlibs/xmlrpc-common-3.1.3.jar Twister -storepass password
echo "Signing jar file jgoodies-looks-2.5.1.jar"
$JDK_PATH/jarsigner ../extlibs/jgoodies-looks-2.5.1.jar Twister -storepass password
echo "Signing jar file jgoodies-common-1.3.1.jar"
$JDK_PATH/jarsigner ../extlibs/jgoodies-common-1.3.1.jar Twister -storepass password
echo "Signing jar file jcalendar-1.4.jar"
$JDK_PATH/jarsigner ../extlibs/jcalendar-1.4.jar Twister -storepass password

echo "Signing jar file UserManagement.jar"
$JDK_PATH/jarsigner ../extlibs/UserManagement.jar Twister -storepass password
echo "Signing jar file runner.jar"
$JDK_PATH/jarsigner ../extlibs/runner.jar Twister -storepass password
echo "Signing jar file ControlPanel.jar"
$JDK_PATH/jarsigner ../extlibs/ControlPanel.jar Twister -storepass password

echo "Signing jar file Twister.jar"
$JDK_PATH/jarsigner ../extlibs/Twister.jar Twister -storepass password

# Export the keystore as X509
$JDK_PATH/keytool  -export -alias Twister -rfc -file ../target/sig.x509 -storepass password

# copy jar files into the binaries directory
cd $CURRENT_PWD
cp target/applet.jar ../../../binaries/applet/
cp target/sig.x509 ../../../binaries/applet/
cp extlibs/*.jar ../../../binaries/applet/

# do some clean-up
rm target/applet.jar
rm target/sig.x509
rm -rf ../../../plugins/UserManagement/target/
rm -r $EXT_DIR/classes
rm $TEST_EXEC_DIR/classes/*.class
rm $USR_MGMT_DIR/classes/*.class


text:
module.exports = require('proof')(function () {
    var register = require('../../register')
    var stream = require('stream')
    var path = require('path')
    var once = require('../../once')
    return {
        once: function (step, path, parameters, stdin) {
            return once(__dirname + '/' + path, parameters, stdin, step())
        }
    }
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/quickstart-springboot-ws" reloadable="true"/>


text:
namespace sessions {
class LiveTab;
class LiveTabContext;
}

namespace ios {

class ChromeBrowserState;

// A class that allows retrieving a sessions::LiveTabContext.
class LiveTabContextProvider {
 public:
  virtual ~LiveTabContextProvider() {}

  // Creates a new context.
  virtual sessions::LiveTabContext* Create(
      ios::ChromeBrowserState* browser_state) = 0;

  // Retrieves the context with the given ID, if one exists.
  virtual sessions::LiveTabContext* FindContextWithID(int32 desired_id) = 0;

  // Retrieves the context for the given tab, if one exists.
  virtual sessions::LiveTabContext* FindContextForTab(
      const sessions::LiveTab* tab) = 0;
};

}  // namespace ios

#endif  // IOS_PUBLIC_PROVIDER_CHROME_BROWSER_SESSIONS_LIVE_TAB_CONTEXT_PROVIDER_H_


text:
var _ = require("hr.utils");
var Q = require("q");
var Collection = require("hr.collection");

var Dialog = require("../views/dialogs/container");
var DialogInputView = require("../views/dialogs/input");
var DialogListView = require("../views/dialogs/list");

var alertTemplate = require("../resources/templates/dialogs/alert.html");
var confirmTemplate = require("../resources/templates/dialogs/confirm.html");
var promptTemplate = require("../resources/templates/dialogs/prompt.html");
var schemaTemplate = require("../resources/templates/dialogs/schema.html");

// Open a dialog
var open = function(View, options) {
    var d = Q.defer();

    // Create the dialog
    var diag = new Dialog(_.extend(options || {}, {
        View: View
    }));

    // Bind close
    diag.on("close", function(force) {
        if (force) return d.reject(new Error("Dialog was been closed"));
        d.resolve(diag.view);
    });

    // Open it (add it to dom)
    diag.update();

    return d.promise;
};

// Input dialog
var openInput = function(viewOptions, options, View) {
    return open(View || DialogInputView, _.extend(options || {}, {
        view: viewOptions || {}
    }))
    .then(function(view) {
        var value = view.getValue();

        if (value == null) return Q.reject(new Error("Dialog return empty value"));
        return value;
    });
};

// Alert
var openAlert = function(text, options) {
    options = _.defaults(options || {}, {
        isHtml: false
    });
    return openInput({
        template: alertTemplate,
        text: text,
        isHtml: options.isHtml
    });
};
var openErrorAlert = function(err) {
    console.log("error", err);
    return openAlert("Error: "+(err.message || err))
    .fin(function() {
        return Q.reject(err);
    });
};

// Confirm
var openConfirm = function(text, options) {
    return openInput({
        template: confirmTemplate,
        text: text
    });
};

// Prompt
var openPrompt = function(text, value, options) {
    return openInput({
        template: promptTemplate,
        text: text,
        defaultValue: value,
        value: function(d) { return d.$("input").val(); }
    });
};

// List
var openList = function(source, options) {
    if (_.isArray(source)) {
        source = new Collection({
            models: _.map(source, function(item) {
                if (!_.isObject(item)) return { value: item };
                return item;
            })
        });
    }

    return openInput(
        _.extend({
            template: "
<%- item.get('value') %>
",
            placeholder: "",
            filter: function() { return true; }
        }, options, {
            source: source
        }), {}, DialogListView);
};

// Schema
var openSchema = function(schema, values) {
    values = values || {};

    return openInput({
        template: schemaTemplate,
        schema: schema,
        defaultValues: values,
        value: function(d) {
            var nvalues = _.clone(values);

            _.each(schema.properties, function(property, key) {
                var v = d.$("*[name='"+key+"']").val();
                nvalues[key] = v;
            });

            return nvalues;
        }
    });
};

module.exports = {
    open: open,
    alert: openAlert,
    error: openErrorAlert,
    confirm: openConfirm,
    prompt: openPrompt,
    list: openList,
    schema: openSchema,
    input: openInput
};


text:
'use strict';

var request = require('request');
var Pin = require('./pin');
var version = require('../package').version;

var USER_AGENT = 'pebble-api-node/' + version + ';node/' + process.versions.node;
var API_ROOT = 'https://timeline-api.getpebble.com';

/**
 * Timeline
 *
 * @constructor
 * @param {Object} [opts]
 */
var Timeline = module.exports = function (opts) {
  opts = opts || {};

  this._apiKey = opts.apiKey || process.env.PEBBLE_TIMELINE_API_KEY;

  this._apiRoot = opts.apiRoot || process.env.PEBBLE_TIMELINE_API_ROOT || API_ROOT;
};

Timeline.Pin = Pin;

/**
 * Send a pin to a user
 *
 * @param {String} userToken
 * @param {Pin} pin
 * @callback {callback} callback
 */
Timeline.prototype.sendUserPin = function (userToken, pin, callback) {
  if (typeof userToken !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected userToken to be a string.'));
    });
  }

  if (!(pin instanceof Pin)) {
    pin = new Pin(pin);
  }

  var opts = {
    method: 'PUT',
    endpoint: '/v1/user/pins/' + pin.id,
    headers: {
      'X-User-Token': userToken
    },
    body: pin
  };

  this._request(opts, callback);
};

/**
 * Send a pin to a topic
 *
 * @param {Array} topics
 * @param {Pin} pin
 * @callback {callback} callback
 */
Timeline.prototype.sendSharedPin = function (topics, pin, callback) {
  if (!this._apiKey) {
    return process.nextTick(function () {
      callback(new Error('API Key not set.'));
    });
  }

  if (!(topics instanceof Array)) {
    return process.nextTick(function () {
      callback(new Error('Expected topics to be an array.'));
    });
  }

  if (!(pin instanceof Pin)) {
    pin = new Pin(pin);
  }

  var opts = {
    method: 'PUT',
    endpoint: '/v1/shared/pins/' + pin.id,
    headers: {
      'X-API-Key': this._apiKey,
      'X-PIN-Topics': topics.join(',')
    },
    body: pin
  };

  this._request(opts, callback);
};

/**
 * Delete a user pin
 *
 * @param {String} userToken
 * @param {Pin} pin
 * @return {callback} callback
 */
Timeline.prototype.deleteUserPin = function (userToken, pin, callback) {
  if (typeof userToken !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected userToken to be a string.'));
    });
  }

  if (!(pin instanceof Pin)) {
    pin = new Pin(pin);
  }

  var opts = {
    method: 'DELETE',
    endpoint: '/v1/user/pins/' + pin.id,
    headers: {
      'X-User-Token': userToken
    }
  };

  this._request(opts, callback);
};

/**
 * Delete a shared pin
 *
 * @param {Pin} pin
 * @return {callback} callback
 */
Timeline.prototype.deleteSharedPin = function (pin, callback) {
  if (!this._apiKey) {
    return process.nextTick(function () {
      callback(new Error('API Key not set.'));
    });
  }

  if (!(pin instanceof Pin)) {
    pin = new Pin(pin);
  }

  var opts = {
    method: 'DELETE',
    endpoint: '/v1/shared/pins/' + pin.id,
    headers: {
      'X-API-Key': this._apiKey
    }
  };

  this._request(opts, callback);
};

/**
 * Subscribe to a topic
 *
 * @param {String} userToken
 * @param {String} topic
 * @callback {callback} callback
 */
Timeline.prototype.subscribe = function (userToken, topic, callback) {
  if (typeof userToken !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected userToken to be a string.'));
    });
  }

  if (typeof topic !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected topic to be a string.'));
    });
  }

  var opts = {
    method: 'POST',
    endpoint: '/v1/user/subscriptions/' + topic,
    headers: {
      'X-User-Token': userToken
    }
  };

  this._request(opts, callback);
};

/**
 * Unsubscribe from a topic
 *
 * @param {String} userToken
 * @param {String} topic
 * @callback {callback} callback
 */
Timeline.prototype.unsubscribe = function (userToken, topic, callback) {
  if (typeof userToken !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected userToken to be a string.'));
    });
  }

  if (typeof topic !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected topic to be a string.'));
    });
  }

  var opts = {
    method: 'DELETE',
    endpoint: '/v1/user/subscriptions/' + topic,
    headers: {
      'X-User-Token': userToken
    }
  };

  this._request(opts, callback);
};

/**
 * List user subscriptions
 *
 * @param {String} userToken
 * @callback {callback} callback
 */
Timeline.prototype.listSubscriptions = function (userToken, callback) {
  if (typeof userToken !== 'string') {
    return process.nextTick(function () {
      callback(new Error('Expected userToken to be a string.'));
    });
  }

  var opts = {
    method: 'GET',
    endpoint: '/v1/user/subscriptions',
    headers: {
      'X-User-Token': userToken
    }
  };

  this._request(opts, function (err, body, res) {
    if (err) {
      return callback(err);
    }

    var topics = body.topics || [];

    callback(null, topics, res);
  });
};

Timeline.prototype._request = function(opts, callback) {
  if (typeof callback !== 'function') {
    throw new Error('Callback not set but is required.');
  }

  var reqOpts = {};

  reqOpts.method = opts.method.toUpperCase();
  reqOpts.url = this._apiRoot + opts.endpoint;
  reqOpts.headers = opts.headers || {};
  reqOpts.headers['user-agent'] = USER_AGENT;

  switch (reqOpts.method) {
    case 'GET':
      reqOpts.json = true;
      break;
    case 'PUT':
      reqOpts.body = opts.body;
      reqOpts.json = true;
      break;
  }

  request(reqOpts, function (err, res, body) {
    if (err) {
      return callback(err, body, res);
    }

    if (res.statusCode < 300) {
      return callback(null, body, res);
    }

    if (Timeline.errorCodes[res.statusCode]) {
      return callback(new Error(Timeline.errorCodes[res.statusCode]), body, res);
    }

    callback(new Error('Unknown error. Status code: ' + res.statusCode), body, res);
  });
};

Timeline.errorCodes = {
  400: 'The pin object submitted was invalid.',
  403: 'The API key submitted was invalid.',
  410: 'The user token submitted was invalid or does not exist.',
  429: 'Server is sending updates too quickly.',
  503: 'Could not save pin due to a temporary server error.',
};


text:
import * as assert from 'assert';
import Enumerable from './Enumerable';

describe('select()', () => {
    it('should projects each element of a sequence', () => {
        assert.deepEqual(new Enumerable([1, 2, 3, 4]).select(x => x * 2).toArray(), [2, 4, 6, 8]);
    });
});


text:
package org.opencb.bionetdb.lib.executors;

import org.opencb.bionetdb.core.models.network.NetworkStats;
import org.opencb.bionetdb.core.response.BioNetDBResult;
import org.opencb.bionetdb.lib.api.NetworkDBAdaptor;

public class NetworkQueryExecutor {

    private NetworkDBAdaptor networkDBAdaptor;

    public NetworkQueryExecutor(NetworkDBAdaptor networkDBAdaptor) {
        this.networkDBAdaptor = networkDBAdaptor;
    }

    public BioNetDBResult<NetworkStats> stats() {
        return networkDBAdaptor.networkStats();
    }
}


text:
package client.app.system.tasks;

import share.core.utils.Environment;
import client.app.system.gui.def.GUILogInfo;
import client.core.debug.Debug;
import client.core.gui.taks.Activity;

public class LogInfo extends Activity<Void>
{
	private final GUILogInfo gui = new GUILogInfo();

	public LogInfo()
	{
		super(GUILogInfo.PATH, Type.MODAL, true);
	}

	@Override
	public void start()
	{
		setGUI(this.gui);
		this.gui.info.setEditable(false);
		this.gui.info.set(Debug.getInfo());
		this.gui.info.setBottom();
	}

	private void copyText()
	{
		Environment.copyClipboard(this.gui.info.get());
		this.gui.info.focus();
	}

	@Override
	public void event(Event event)
	{
		switch (event)
		{
			case COPY:
				copyText();
				break;

			case ACCEPT:
				close();
				break;

			default:
				break;
		}
	}
}


text:
using System;
using System.Text;
using System.Collections.Generic;

namespace UnityORM
{
	public class SQLMaker
	{
		public readonly static DateTime UnixTime = new DateTime(1970,1,1, 0, 0, 0);

		public static string GenerateCreateTableSQL<T>(ClassDesc desc){

			var builder = new StringBuilder();
			builder.Append("CREATE TABLE IF NOT EXISTS " + desc.Name + "(");
			foreach(var f in desc.FieldDescs){
				builder.Append(f.NameInTable + " " + ConvertToSQLType(f.FieldType ));
				if(f == desc.KeyField){
					builder.Append(" PRIMARY KEY");
				}
				if( desc.AutoIncrement){
					builder.Append(" AUTOINCREMENT");
				}
				builder.Append(",");
			}
			builder.Remove(builder.Length - 1,1);
			builder.Append(");");
			return builder.ToString();
		}
		static string ConvertToSQLType(Type t){
			if(t == typeof(int) ||
				t == typeof(long)){
				return "INTEGER";
			}else if(t == typeof(double)){
				return "FLOAT";
			}else if(t == typeof(byte[])){
				return "BLOB";
			}else if(t == typeof(DateTime)){
				return "INTEGER";
			}else{
				return "TEXT";
			}
		}
		public static string GenerateSelectAllSQL<T>(ClassDesc desc){
			return "SELECT * FROM " + desc.Name + ";";
		}
		public static string GenerateSelectSQL<T>(ClassDesc desc,object key){
			if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field");
			return "SELECT * FROM " + desc.Name + " WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(key) + ";";
		}
		public static string GenerateSelectSQL<T>(ClassDesc desc,T obj){
			if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field");
			return "SELECT * FROM " + desc.Name + " WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(desc.KeyField.GetForDb(obj)) + ";";
		}
		public static string GenerateDeleteAllSQL<T>(ClassDesc desc){
			return "DELETE FROM " + desc.Name + ";";
		}
		public static string GenerateDeleteSQL<T>(ClassDesc desc,object key){
			if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field");
			return "DELETE FROM " + desc.Name + " WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(key) + ";";
		}
		public static string GenerateInsertSQL<T>(ClassDesc desc,T obj){
			var builder = new StringBuilder();
			builder.Append("INSERT INTO " + desc.Name + " (");

			var fields = desc.FieldDescs;
			if(desc.AutoIncrement){
				fields = new List<UnityORM.FieldDesc>(fields);
				fields.Remove(desc.KeyField);
			}

			foreach( var f in fields){
				builder.Append(f.NameInTable + ",");
			}
			builder.Remove(builder.Length - 1,1);
			builder.Append(") VALUES (");

			foreach( var f in fields){
				object v = f.GetForDb(obj);
				builder.Append(ValueToBlock(v) + ",");
			}
			builder.Remove(builder.Length - 1,1);
			builder.Append(");");

			return builder.ToString();
		}
		public static string GenerateUpdateSQL<T>(ClassDesc desc,T obj){
			if(desc.KeyField == null) throw new Exception("Class " + desc.Name + " hasn't key field");
			var builder = new StringBuilder();
			builder.Append("UPDATE " + desc.Name + " SET ");
			foreach(var f in desc.FieldDescs){
				object v = f.GetForDb(obj);
				builder.Append(f.NameInTable + "=" + ValueToBlock(v) + ",");
			}
			builder.Remove(builder.Length -1 ,1);
			builder.Append(" WHERE " + desc.KeyField.NameInTable + " = " + ValueToBlock(desc.KeyField.GetForDb(obj)) + ";");

			return builder.ToString();
		}
		static string ValueToBlock(object v){
			if(v == null){
				return "NULL";
			}else{
				return "'" + Escape(v.ToString()) + "'";
			}
		}
		public static string Escape(string str){
			return str.Replace("'","''");
		}
	}
}


text:
package org.apache.spark.scheduler

import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.storage.RDDInfo

/**
 * :: DeveloperApi ::
 * Stores information about a stage to pass from the scheduler to SparkListeners.
 */
@DeveloperApi
class StageInfo(val stageId: Int, val name: String, val numTasks: Int, val rddInfos: Seq[RDDInfo]) {
  /** When this stage was submitted from the DAGScheduler to a TaskScheduler. */
  var submissionTime: Option[Long] = None
  /** Time when all tasks in the stage completed or when the stage was cancelled. */
  var completionTime: Option[Long] = None
  /** If the stage failed, the reason why. */
  var failureReason: Option[String] = None

  var emittedTaskSizeWarning = false

  def stageFailed(reason: String) {
    failureReason = Some(reason)
    completionTime = Some(System.currentTimeMillis)
  }
}

private[spark] object StageInfo {
  /**
   * Construct a StageInfo from a Stage.
   *
   * Each Stage is associated with one or many RDDs, with the boundary of a Stage marked by
   * shuffle dependencies. Therefore, all ancestor RDDs related to this Stage's RDD through a
   * sequence of narrow dependencies should also be associated with this Stage.
   */
  def fromStage(stage: Stage): StageInfo = {
    val ancestorRddInfos = stage.rdd.getNarrowAncestors.map(RDDInfo.fromRdd)
    val rddInfos = Seq(RDDInfo.fromRdd(stage.rdd)) ++ ancestorRddInfos
    new StageInfo(stage.id, stage.name, stage.numTasks, rddInfos)
  }
}


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.WebSites.Models;

namespace Microsoft.Azure.Management.WebSites.Models
{
    /// <summary>
    /// Create or update website parameters.
    /// </summary>
    public partial class WebSiteCreateOrUpdateParameters
    {
        private WebSiteBase _webSite;

        /// <summary>
        /// Required. Gets or sets information about a website being created of
        /// updated.
        /// </summary>
        public WebSiteBase WebSite
        {
            get { return this._webSite; }
            set { this._webSite = value; }
        }

        /// <summary>
        /// Initializes a new instance of the WebSiteCreateOrUpdateParameters
        /// class.
        /// </summary>
        public WebSiteCreateOrUpdateParameters()
        {
        }

        /// <summary>
        /// Initializes a new instance of the WebSiteCreateOrUpdateParameters
        /// class with required arguments.
        /// </summary>
        public WebSiteCreateOrUpdateParameters(WebSiteBase webSite)
            : this()
        {
            if (webSite == null)
            {
                throw new ArgumentNullException("webSite");
            }
            this.WebSite = webSite;
        }
    }
}


text:
import * as React from 'react';
import { mergeProps, useButton, useHover } from 'react-aria';
import Image from 'next/image';
import cn from 'classnames';
import { trackCustomEvent } from 'utils/analytics';
import { useRouter } from 'next/router';

export interface FeedbackButtonProps {
  intent: 'tears' | 'meh' | 'happy' | 'awesome';
  onPress: () => void;
}

const mapIntentToSource = {
  tears: '/twemoji/1f62d.svg',
  meh: '/twemoji/1f615.svg',
  happy: '/twemoji/1f600.svg',
  awesome: '/twemoji/1f929.svg',
};

export function FeedbackButton({ intent, ...props }: FeedbackButtonProps) {
  const ref = React.useRef<HTMLButtonElement | null>(null);
  const { buttonProps } = useButton(props, ref);
  const { isHovered, hoverProps } = useHover({});
  const mergedProps = mergeProps(hoverProps, buttonProps);
  return (
    <>
      <button
        {...mergedProps}
        ref={ref}
        className={cn(
          'inline-flex items-center justify-center py-2',
          isHovered
            ? ' none transition duration-150 scale-125 transform  ease-in-out '
            : ' grayed transition duration-150 scale-100 transform ease-in-out '
        )}
      >

      </button>

    </>
  );
}

FeedbackButton.displayName = 'FeedbackButton';

export function ReactionForm() {
  const [feedbackGiven, setFeedbackGiven] = React.useState(false);

  const { asPath } = useRouter();
  React.useEffect(() => {
    setFeedbackGiven(false);
  }, [asPath, setFeedbackGiven]);

  const makeTrackedHandler = (value: number) => () => {
    trackCustomEvent({
      category: 'Feedback Button',
      action: 'feedback',
      name: 'feedback',
      label: window.location.pathname,
      value,
    });
    setFeedbackGiven(true);
  };

  if (feedbackGiven) {
    return (

        Thanks for letting us know!

    );
  } else {
    return (
      <>

          Was this page helpful?

          <FeedbackButton intent="tears" onPress={makeTrackedHandler(0)} />
          <FeedbackButton intent="meh" onPress={makeTrackedHandler(1)} />
          <FeedbackButton intent="happy" onPress={makeTrackedHandler(2)} />
          <FeedbackButton intent="awesome" onPress={makeTrackedHandler(3)} />

      </>
    );
  }
}

ReactionForm.displayName = 'ReactionForm';


text:
require "erector/attributes"
require "erector/text"

module Erector
  class Promise
    extend Attributes
    extend Text

    def initialize(output, tag_name, attributes = {}, self_closing = false, newliney = true, &inside_renderer)
      raise "bad output: #{output.inspect}" unless output.is_a? Output
      raise "forgot self-closing" unless [false, true].include? self_closing

      @output = output

      # todo: pointer to Tag object?
      @tag_name = tag_name
      @self_closing = self_closing
      @newliney = newliney

      @attributes = {}
      _set_attributes attributes
      @text = nil
      @inside_renderer = inside_renderer
      _mark
    end

    def _set_attributes attributes
      attributes.each_pair do |k,v|
        @attributes[k.to_s] = v
      end
    end

    def _mark
      @mark = @output.mark
    end

    def _rewind
      @output.rewind @mark
    end

    def _render
      _rewind
      _render_open_tag
      begin
        _render_inside_tag
      ensure
        _render_close_tag
      end
    end

    def _render_open_tag

      @output.newline if !@self_closing and @newliney and !@output.at_line_start?

      @output << RawString.new( "<#{@tag_name}#{Promise.format_attributes(@attributes)}")
      if @self_closing
        @output << RawString.new( " />")
        @output.newline if @newliney
      else
        @output << RawString.new( ">")
        @output.indent
      end
    end

    def _render_inside_tag
      return if @self_closing
      if @text
        @output << @text
      end
      if @inside_renderer
        @inside_renderer.call
      end
    end

    def _render_close_tag
      return if @self_closing

      @output.undent
      @output<< RawString.new("</#{@tag_name}>")
      if @newliney
        @output.newline
      end
    end

    def method_missing(method_name, *args, &block)
      method_name = method_name.to_s
      if Erector::Widget.hyphenize_underscores
        method_name = method_name.gsub(/_/, "-")
      end

      if method_name =~ /\!$/
        id_str = method_name[0...-1]
        raise ArgumentError, "setting id #{id_str} but id #{@attributes["id"]} already present" if @attributes["id"]
        @attributes["id"] = id_str
      else
        if @attributes["class"]
          @attributes["class"] += " "
        else
          @attributes["class"] = ""
        end
        @attributes["class"] += method_name.to_s
      end

      if block_given?
        @inside_renderer = block
      end

      if args.last.is_a? Hash
        attributes = args.pop
        _set_attributes attributes
      end

      # todo: allow multiple args
      # todo: allow promise args
      @text = args.first

      _render

      self
    end

    # are these accessors necessary?

    def _tag_name
      @tag_name
    end

    def _attributes
      @attributes
    end

    def _open_tag
      @open_tag
    end

    def _close_tag
      @close_tag
    end

  end
end


text:
#ifndef ALITPCMONITORDATEFORMAT_H
#define ALITPCMONITORDATEFORMAT_H

/* $Id$ */

////////////////////////////////////////////////////////////////////////
////
//// AliTPCMonitorDateFormat class
////
//// Class for decoding raw data headers in DATE format
////
//// Authors: Roland Bramm,
////          Stefan Kniege, IKF, Frankfurt
////
/////////////////////////////////////////////////////////////////////////

struct eventHeaderStruct;
struct equipmentHeaderStruct;

#define long32 int
#include "TNamed.h"
using namespace std;

class AliTPCMonitorDateFormat : public TNamed {
 public:
    AliTPCMonitorDateFormat(Char_t* data);
    AliTPCMonitorDateFormat(const  AliTPCMonitorDateFormat &dateformat);
    AliTPCMonitorDateFormat& operator= (const AliTPCMonitorDateFormat& dateformat);
    ~AliTPCMonitorDateFormat();

    //Super Event Header
    Int_t   GetEventSize() const;
    Int_t   GetEventHeaderSize() const;
    Int_t   GetEventHeaderBaseSize() const;
    Int_t   GetEventID() const;
    Int_t   GetEventLDC() const;
    Int_t   GetEventGDC() const;

    Int_t   GetEventRunID() const;
    Int_t   GetEventVersion() const;
    Int_t   GetEventVersionMajor() const;
    Int_t   GetEventVersionMinor() const;
    Bool_t  IsEventSuperEvent() const;
    Bool_t  IsEventStartOfRun() const;
    Bool_t  IsEventEndOfRun() const;
    Bool_t  IsEventPhysicsEvent() const;
    Bool_t  IsEventSwapped() const;
    Bool_t  IsEventWrongEndian() const;

    //Sub Event Header
    void    GotoSubEventHeader();
    void    GotoNextSubEventHeader();
    Bool_t  IsLastSubEventHeader() const;

    Int_t   GetSubEventSize() const;
    Int_t   GetSubEventHeaderSize() const;
    Int_t   GetSubEventLDC() const;
    Int_t   GetSubEventGDC() const;

    Bool_t  IsSubEventSuperEvent();
    Bool_t  IsSubEventStartOfRun() const;
    Bool_t  IsSubEventEndOfRun() const;
    Bool_t  IsSubEventPhysicsEvent() const;

    //Eqipments
    void    GotoFirstEquipment();
    void    GotoNextEquipment();
    Bool_t  IsLastEquipment() const;

    Int_t   GetEquipmentSize() const;
    Int_t   GetEquipmentType() const;
    Int_t   GetEquipmentID() const;
    Int_t*  GetEquipmentTypeAttribute();
    Int_t   GetEquipmentBasicSize()  const;
    Int_t   GetEquipmentHeaderSize() const;
    Int_t   GetPayloadSize() const;

    //DATA
    Char_t* GetFirstDataPointer();
    Int_t   GetPosition() const;
    Int_t   GetPositionSubEvent() const;

 private:
    Char_t*                fdataPtr;       // pointer to data array (start, will not be changed in event)
    Char_t*                fsubEventPtr;   // pointer to SubEvent
    Char_t*                fcurrentPtr;    // pointer to current data position (header or data)
    eventHeaderStruct*     fevent;         // event and
    eventHeaderStruct*     fsubEvent;      // subevent structure
    equipmentHeaderStruct* fequipment;     // equipmemnt structure

    ClassDef(AliTPCMonitorDateFormat,1);
};

#endif


text:
using System;

namespace ApiCheck.Result.Difference
{
  public class Changed<T> : Difference
  {
    private readonly string _propertyName;
    private readonly T _referenceValue;
    private readonly T _newValue;

    public Changed(string propertyName, T referenceValue, T newValue, Severity severity)
      : base(severity)
    {
      if (propertyName == null || referenceValue == null || newValue == null)
      {
        throw new ArgumentNullException();
      }
      _propertyName = propertyName;
      _referenceValue = referenceValue;
      _newValue = newValue;
    }

    public T ReferenceValue
    {
      get { return _referenceValue; }
    }

    public T NewValue
    {
      get { return _newValue; }
    }

    public string PropertyName
    {
      get { return _propertyName; }
    }

    public override string ToString()
    {
      return string.Format("{0} has changed from '{1}' to '{2}'. Severity: {3}", PropertyName, ReferenceValue, NewValue, Severity);
    }
  }
}