text:
{-# LANGUAGE CPP #-}
-- |
-- Working with buffer_t struct
--
-- FIXME: offsets in struct are hardcoded!
module Flow.Halide.BufferT where

import Control.Monad
import Data.Int
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Array
import Foreign.Storable

#ifdef USE_CUDA
import Foreign.CUDA.Ptr (DevicePtr, nullDevPtr)
#endif

-- | Wrapper for buffer_t data type. It's managed by haskell GC
--
-- I don't remember how to use tools to generate accessors from
-- headers so I'll just hard code offsets.
newtype BufferT = BufferT (ForeignPtr ())

-- | Allocate new buffer_t and
newBufferT :: IO BufferT
newBufferT = do
  let size = 72
  fptr <- mallocForeignPtrBytes size
  -- Zero out memory
  withForeignPtr fptr $ \p ->
    forM_ [0 .. 72 `div` 8] $ \i ->
      pokeElemOff (castPtr p) i (0 :: Int64)
  return $ BufferT fptr

withBufferT :: BufferT -> (Ptr BufferT -> IO a) -> IO a
withBufferT (BufferT fptr) action =
  withForeignPtr fptr (action . castPtr)

setHostPtr :: BufferT -> Ptr () -> IO ()
setHostPtr (BufferT fptr) buf =
  withForeignPtr fptr $ \p ->
    pokeByteOff (castPtr p) 8 buf

setDirty :: Int -> BufferT -> Bool -> IO ()
setDirty off (BufferT fptr) d =
  withForeignPtr fptr $ \p ->
    poke (p `plusPtr` off) dbyte
  where
    dbyte :: Int8
    dbyte = fromIntegral (fromEnum d)

setHostDirty, setDeviceDirty :: BufferT -> Bool -> IO ()
setHostDirty = setDirty 68
setDeviceDirty = setDirty 69

setDirtyHostPtr :: BufferT -> Ptr () -> IO ()
setDirtyHostPtr buf p = setHostPtr buf p >> setHostDirty buf True

#ifdef USE_CUDA
-- foreign import ccall unsafe
halide_cuda_wrap_device_ptr :: Ptr () -> Ptr () -> DevicePtr a -> IO ()
-- Not enabled yet
halide_cuda_wrap_device_ptr _user_ctx _buffer_t _dev_ptr = return ()

setDevicePtr :: BufferT -> DevicePtr a -> IO ()
setDevicePtr (BufferT fptr) buf =
  withForeignPtr fptr $ \p ->
    halide_cuda_wrap_device_ptr nullPtr p buf

-- foreign import ccall unsafe
halide_cuda_detach_device_ptr :: Ptr () -> Ptr () -> IO (DevicePtr a)
-- Not enabled yet. Stub only
halide_cuda_detach_device_ptr _user_ctx _buffer_t = return nullDevPtr

detachDevicePtr :: BufferT -> IO (DevicePtr a)
detachDevicePtr (BufferT fptr) =
  withForeignPtr fptr $ halide_cuda_detach_device_ptr nullPtr
#endif

setBufferExtents :: BufferT -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
setBufferExtents (BufferT fptr) a b c d =
  withForeignPtr fptr $ \p ->
    pokeArray (castPtr $ p `plusPtr` 16) [a,b,c,d]

setBufferStride :: BufferT -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
setBufferStride (BufferT fptr) a b c d =
  withForeignPtr fptr $ \p ->
    pokeArray (castPtr $ p `plusPtr` 32) [a,b,c,d]

setBufferMin :: BufferT -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()
setBufferMin (BufferT fptr) a b c d =
  withForeignPtr fptr $ \p ->
    pokeArray (castPtr $ p `plusPtr` 48) [a,b,c,d]

setElemSize :: BufferT -> Int -> IO ()
setElemSize (BufferT fptr) n =
  withForeignPtr fptr $ \p ->
    pokeByteOff (castPtr p) 64 (fromIntegral n :: Int32)


text:
"use strict";

const HTMLElementImpl = require("./HTMLElement-impl").implementation;

class HTMLOListElementImpl extends HTMLElementImpl { }

module.exports = {
  implementation: HTMLOListElementImpl
};

redpajama_set_name: RedPajamaGithub


text:
package com.xym.factory.presenter.message;

import com.xym.common.factory.presenter.BaseContract;
import com.xym.factory.model.db.Session;

import java.nio.channels.SeekableByteChannel;

/**
 * Created by xym on 2017/9/3.
 */

public interface SessionContract {
    interface Presenter extends BaseContract.Presenter {

    }

    interface View extends BaseContract.RecyclerView<Presenter, Session> {

    }
}


text:
using Swisstalk.Foundation.Metadata.Reflection.Blueprints.Builder.Validation;
using Swisstalk.Foundation.Metadata.Reflection.Elements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Swisstalk.Foundation.Metadata.Reflection.Blueprints.Builder.Extraction
{
    public class DirectFieldExtractionStrategy : DirectMemberExtractionStrategy
    {
        private readonly IMemberExtractionPredicate extractionPredicate;

        public DirectFieldExtractionStrategy(IMemberExtractionPredicate extractionPredicate,
                                             IMemberNameSelector nameSelector,
                                             IEnumerable<IMemberValidator> validators) : base(nameSelector, validators)
        {
            this.extractionPredicate = extractionPredicate;
        }

        protected override ITypeElement CreateTypeElement(string name, MemberInfo memberInfo)
        {
            return new FieldTypeElement(name, (FieldInfo)memberInfo);
        }

        protected override IEnumerable<MemberInfo> FilterMembers(Type typeInfo)
        {
            return typeInfo.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                           .Where(f => extractionPredicate.IsEligible(f))
                           .Select(f => (MemberInfo)f);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/darker_gray" /><!-- From: file:/Users/Breeze/Downloads/Products/Android/IntelliJ/trunk/moxtrasdk/products/ConversationSDK/src/main/res/layout/action_item_vertical_separator.xml -->


text:
/**
 * Created by chris on 1/4/17.
 */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import { selector } from '../';
import { gameActions } from 'actions/gameActions';
import { gameplayActions } from 'actions/gameplayActions';
import { userActions } from 'actions/userActions';
import { playerActions } from 'actions/playerActions';
import GameLayout from './GameLayout';

@connect(selector, (dispatch) => ({
  actions: bindActionCreators({...gameActions, ...userActions, ...gameplayActions, ...playerActions}, dispatch)
}))
export default class GameView extends Component {
  render() {
    return (
      <div>
        <GameLayout {...this.props} />
      </div>
    );
  }
}


text:
using OrchardCore.Modules.Manifest;

[assembly: Module(
    Name = "Auto Setup",
    Author = ManifestConstants.OrchardCoreTeam,
    Website = ManifestConstants.OrchardCoreWebsite,
    Version = ManifestConstants.OrchardCoreVersion,
    Description = "The auto setup module allows to automatically install the application / tenants",
    Dependencies = new[] { "OrchardCore.Setup" },
    Category = "Infrastructure"
)]


text:
define('main', [] , function(){

    return{
        common: function(){},
        index: function(){
            setTimeout(function(){alert("hello @world@")},3000);
        }
    };
});


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>tbb::tbb_allocator< T > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

tbb_allocator

Classes |
Public Types |
Public Member Functions |
Static Public Member Functions |
List of all members

tbb::tbb_allocator< T > Class Template Reference
Memory Allocation

Meets "allocator" requirements of ISO C++ Standard, Section 20.1.5.
 More...

#include <tbb_allocator.h>

Classes

struct  	rebind

Public Types

enum  	malloc_type { scalable,
standard
 }

 	Specifies current allocator.

typedef

internal::allocator_type< T >

::value_type 	value_type

typedef value_type * 	pointer

typedef const value_type * 	const_pointer

typedef value_type & 	reference

typedef const value_type & 	const_reference

typedef size_t 	size_type

typedef ptrdiff_t 	difference_type

Public Member Functions

 	tbb_allocator (const tbb_allocator &)  throw ()

template<typename U >

 	tbb_allocator (const tbb_allocator< U > &)  throw ()

pointer 	address (reference x) const

const_pointer 	address (const_reference x) const

pointer 	allocate (size_type n, const void *=0)

 	Allocate space for n objects.

void 	deallocate (pointer p, size_type)

 	Free previously allocated block of memory.

size_type 	max_size () const   throw ()

 	Largest value for which method allocate might succeed.

template<typename U , typename... Args>

void 	construct (U *p, Args &&...args)

 	Copy-construct value at location pointed to by p.

void 	construct (pointer p, value_type &&value)

void 	construct (pointer p, const value_type &value)

void 	destroy (pointer p)

 	Destroy value at location pointed to by p.

Static Public Member Functions

static malloc_type 	allocator_type ()

 	Returns current allocator.

Detailed Description

template<typename T>

class tbb::tbb_allocator< T >

Meets "allocator" requirements of ISO C++ Standard, Section 20.1.5.

The class selects the best memory allocation mechanism available from scalable_malloc and standard malloc. The members are ordered the same way they are in section 20.4.1 of the ISO C++ standard.

The documentation for this class was generated from the following file:

tbb_allocator.h

Copyright © 2005-2017 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
<?php

namespace App\Common\Models\Bargain;

use App\Common\Models\Base\Base;

class BlackUser extends Base
{

    function __construct()
    {
        $this->setModel(new \App\Common\Models\Bargain\Mysql\BlackUser());
    }
}


text:
namespace BlogEngine.Core.Web.HttpHandlers
{
    using BlogEngine.Core.Providers;
    using System;
    using System.Web;

    /// <summary>
    /// The FileHandler serves all files that is uploaded from
    ///     the admin pages except for images.
    /// </summary>
    /// <remarks>
    /// By using a HttpHandler to serve files, it is very easy
    ///     to add the capability to stop bandwidth leeching or
    ///     to create a statistics analysis feature upon it.
    /// </remarks>
    public class FileHandler : IHttpHandler
    {
        #region Events

        /// <summary>
        ///     Occurs when the requested file does not exist;
        /// </summary>
        public static event EventHandler<EventArgs> BadRequest;

        /// <summary>
        ///     Occurs when a file is served;
        /// </summary>
        public static event EventHandler<EventArgs> Served;

        /// <summary>
        ///     Occurs when the requested file does not exist;
        /// </summary>
        public static event EventHandler<EventArgs> Serving;

        #endregion

        #region Properties

        /// <summary>
        ///     Gets a value indicating whether another request can use the <see cref = "T:System.Web.IHttpHandler"></see> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref = "T:System.Web.IHttpHandler"></see> instance is reusable; otherwise, false.</returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region Implemented Interfaces

        #region IHttpHandler

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that
        ///     implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">
        /// An <see cref="T:System.Web.HttpContext"></see>
        ///     object that provides references to the intrinsic server objects
        ///     (for example, Request, Response, Session, and Server) used to service HTTP requests.
        /// </param>
        public void ProcessRequest(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request.QueryString["file"]))
            {
                var fileName = context.Request.QueryString["file"];
                OnServing(fileName);
                fileName = !fileName.StartsWith("/") ? string.Format("/{0}", fileName) : fileName;
                try
                {

                    var file = BlogService.GetFile(string.Format("{0}files{1}",Blog.CurrentInstance.StorageLocation, fileName));
                    if (file != null)
                    {
                        context.Response.AppendHeader("Content-Disposition", string.Format("inline; filename=\"{0}\"", file.Name));
                        SetContentType(context, file.Name);
                        if (Utils.SetConditionalGetHeaders(file.DateCreated.ToUniversalTime()))
                            return;

                        context.Response.BinaryWrite(file.FileContents);
                        OnServed(fileName);
                    }
                    else
                    {
                        OnBadRequest(fileName);
                        context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot));
                    }
                }
                catch (Exception)
                {
                    OnBadRequest(fileName);
                    context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot));
                }
            }
        }

        #endregion

        #endregion

        #region Methods

        /// <summary>
        /// Called when [bad request].
        /// </summary>
        /// <param name="file">The file name.</param>
        private static void OnBadRequest(string file)
        {
            if (BadRequest != null)
            {
                BadRequest(file, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Called when [served].
        /// </summary>
        /// <param name="file">The file name.</param>
        private static void OnServed(string file)
        {
            if (Served != null)
            {
                Served(file, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Called when [serving].
        /// </summary>
        /// <param name="file">The file name.</param>
        private static void OnServing(string file)
        {
            if (Serving != null)
            {
                Serving(file, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Sets the content type depending on the filename's extension.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="fileName">
        /// The file Name.
        /// </param>
        private static void SetContentType(HttpContext context, string fileName)
        {
            context.Response.AddHeader(
                "Content-Type", fileName.EndsWith(".pdf") ? "application/pdf" : "application/octet-stream");
        }

        #endregion
    }
}


text:
using System;
using Newtonsoft.Json;

namespace Task3
{
    class Printer : IItem
    {
        /// <PRIVATE_FIELD>
        /// Über 10 Stück am Lager 10 % Rabatt
        /// </summary>
        private decimal discount = 90;

        /// <CONSTRUCTOR>
        /// Creats new Object
        /// </summary>
        /// <param name="company"></param>
        /// <param name="model"></param>
        /// <param name="newPieces"></param>
        /// <param name="newPrice"></param>
        [JsonConstructor]
        public Printer(string company, string model, uint newPieces, decimal newPrice)
        {
            if (string.IsNullOrEmpty(company)) throw new ArgumentException("Company must not be emty", nameof(company));
            if (string.IsNullOrEmpty(model)) throw new ArgumentException("Model must not be emty", nameof(model));

            if (newPieces > 99) throw new ArgumentException("Pieces must be lesser than 99.", nameof(newPieces));

            if (newPrice > 99999) throw new ArgumentException("Price must be lesser than 99999.", nameof(newPrice));
            if (newPrice < 0) throw new ArgumentException("Price must not be negative.", nameof(newPrice));

            Company = company;
            Model = model;
            Pieces = UpdatePieces(newPieces);
            Price = UpdatePrice(newPieces, newPrice);

        }
        /// <PROPERTIES>
        /// Properties from the object
        /// </summary>
        public string Company { get; }
        public string Model { get; }
        public uint Pieces { get; set; }
        public decimal Price { get; private set; }

        /// <METHODE>
        /// Neue Bestellung!
        /// </summary>
        /// <param name="Pieces"></param>
        /// <returns></returns>
        public uint UpdatePieces(uint Pieces)
        {
            if (Pieces <= 5)
            {
                Pieces += 10;
            }
            return Pieces;
        }
        /// <METHODE>
        /// Discount!
        /// </summary>
        /// <param name="Pieces"></param>
        /// <param name="Price"></param>
        /// <returns></returns>
        private decimal UpdatePrice(uint Pieces, decimal Price)
        {
            if (Pieces > 10)
            {
                Price *= discount;
                return Price / 100;
            }
        return Price;
        }

        #region IItem implementation

        /// <summary>
        /// Gets a textual description of this item.
        /// </summary>
        public string Description => Company;

        /// <summary>
        /// Gets the amount
        /// </summary>
        public uint GetPieces => Pieces;

        /// <summary>
        /// Gets a special price of this item.
        /// </summary>
        public decimal GetPrice => Price;

        #endregion

    }
}


text:
module MagicLocaleHelper
  module InstanceMethods

    private

    def get_user_language
      @accept_locale ||= get_accepted_locale
      I18n.locale = @accept_locale.to_sym
    end

    def get_accepted_locale
      if params[:locale] && !params[:locale].blank?
        params[:locale]
      elsif session[:user_locale] && !session[:user_locale].blank?
        session[:user_locale]
      elsif request.env["HTTP_ACCEPT_LANGUAGE"] && !request.env["HTTP_ACCEPT_LANGUAGE"].blank?
        if acceptable_locale?( request.env["HTTP_ACCEPT_LANGUAGE"].to_sym )
          request.env["HTTP_ACCEPT_LANGUAGE"]
        elsif acceptable_locale?( request.env["HTTP_ACCEPT_LANGUAGE"].split("-")[0].to_sym )
          request.env["HTTP_ACCEPT_LANGUAGE"].split("-")[0]
        else
          I18n.default_locale
        end
      else
        I18n.default_locale
      end
    end

    def acceptable_locale?( locale )
      system_locales.include?( locale.to_s )
    end

    def get_system_locales
      if Rails.env.production?
        MagicLocales::Locale.where(locale_state: "live")
      else
        MagicLocales::Locale.where(locale_state: ["active","live"])
      end
    end

    def system_locales
      get_system_locales.map(&:iso_code)
    end

  end

  def self.included(receiver)
    receiver.send :include, InstanceMethods
    receiver.send :helper_method, :get_user_language, :system_locales, :get_system_locales
  end

end


text:
@implementation MYDiscountListModel

-(NSDictionary *)replacedKeyFromPropertyName
{
    return @{@"desc" : @"description"};
}

@end


text:
package org.apache.vinci.transport.document;

import java.io.IOException;

import org.apache.vinci.transport.Attributes;
import org.apache.vinci.transport.Frame;
import org.apache.vinci.transport.FrameComponent;
import org.apache.vinci.transport.FrameLeaf;
import org.apache.vinci.transport.ServiceDownException;
import org.apache.vinci.transport.ServiceException;
import org.apache.vinci.transport.Transportable;
import org.apache.vinci.transport.TransportableFactory;
import org.apache.vinci.transport.VNSException;
import org.apache.vinci.transport.VinciClient;
import org.apache.vinci.transport.VinciFrame;
import org.apache.vinci.transport.util.TransportableConverter;

/**
 * This class is a VinciFrame with extensions for support of XML attributes.
 *
 * This class provides a set of "aadd" decorator methods that are almost exactly the same as the
 * "fadd" methods of the Frame class, except they return an empty set of attributes that can then be
 * populated. See the "main()" method for an example of how to use this class to easily create
 * documents with attributes.
 */

public class AFrame extends VinciFrame {
  private Attributes a = null;

  @Override
  public void setAttributes(Attributes s) {
    a = s;
  }

  @Override
  public Attributes getAttributes() {
    return a;
  }

  public Attributes createAttributes() {
    if (a == null) {
      a = new Attributes();
    }
    return a;
  }

  private static TransportableFactory aFrameFactory = new TransportableFactory() {
    @Override
    public Transportable makeTransportable() {
      return new AFrame();
    }
  };

  /**
   * Get a TransportableFactory that creates new AFrames.
   *
   * @return -
   */
  static public TransportableFactory getAFrameFactory() {
    return aFrameFactory;
  }

  public AFrame() {
    this(10);
  }

  /**
   * @pre capacity ≥ 0
   * @param capacity
   *          -
   */
  public AFrame(int capacity) {
    super(capacity);
  }

  /**
   * Create an AFrame that is a (deep) copy of the given transportable.
   *
   * @pre t != null
   * @param t
   *          -
   * @return -
   */
  public static AFrame toAFrame(Transportable t) {
    return (AFrame) TransportableConverter.convert(t, getAFrameFactory());
  }

  /**
   * Override the createSubFrame to create an AFrame of precise capacity.
   *
   * @pre tag_name != null
   * @pre initialCapacity ≥ 0
   */
  @Override
  public Frame createSubFrame(String tag_name, int initialCapacity) {
    return new AFrame(initialCapacity);
  }

  /**
   * Override the createFrameLeaf to create an AFrameLeaf so that leaf values can have attributes.
   *
   * @pre array != null
   */
  @Override
  public FrameLeaf createFrameLeaf(byte[] array) {
    return new AFrameLeaf(array, false);
  }

  /**
   * Convenience method for fetching sub-frames when their type is known to be AFrame
   *
   * @param key
   *          The key identifying the value to retrieve.
   * @exception ClassCastException
   *              if the value was not of type AFrame.
   * @return The requested value, or null if the specified key does not exist.
   *
   * @pre key != null
   */
  public AFrame fgetAFrame(String key) {
    return (AFrame) fgetFirst(key);
  }

  /**
   * Get the attributes associated with a particular key. If there is more than one matching key,
   * then the attributes of only the first matching key are returned.
   *
   * @param key
   *          The key whose attributes to fetch.
   * @return The (possibly empty) set of attributes associated with the key, or null (which
   *         indicates no such key).
   *
   * @pre key != null
   */
  public Attributes aget(String key) {
    FrameComponent comp = fgetFirst(key);
    if (comp != null) {
      Attributes not_null = comp.getAttributes();
      if (not_null == null) {
        return new Attributes();
      } else {
        return not_null;
      }
    }
    return null;
  }

  /**
   * Decorator method for adding float-valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          -
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, float val) {
    AFrameLeaf l = new AFrameLeaf(val);
    add(key, l);
    return l.createAttributes();
  }

  /**
   * Decorator method for adding float-array valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          -
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, float[] val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding double valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          -
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, double val) {
    AFrameLeaf l = new AFrameLeaf(val);
    add(key, l);
    return l.createAttributes();
  }

  /**
   * Decorator method for adding double-array valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The array to add. The array is immediately converted to string representation.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, double[] val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding int valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The int to add.
   * @return The (empty) set of attributes associated with the key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, int val) {
    AFrameLeaf l = new AFrameLeaf(val);
    add(key, l);
    return l.createAttributes();
  }

  /**
   * Decorator method for adding int-array valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The array to add. The array is immediately converted to string representation.
   * @return The set of attributes associated with the key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, int[] val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding long valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The long value to add.
   * @return The (empty) set of attributes associated with the key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, long val) {
    AFrameLeaf l = new AFrameLeaf(val);
    add(key, l);
    return l.createAttributes();
  }

  /**
   * Decorator method for adding long-array valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The array to add. The array is immediately converted to string representation.
   * @return The (empty) set of attributes associated with the key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, long[] val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding String valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The string to add.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, String val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding binary valued tags. Encodes the data in Base64.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The data to be encoded and added to this frame.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, byte[] val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val, true);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding boolean valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The boolean value to add.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, boolean val) {
    AFrameLeaf l = new AFrameLeaf(val);
    add(key, l);
    return l.createAttributes();
  }

  /**
   * Decorator method for adding Frame-valued tags.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The sub-frame to add. Note this frame is not copied.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key, AFrame val) {
    if (val != null) {
      add(key, val);
      return val.createAttributes();
    }
    return null;
  }

  /**
   * Decorator method for adding a valueless tag.
   *
   * @param key
   *          The key name.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aadd(String key) {
    AFrame sub = new AFrame(0);
    add(key, sub);
    return sub.createAttributes();
  }

  /**
   * This is a hack method which allows you to add binary-valued tags to Frames in a manner such
   * that there is no textual encoding overhead of that binary data. This is NOT necessarily
   * XTalk-1.0 compatible which formally requires only UTF-8, but it still works. Binary data added
   * using this method can be retrieved using QueryableFrame/VinciFrame getter method
   * fgetTrueBinary(String).
   *
   * WARNING: if the default XTalk parser is replaced with another one, applications that depend on
   * this method may break!
   *
   * NOTE: This method should only be used when performance hit of Base64 encoding binary data [as
   * performed by aadd(String, byte[])] is unacceptable.
   *
   * @param key
   *          The key to be associated with the value.
   * @param val
   *          The byte array to be added to the frame. Note the array is NOT copied or converted in
   *          any way.
   * @return The (empty) set of attributes associated with the added key.
   *
   * @pre key != null
   */
  public Attributes aaddTrueBinary(String key, byte[] val) {
    if (val != null) {
      AFrameLeaf l = new AFrameLeaf(val, false);
      add(key, l);
      return l.createAttributes();
    }
    return null;
  }

  /**
   * @pre in != null
   * @pre service_name != null
   *
   * @param in
   *          -
   * @param service_name
   *          -
   * @return -
   * @throws IOException
   *           -
   * @throws ServiceException
   *           -
   * @throws ServiceDownException
   *           -
   * @throws VNSException
   *           -
   * @throws IllegalStateException
   *           if VNS_HOST is not specified.
   */
  static public AFrame rpc(Transportable in, String service_name)
          throws IOException, ServiceException, ServiceDownException, VNSException {
    return (AFrame) VinciClient.sendAndReceive(in, service_name, getAFrameFactory());
  }

  /**
   * @pre in != null
   * @pre service_name != null
   * @pre socket_timeout ≥ 0
   *
   * @param in
   *          -
   * @param service_name
   *          -
   * @param socket_timeout
   *          -
   * @return -
   * @throws IOException
   *           -
   * @throws ServiceException
   *           -
   * @throws ServiceDownException
   *           -
   * @throws VNSException
   *           -
   * @throws IllegalStateException
   *           if VNS_HOST is not specified.
   */
  static public AFrame rpc(Transportable in, String service_name, int socket_timeout)
          throws IOException, ServiceException, ServiceDownException, VNSException {
    return (AFrame) VinciClient.sendAndReceive(in, service_name, getAFrameFactory(),
            socket_timeout);
  }

  /**
   * @pre in != null
   * @pre service_name != null
   * @pre socket_timeout ≥ 0
   *
   *      WARNING: This method relies on JDK-1.4 specific functions. USE IT ONLY if you don't need
   *      to maintain JDK1.3 compatability.
   *
   * @param in
   *          -
   * @param service_name
   *          -
   * @param socket_timeout
   *          -
   * @param connect_timeout
   *          -
   * @return -
   * @throws IOException
   *           -
   * @throws ServiceException
   *           -
   * @throws ServiceDownException
   *           -
   * @throws VNSException
   *           -
   * @throws IllegalStateException
   *           if VNS_HOST is not specified.
   */
  static public AFrame rpc(Transportable in, String service_name, int socket_timeout,
          int connect_timeout)
          throws IOException, ServiceException, ServiceDownException, VNSException {
    return (AFrame) VinciClient.sendAndReceive(in, service_name, getAFrameFactory(), socket_timeout,
            connect_timeout);
  }

  /*
   * public static void main(String[] args) { // EXAMPLE of creating a document with attributes.
   * AFrame f = new AFrame(); f.setAttributes((Attributes)new Attributes().fadd("foo", "bar")); //
   * Once we create the empty AFrame, we can call "aadd" to add a key/value pair and // retrieve an
   * empty set of attributes that we can then populate with attributes that will // be associated
   * with the just-added key. Note that the attribute list object is itself a // special type of
   * VinciFrame, thus we can use the standard "fadd()" methods to create the // attribute list.
   * f.aadd("KEY", "value1") // Add XML element and retrieve the attribute list object
   * .fadd("attr1", "aval1") // Add an attribute for the tag. .fadd("attr2", "aval2") // Add another
   * attribute for the tag. .fadd("attr3", "you get the point"); // Note that with fadd() you can
   * potentially create a duplicate attribute (an XML no-no), // so the "idiot proof" method is to
   * instead use fset(): f.aadd("VALUELESS_KEY") // Add a valueless tag that has a couple of
   * attributes .fset("foo", "bar") .fset("foo2", 2) .fset("foo", "replaced bar"); // Here's how to
   * create a nested AFrame: AFrame nested = new AFrame(); nested.aadd("NESTED_KEY", 1234.567)
   * .fadd("nested", "attribute"); f.aadd("NESTED_FRAME", nested) .fadd("attributename", new int[]
   * {1,2,3}); // We can use either fadd() or aadd() to add attributeless tags, though fadd is //
   * preferrable since it avoids creating the attributes object. nested.fadd("ATTRIBUTELESS_KEY",
   * "done with fadd()"); nested.aadd("ANOTHER_ATTRIBUTELESS_KEY", "done with aadd()");
   *
   * System.out.println(f.toXML()); System.out.println(); // Querying key values: String foo_value =
   * f.aget("VALUELESS_KEY").fgetString("foo");
   * System.out.println("Attribute value of foo from VALUELESS_KEY: " + foo_value);
   * System.out.println("TEST: " + toAFrame(f).toXML()); }
   */
}


text:
The data set at [http://www.stat.cmu.edu/~cshalizi/uADA/13/hw/01/calif_penn_2011.csv] contains information about the housing stock of California and Pennsylvania, as of 2011.  Information as aggregated into "Census tracts", geographic regions of a few thousand people which are supposed to be fairly homogeneous economically and socially.

_General hint_: See Recipes 10.1 and 10.2 in _The R Cookbook_ for making scatterplots.

1. _Loading and cleaning_
    a. Load the data into a dataframe called `ca_pa`.
    b. How many rows and columns does the dataframe have?
    c. Run this command, and explain, in words, what this does:

```
colSums(apply(ca_pa,c(1,2),is.na))
```
    d. The function `na.omit()` takes a dataframe and returns a new dataframe, omitting any row containing an NA value.  Use it to purge the data set of rows with incomplete data.
    e. How many rows did this eliminate?
    f. Are your answers in (c) and (e) compatible? Explain.

```r
ca_pa <- read.csv('http://www.stat.cmu.edu/~cshalizi/uADA/13/hw/01/calif_penn_2011.csv')

nrow(ca_pa)
```

```
## [1] 11275
```

```r
ncol(ca_pa)
```

```
## [1] 34
```

```r
#counts the number of NAs in each column
colSums(apply(ca_pa,c(1,2),is.na))
```

```
##                           X                     GEO.id2
##                           0                           0
##                     STATEFP                    COUNTYFP
##                           0                           0
##                     TRACTCE                  POPULATION
##                           0                           0
##                    LATITUDE                   LONGITUDE
##                           0                           0
##           GEO.display.label          Median_house_value
##                           0                         599
##                 Total_units                Vacant_units
##                           0                           0
##                Median_rooms  Mean_household_size_owners
##                         157                         215
## Mean_household_size_renters         Built_2005_or_later
##                         152                          98
##          Built_2000_to_2004                 Built_1990s
##                          98                          98
##                 Built_1980s                 Built_1970s
##                          98                          98
##                 Built_1960s                 Built_1950s
##                          98                          98
##                 Built_1940s       Built_1939_or_earlier
##                          98                          98
##                  Bedrooms_0                  Bedrooms_1
##                          98                          98
##                  Bedrooms_2                  Bedrooms_3
##                          98                          98
##                  Bedrooms_4          Bedrooms_5_or_more
##                          98                          98
##                      Owners                     Renters
##                         100                         100
##     Median_household_income       Mean_household_income
##                         115                         126
```

```r
nna <- na.omit(ca_pa)
nrow(nna)
```

```
## [1] 10605
```

```r
nrow(nna) - ncol(ca_pa)
```

```
## [1] 10571
```

```r
#results are compatible - a given row with an NA could have one or many
```

2. _This Very New House_
    a. The variable `Built_2005_or_later` indicates the percentage of houses in each Census tract built since 2005.  Plot median house prices against this variable.
    b. Make a new plot, or pair of plots, which breaks this out by state.  Note that the state is recorded in the `STATEFP` variable, with California being state 6 and Pennsylvania state 42.

```r
library(ggplot2)
library(dplyr)
```

```
##
## Attaching package: 'dplyr'
##
## The following object is masked from 'package:stats':
##
##     filter
##
## The following objects are masked from 'package:base':
##
##     intersect, setdiff, setequal, union
```

```r
nna %>% filter(STATEFP != 6)  %>% ggplot(aes(Built_2005_or_later, Median_house_value)) + geom_point(alpha=.2)
```

![](hw_files/figure-html/unnamed-chunk-2-1.png)

```r
nna %>% filter(STATEFP != 6)  %>% ggplot(aes(Built_2005_or_later, Median_house_value)) + geom_point(alpha=.3)
```

![](hw_files/figure-html/unnamed-chunk-2-2.png)

3. _Nobody Home_
The vacancy rate is the fraction of housing units which are not occupied.  The dataframe contains columns giving the total number of housing units for each Census tract, and the number of vacant housing units.
    a. Add a new column to the dataframe which contains the vacancy rate.  What are the minimum, maximum, mean, and median vacancy rates?
    b. Plot the vacancy rate against median house value.
    c. Plot vacancy rate against median house value separately for California and for Pennsylvania.  Is there a difference?

```r
nna$vrate <- nna$Vacant_units/nna$Total_units
summary(nna$vrate)
```

```
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
## 0.00000 0.03846 0.06767 0.08889 0.10920 0.96530
```

```r
nna %>% filter(STATEFP != 6)  %>% ggplot(aes(vrate, Median_house_value)) + geom_point(alpha=.2)
```

![](hw_files/figure-html/unnamed-chunk-3-1.png)

```r
nna %>% filter(STATEFP != 6)  %>% ggplot(aes(vrate, Median_house_value)) + geom_point(alpha=.3)
```

![](hw_files/figure-html/unnamed-chunk-3-2.png)

4. The column `COUNTYFP` contains a numerical code for counties within each state.  We are interested in Alameda County (county 1 in California), Santa Clara (county 85 in California), and Allegheny County (county 3 in Pennsylvania).
    a. Explain what the block of code at the end of this question is supposed to accomplish, and how it does it.
    b. Give a single line of R which gives the same final answer as the block of code.  Note: there are at least two ways to do this; you just have to find one.

```r
#finds the median of track median house values in Alameda
median(nna[nna$STATEFP == 6 && nna$COUNTYFP == 1,]$Median_house_value)
```

```
## [1] 311100
```

    c. For Alameda, Santa Clara and Allegheny Counties, what were the average percentages of housing built since 2005?

```r
mean(nna[nna$STATEFP == 6 & nna$COUNTYFP == 1,]$Built_2005_or_later)
```

```
## [1] 2.820468
```

```r
mean(nna[nna$STATEFP == 6 & nna$COUNTYFP == 85,]$Built_2005_or_later)
```

```
## [1] 3.200319
```

```r
mean(nna[nna$STATEFP != 6 & nna$COUNTYFP == 3,]$Built_2005_or_later)
```

```
## [1] 1.474219
```
    d. The `cor` function calculates the correlation coefficient between two variables.  What is the correlation between median house value and the percent of housing built since 2005 in (i) the whole data, (ii) all of California, (iii) all of Pennsylvania, (iv) Alameda County, (v) Santa Clara County and (vi) Allegheny County?
    e. Make three plots, showing median house values against median income, for Alameda, Santa Clara, and Allegheny Counties.  (If you can fit the information into one plot, clearly distinguishing the three counties, that's OK too.)

```r
acca <- c()
for (tract in 1:nrow(ca_pa)) {
  if (ca_pa$STATEFP[tract] == 6) {
    if (ca_pa$COUNTYFP[tract] == 1) {
      acca <- c(acca, tract)
    }
  }
}
accamhv <- c()
for (tract in acca) {
  accamhv <- c(accamhv, ca_pa[tract,10])
}
median(accamhv)
```


text:
Converts incoming UART signal to SPI signal which is output in 1ms intervals.

Currently set to 57600 Baud rate, requiring a 12MHz clock.

Everything is interrupt driven, so there are no synchronous wait times.

SPI output is handled by timer1 as I needed a 16bit counter for it, and other than minor deviations it appears to be highly accurate output.
Output to SPI is on exactly 1ms intervals (1,000Hz), this will require a recompile to adjust.
	to adjust this you need to set OCR1A to the following. F_CPU/(8x*Interval)-1 (Ex. for this project 12,000,000/(8x1,000) as I was using a 12MHz ceramic oscilator.

UART is buffered on both input and output.
	Working flow control, on D2 pin. Can be handled by hardware or software if you read the pin value
	Note RTS was implemented only, does not currently have a CTS line.

There are a few special commands that may be helpful, these were used in debugging
These settings are saved to EEPROM, you will need to locate the EEPROM file in the complied directory (release/debug) and have to uploaded to the chip or you will get strange results.

0xFnxx - This sets the debug status commands, these will be saved in the EEPROM, so once set they will remain that way until you change them again.
	n - Selects which "command" or debug value is being set.
		n = 0x0 - xx = character for buffer empty (Set to zero to turn off)
		n = 0x1 - xx = character for buffer underflow, cant write anything more to SPI. (Set to zero to turn off)
		n = 0x2 - xx = character for buffer full
		n = 0x3 - xx = character for buffer overflow (cant store anything more data was lost)
		n = 0xA - xx = value for UART echo, 1 for raw output, 2 for hex output, all other values disable this feature.
		n = 0xB - xx = value for SPI echo through UART, 1 for raw output, 2 for hex output, all other values disable this feature.

0xEnxx - Returns buffer fill position, and buffer state if full or empty (can indicate errors)
	n = 0x0 - Output for fill position is in hex
	n = any non-Zero - Output for fill position is a raw byte

0xDxxx - Resets buffer - E.g. buffer will be empty after this, all data inside will be lost.

All other signals are interpreted as data, they will be masked using 0x0FFF, and will be sent directly to SPI output buffer.

Note 1: This version has output range filtering between 0x47C and 0x3F3C as a firend requested it for a specific project that required that the inputs fall within this range. (This is implemented in main before processing data sent through SPI, bufUARTtoSPI.c, SPI_send_wrap. (remove or coment out the 4 lines after the "limit data range" comment do disable.

Note 2: SPI receive was not implemented as the device that the data was being sent to did not send anything back, so it was not imperative to have this feature. This can be easily implemented by added a pin read and bit shift after each SCK high, in SPIemu.c, SPI_send.

Note 3: All of the debug status commands, are processed before input buffer, however any return values will be added to output buffer, so responses may be delayed, but the action will be immediate.


text:
var defaultUserModel = require('../models/user');
module.exports = function (userModel) {
    userModel = userModel || defaultUserModel;
    return function (req, res, next) {
        //not enough parameter
        if ((typeof req.body === 'undefined') || (typeof req.body.user === 'undefined') ||
            (typeof req.body.password === 'undefined')) {
            return next();
        }
        //lets find the user
        userModel.findOne({
            name: req.body.user
        }, function (err, result) {
            if ((err) || (!result)) {
                res.tpl.error.push('Felhasznalo nincs regisztrálva!');
                return next();
            }

            //check password
            if (result.password !== req.body.password) {
                res.tpl.error.push('Hibás jelszó!');
                return next();
            }

            //login is ok, save id to session
            req.session.userid = result._id;

            //redirect to / so the app can decide where to go next
            return res.redirect('/');
        });
    };
};


text:
<?php

declare(strict_types=1);

namespace DCarbone\PHPConsulAPI\ConfigEntry;

use DCarbone\PHPConsulAPI\AbstractModel;
use DCarbone\PHPConsulAPI\Transcoding;

/**
 * Class ServiceResolverFailover
 */
class ServiceResolverFailover extends AbstractModel
{
    protected const FIELDS = [
        self::FIELD_SERVICE        => Transcoding::OMITEMPTY_STRING_FIELD,
        self::FIELD_SERVICE_SUBSET => Transcoding::OMITEMPTY_STRING_FIELD,
        self::FIELD_NAMESPACE      => Transcoding::OMITEMPTY_STRING_FIELD,
        self::FIELD_DATACENTERS    => Transcoding::OMITEMPTY_STRING_ARRAY_FIELD,
    ];

    private const FIELD_SERVICE        = 'Service';
    private const FIELD_SERVICE_SUBSET = 'ServiceSubset';
    private const FIELD_NAMESPACE      = 'Namespace';
    private const FIELD_DATACENTERS    = 'Datacenters';

    /** @var string */
    public string $Service = '';
    /** @var string */
    public string $ServiceSubset = '';
    /** @var string */
    public string $Namespace = '';
    /** @var string[] */
    public array $Datacenters = [];

    /**
     * @return string
     */
    public function getService(): string
    {
        return $this->Service;
    }

    /**
     * @param string $Service
     * @return ServiceResolverFailover
     */
    public function setService(string $Service): self
    {
        $this->Service = $Service;
        return $this;
    }

    /**
     * @return string
     */
    public function getServiceSubset(): string
    {
        return $this->ServiceSubset;
    }

    /**
     * @param string $ServiceSubset
     * @return ServiceResolverFailover
     */
    public function setServiceSubset(string $ServiceSubset): self
    {
        $this->ServiceSubset = $ServiceSubset;
        return $this;
    }

    /**
     * @return string
     */
    public function getNamespace(): string
    {
        return $this->Namespace;
    }

    /**
     * @param string $Namespace
     * @return ServiceResolverFailover
     */
    public function setNamespace(string $Namespace): self
    {
        $this->Namespace = $Namespace;
        return $this;
    }

    /**
     * @return string[]
     */
    public function getDatacenters(): array
    {
        return $this->Datacenters;
    }

    /**
     * @param string[] $Datacenters
     * @return ServiceResolverFailover
     */
    public function setDatacenters(array $Datacenters): self
    {
        $this->Datacenters = $Datacenters;
        return $this;
    }
}


text:
<?php

namespace Newscoop\Entity;

use Doctrine\ORM\Mapping AS ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Newscoop\Utils\Validation;

/**
 * Issue entity
 * @ORM\Entity
 * @ORM\Table(name="ArticleTypeMetadata")
 * @ORM\Entity(repositoryClass="Newscoop\Entity\Repository\ArticleTypeRepository")
 */
class ArticleType
{
    /**
     * @ORM\Id
     * @ORM\Column(type="string",unique=true,name="type_name")
     */
    protected $name;

    /**
     * @ORM\Id
     * @ORM\Column(type="string",unique=true,name="field_name")
     *
     * TODO MASSIVE ALERT HERE! WE HAVE THE STRING: NULL FOR NULL VALUES FROM LEGACY!!!...
     */
    protected $fieldName = 'NULL';

    /**
     * @ORM\Column(type="integer", name="fk_phrase_id", nullable=True)
     * @var int
     */
    protected $phraseId;

    /**
     * @var Doctrine\Common\Collections\ArrayCollection
     * (at) OneToMany( targetEntity="Newscoop\Entity\ArticleTypeField", mappedBy="articleType" )
     * @todo hack
     */
    protected $articleTypeFields;

    /**
     * Provides the name of the article type.
     *
     * @return string   The name of the theme.
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the name of the article type
     *
     * @param string $name
     *      The name of the article type, must not be null or empty.
     *
     * @return Newscoop\Entity\ArticleType
     *      This object for chaining purposes.
     */
    public function setName($name)
    {
        Validation::notEmpty($name, 'name');
        $this->name = $name;
        return $this;
    }

    /**
     * Provides article type phraseId.
     *
     * @return integer
     */
    public function getPhraseId()
    {
        return $this->phraseId;
    }

    /**
     * Set article type phraseId.
     */
    public function setPhraseId($phraseId)
    {
        $this->phraseId = $phraseId;

        return $this;
    }

    /**
     * Getter for fieldName
     *
     * @return string
     */
    public function getFieldName()
    {
        return $this->fieldName;
    }

    /**
     * Getter for articleTypeFields
     *
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function getArticleTypeFields()
    {
        return $this->articleTypeFields;
    }

    /**
     * Setter for articleTypeFields
     *
     * @param Doctrine\Common\Collections\ArrayCollection $articleTypeFields
     *        Value to set
     *
     * @return self
     */
    public function setArticleTypeFields(ArrayCollection $articleTypeFields)
    {
        $this->articleTypeFields = $articleTypeFields;

        return $this;
    }

	/**
	 * Used for update and stuff
     *
	 * @return string
	 */
	public function __toString()
	{
	    return $this->getName();
	}
}


text:
// We use an "Immediate Function" to initialize the application to avoid leaving anything behind in the global scope
(function () {

    /* ---------------------------------- Local Variables ---------------------------------- */
    HomeView.prototype.template = Handlebars.compile($("#home-tpl").html());
    QuestionView.prototype.template = Handlebars.compile($("#question-tpl").html());
    ResultView.prototype.template = Handlebars.compile($("#result-tpl").html());
    NoteView.prototype.template = Handlebars.compile($('#note-tpl').html());
    WageTheftView.prototype.template = Handlebars.compile($('#wage-theft-tpl').html());
    AtWorkView.prototype.template = Handlebars.compile($('#in-seattle-determination-at-work-tpl').html());
    AddressInSeattleView.prototype.template = Handlebars.compile($('#in-seattle-determination-address-tpl').html());
    ContactUsView.prototype.template = Handlebars.compile($('#contact-us-tpl').html());
    EmployerSizeAddressView.prototype.template = Handlebars.compile($('#employer-size-determination-address-tpl').html());
    EmployerSizeNameView.prototype.template = Handlebars.compile($('#employer-size-determination-name-tpl').html());
    ThanksView.prototype.template = Handlebars.compile($('#thanks-tpl').html());
    PrivacyPolicyView.prototype.template = Handlebars.compile($('#privacy-policy-tpl').html());

    Handlebars.registerPartial("contact-us-bar", $("#contact-us-bar-partial").html());
    Handlebars.registerPartial("header-bar", $("#header-bar-partial").html());
    Handlebars.registerPartial("disclaimer", $("#disclaimer-partial").html());

    var slider = new PageSlider($('body'));

    var questionService = new QuestionService();
    var answerService = new AnswerService();
    var wageService = new WageService();
    var definitionService = new DefinitionService();
    var noteService = new NoteService();
    var wageTheftReportService = new WageTheftReportService();
    var contactUsService = new ContactUsService();
    var employerSizeService = new EmployerSizeService();

    $.when(questionService.initialize(), answerService.initialize(), wageService.initialize(), definitionService.initialize(), noteService.initialize(), wageTheftReportService.initialize(), employerSizeService.initialize(), contactUsService.initialize()).done(function() {
      router.addRoute('', function() {
          slider.slidePage(new HomeView(answerService).render().$el);
      });

      router.addRoute('report-it', function() {
          slider.slidePage(new WageTheftView(wageTheftReportService).render().$el);
      });

      router.addRoute('results', function() {
        answerService.getAnswers().done(function(answers) {
          wageService.findByAnswers(answers).done(function(result) {
            slider.slidePage(new ResultView(result).render().$el);
            $('.result-view').readmore({
                collapsedHeight: $(".current-wage-view").outerHeight(),
                moreLink: "<button class=\"btn btn-block btn-primary btn-contrast\">See future wages...</button>",
                lessLink: "<button class=\"btn btn-block btn-primary btn-contrast\">Hide</button>"
            });
          });
        });
      });

      router.addRoute('question/:id', function(id) {
          questionService.findById(id).done(function(question) {
            console.log("Question: " + question);
            slider.slidePage(new QuestionView(question, answerService, definitionService).render().$el);
          });
      });

      router.addRoute('note/:id', function(id) {
          noteService.findById(id).done(function(note) {
            answerService.getAnswers().done(function(answers) {
              slider.slidePage(new NoteView(note).render().$el);

              $('.ordinance-info').readmore({
                collapsedHeight: $('.ordinance-info .explanation').outerHeight(),
                moreLink: "<button class=\"btn btn-block btn-primary btn-contrast\">Show Ordinance Text</button>",
                lessLink: "<button class=\"btn btn-block btn-primary btn-contrast\">Hide Ordinance Text</button>"
              });
            });
          });
      });

      router.addRoute('in-seattle-determination/:method', function(method) {
        if(method == "at-work"){
          slider.slidePage(new AtWorkView(answerService).render().$el);
        } else {
          slider.slidePage(new AddressInSeattleView(answerService).render().$el);
        }
      });

      router.addRoute('employer-size-determination/:method', function(method) {
        if(method == "address"){
          slider.slidePage(new EmployerSizeAddressView(employerSizeService, answerService).render().$el);
        } else {
          slider.slidePage(new EmployerSizeNameView(employerSizeService, answerService).render().$el);
        }
      });

      router.addRoute('contact-us', function() {
        slider.slidePage(new ContactUsView(contactUsService).render().$el);
      });

      router.addRoute('thanks', function() {
        slider.slidePage(new ThanksView().render().$el);
      });

      router.addRoute('privacy-policy', function() {
        slider.slidePage(new PrivacyPolicyView().render().$el);
      });

      router.start();
    });

    /* --------------------------------- Event Registration -------------------------------- */

    if ('addEventListener' in document) {
      document.addEventListener('deviceready', function () {
        StatusBar.overlaysWebView( false );
        StatusBar.backgroundColorByHexString('#ffffff');
        StatusBar.styleDefault();

        if (navigator.notification) { // Override default HTML alert with native dialog
            window.alert = function (message) {
                navigator.notification.alert(
                    message,    // message
                    null,       // callback
                    "Forgotten Incidents", // title
                    'OK'        // buttonName
                );
            };
        }
      }, false);
    }

    FastClick.attach(document.body);

    $(document).ready(function(evt) {
      ga('send', 'pageview', location.pathname + location.hash);
    });

    // Add per link tracking
    $(document.body).on('click', 'a', function(evt) {
      var match = jQuery(this).attr('href').match(/#\S*/);
      ga('send', 'pageview', location.pathname + match[0]);
    });
}());