text:
#
# 2012-01-31, Lars Bilke
# - Enable Code Coverage
#
# 2013-09-17, Joakim Söderberg
# - Added support for Clang.
# - Some additional usage instructions.
#
# USAGE:

# 0. (Mac only) If you use Xcode 5.1 make sure to patch geninfo as described here:
#      http://stackoverflow.com/a/22404544/80480
#
# 1. Copy this file into your cmake modules path.
#
# 2. Add the following line to your CMakeLists.txt:
#      INCLUDE(CodeCoverage)
#
# 3. Set compiler flags to turn off optimization and enable coverage:
#    SET(CMAKE_CXX_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
#	 SET(CMAKE_C_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
#
# 3. Use the function SETUP_TARGET_FOR_COVERAGE to create a custom make target
#    which runs your test executable and produces a lcov code coverage report:
#    Example:
#	 SETUP_TARGET_FOR_COVERAGE(
#				my_coverage_target  # Name for custom target.
#				test_driver         # Name of the test driver executable that runs the tests.
#									# NOTE! This should always have a ZERO as exit code
#									# otherwise the coverage generation will not complete.
#				coverage            # Name of output directory.
#				)
#
# 4. Build a Debug build:
#	 cmake -DCMAKE_BUILD_TYPE=Debug ..
#	 make
#	 make my_coverage_target
#
#

# Check prereqs
FIND_PROGRAM( GCOV_PATH gcov )
FIND_PROGRAM( LCOV_PATH lcov )
FIND_PROGRAM( GENHTML_PATH genhtml )
FIND_PROGRAM( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/tests)

IF(NOT GCOV_PATH)
	MESSAGE(FATAL_ERROR "gcov not found! Aborting...")
ENDIF() # NOT GCOV_PATH

IF(NOT CMAKE_COMPILER_IS_GNUCXX)
	# Clang version 3.0.0 and greater now supports gcov as well.
	MESSAGE(WARNING "Compiler is not GNU gcc! Clang Version 3.0.0 and greater supports gcov as well, but older versions don't.")

	IF(NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
		MESSAGE(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
	ENDIF()
ENDIF() # NOT CMAKE_COMPILER_IS_GNUCXX

SET(CMAKE_CXX_FLAGS_COVERAGE
    "-g -O0 --coverage -fprofile-arcs -ftest-coverage"
    CACHE STRING "Flags used by the C++ compiler during coverage builds."
    FORCE )
SET(CMAKE_C_FLAGS_COVERAGE
    "-g -O0 --coverage -fprofile-arcs -ftest-coverage"
    CACHE STRING "Flags used by the C compiler during coverage builds."
    FORCE )
SET(CMAKE_EXE_LINKER_FLAGS_COVERAGE
    ""
    CACHE STRING "Flags used for linking binaries during coverage builds."
    FORCE )
SET(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
    ""
    CACHE STRING "Flags used by the shared libraries linker during coverage builds."
    FORCE )
MARK_AS_ADVANCED(
    CMAKE_CXX_FLAGS_COVERAGE
    CMAKE_C_FLAGS_COVERAGE
    CMAKE_EXE_LINKER_FLAGS_COVERAGE
    CMAKE_SHARED_LINKER_FLAGS_COVERAGE )

IF ( NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR CMAKE_BUILD_TYPE STREQUAL "Coverage"))
  MESSAGE( WARNING "Code coverage results with an optimized (non-Debug) build may be misleading" )
ENDIF() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug"

# Param _targetname     The name of new the custom make target
# Param _testrunner     The name of the target which runs the tests.
#						MUST return ZERO always, even on errors.
#						If not, no coverage report will be created!
# Param _outputname     lcov output is generated as _outputname.info
#                       HTML report is generated in _outputname/index.html
# Optional fourth parameter is passed as arguments to _testrunner
#   Pass them in list form, e.g.: "-j;2" for -j 2
FUNCTION(SETUP_TARGET_FOR_COVERAGE _targetname _testrunner _outputname)

	IF(NOT LCOV_PATH)
		MESSAGE(FATAL_ERROR "lcov not found! Aborting...")
	ENDIF() # NOT LCOV_PATH

	IF(NOT GENHTML_PATH)
		MESSAGE(FATAL_ERROR "genhtml not found! Aborting...")
	ENDIF() # NOT GENHTML_PATH

	# Setup target
	ADD_CUSTOM_TARGET(${_targetname}

		# Cleanup lcov
		${LCOV_PATH} --directory . --zerocounters

		# Run tests
		COMMAND ${_testrunner} ${ARGV3}

		# Capturing lcov counters and generating report
		COMMAND ${LCOV_PATH} --directory . --capture --output-file ${_outputname}.info
		COMMAND ${LCOV_PATH} --remove ${_outputname}.info 'tests/*' '/usr/*' '/opt/*' '*/build/*' '*/tst_*' --output-file ${_outputname}.info.cleaned
		COMMAND ${GENHTML_PATH} --demangle-cpp -o ${_outputname} ${_outputname}.info.cleaned
		COMMAND ${CMAKE_COMMAND} -E remove ${_outputname}.info ${_outputname}.info.cleaned

		WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
		COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
	)

	# Show info where to find the report
	ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD
		COMMAND ;
		COMMENT "Open ./${_outputname}/index.html in your browser to view the coverage report."
	)

ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE

# Param _targetname     The name of new the custom make target
# Param _testrunner     The name of the target which runs the tests
# Param _outputname     cobertura output is generated as _outputname.xml
# Optional fourth parameter is passed as arguments to _testrunner
#   Pass them in list form, e.g.: "-j;2" for -j 2
FUNCTION(SETUP_TARGET_FOR_COVERAGE_COBERTURA _targetname _testrunner _outputname)

	IF(NOT PYTHON_EXECUTABLE)
		MESSAGE(FATAL_ERROR "Python not found! Aborting...")
	ENDIF() # NOT PYTHON_EXECUTABLE

	IF(NOT GCOVR_PATH)
		MESSAGE(FATAL_ERROR "gcovr not found! Aborting...")
	ENDIF() # NOT GCOVR_PATH

	ADD_CUSTOM_TARGET(${_targetname}

		# Run tests
		${_testrunner} ${ARGV3}

		# Running gcovr
		COMMAND ${GCOVR_PATH} -x -r ${CMAKE_SOURCE_DIR} -e '${CMAKE_SOURCE_DIR}/tests/'  -o ${_outputname}.xml
		WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
		COMMENT "Running gcovr to produce Cobertura code coverage report."
	)

	# Show info where to find the report
	ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD
		COMMAND ;
		COMMENT "Cobertura code coverage report saved in ${_outputname}.xml."
	)

ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE_COBERTURA


text:
package net

import "syscall"

func maxListenerBacklog() int {
	fd, err := open("/proc/sys/net/core/somaxconn")
	if err != nil {
		return syscall.SOMAXCONN
	}
	defer fd.close()
	l, ok := fd.readLine()
	if !ok {
		return syscall.SOMAXCONN
	}
	f := getFields(l)
	n, _, ok := dtoi(f[0], 0)
	if n == 0 || !ok {
		return syscall.SOMAXCONN
	}
	return n
}

func listenerSockaddr(s, f int, la syscall.Sockaddr, toAddr func(syscall.Sockaddr) Addr) (syscall.Sockaddr, error) {
	a := toAddr(la)
	if a == nil {
		return la, nil
	}
	switch v := a.(type) {
	case *TCPAddr, *UnixAddr:
		err := setDefaultListenerSockopts(s)
		if err != nil {
			return nil, err
		}
	case *UDPAddr:
		if v.IP.IsMulticast() {
			err := setDefaultMulticastSockopts(s)
			if err != nil {
				return nil, err
			}
			switch f {
			case syscall.AF_INET:
				v.IP = IPv4zero
			case syscall.AF_INET6:
				v.IP = IPv6unspecified
			}
			return v.sockaddr(f)
		}
	}
	return la, nil
}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path('../../spec_helper', __FILE__)

describe Polylog::NullLogger do
  attr_reader :null_logger
  before(:all) { @null_logger = Polylog::NullLogger.new }

  it 'responds to `<<`' do
    expect(null_logger).to respond_to :<<
    expect(null_logger << 'foo').to be_nil
  end

  it 'responds to `close`' do
    expect(null_logger).to respond_to :close
    expect(null_logger.close).to be_nil
  end

  it 'responds to `debug?`' do
    expect(null_logger).to respond_to :debug?
    expect(null_logger.debug?).to be_false
  end

  it 'responds to `info?`' do
    expect(null_logger).to respond_to :info?
    expect(null_logger.info?).to be_false
  end

  it 'responds to `warn?`' do
    expect(null_logger).to respond_to :warn?
    expect(null_logger.warn?).to be_false
  end

  it 'responds to `error?`' do
    expect(null_logger).to respond_to :error?
    expect(null_logger.error?).to be_false
  end

  it 'responds to `fatal?`' do
    expect(null_logger).to respond_to :fatal?
    expect(null_logger.fatal?).to be_false
  end

  it 'responds to `add`' do
    expect(null_logger).to respond_to :add
    expect(null_logger.add 'foo').to be_false
  end

  it 'responds to `debug`' do
    expect(null_logger).to respond_to :debug
    expect(null_logger.debug 'foo').to be_false
  end

  it 'responds to `info`' do
    expect(null_logger).to respond_to :info
    expect(null_logger.info 'foo').to be_false
  end

  it 'responds to `warn`' do
    expect(null_logger).to respond_to :warn
    expect(null_logger.warn 'foo').to be_false
  end

  it 'responds to `error`' do
    expect(null_logger).to respond_to :error
    expect(null_logger.error 'foo').to be_false
  end

  it 'responds to `fatal`' do
    expect(null_logger).to respond_to :fatal
    expect(null_logger.fatal 'foo').to be_false
  end

  it 'responds to `unknown`' do
    expect(null_logger).to respond_to :unknown
    expect(null_logger.unknown 'foo').to be_false
  end

  it 'responds to `log`' do
    expect(null_logger).to respond_to :log
    expect(null_logger.log 'foo').to be_false
  end
end


text:
import {ChangeDetectorRef, Directive, ElementRef, forwardRef, Input, OnDestroy, Renderer2} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';

import {NgbButtonLabel} from './label';

const NGB_RADIO_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => NgbRadioGroup),
  multi: true
};

let nextId = 0;

/**
 * Allows to easily create Bootstrap-style radio buttons.
 *
 * Integrates with forms, so the value of a checked button is bound to the underlying form control
 * either in a reactive or template-driven way.
 */
@Directive({selector: '[ngbRadioGroup]', host: {'role': 'radiogroup'}, providers: [NGB_RADIO_VALUE_ACCESSOR]})
export class NgbRadioGroup implements ControlValueAccessor {
  private _radios: Set<NgbRadio> = new Set<NgbRadio>();
  private _value = null;
  private _disabled: boolean;

  get disabled() { return this._disabled; }
  set disabled(isDisabled: boolean) { this.setDisabledState(isDisabled); }

  /**
   * Name of the radio group applied to radio input elements.
   *
   * Will be applied to all radio input elements inside the group,
   * unless [`NgbRadio`](#/components/buttons/api#NgbRadio)'s specify names themselves.
   *
   * If not provided, will be generated in the `ngb-radio-xx` format.
   */
  @Input() name = `ngb-radio-${nextId++}`;

  onChange = (_: any) => {};
  onTouched = () => {};

  onRadioChange(radio: NgbRadio) {
    this.writeValue(radio.value);
    this.onChange(radio.value);
  }

  onRadioValueUpdate() { this._updateRadiosValue(); }

  register(radio: NgbRadio) { this._radios.add(radio); }

  registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }

  registerOnTouched(fn: () => any): void { this.onTouched = fn; }

  setDisabledState(isDisabled: boolean): void {
    this._disabled = isDisabled;
    this._updateRadiosDisabled();
  }

  unregister(radio: NgbRadio) { this._radios.delete(radio); }

  writeValue(value) {
    this._value = value;
    this._updateRadiosValue();
  }

  private _updateRadiosValue() { this._radios.forEach((radio) => radio.updateValue(this._value)); }
  private _updateRadiosDisabled() { this._radios.forEach((radio) => radio.updateDisabled()); }
}

/**
 * A directive that marks an input of type "radio" as a part of the
 * [`NgbRadioGroup`](#/components/buttons/api#NgbRadioGroup).
 */
@Directive({
  selector: '[ngbButton][type=radio]',
  host: {
    '[checked]': 'checked',
    '[disabled]': 'disabled',
    '[name]': 'nameAttr',
    '(change)': 'onChange()',
    '(focus)': 'focused = true',
    '(blur)': 'focused = false'
  }
})
export class NgbRadio implements OnDestroy {
  static ngAcceptInputType_disabled: boolean | '';

  private _checked: boolean;
  private _disabled: boolean;
  private _value: any = null;

  /**
   * The value for the 'name' property of the input element.
   *
   * All inputs of the radio group should have the same name. If not specified,
   * the name of the enclosing group is used.
   */
  @Input() name: string;

  /**
   * The form control value when current radio button is checked.
   */
  @Input('value')
  set value(value: any) {
    this._value = value;
    const stringValue = value ? value.toString() : '';
    this._renderer.setProperty(this._element.nativeElement, 'value', stringValue);
    this._group.onRadioValueUpdate();
  }

  /**
   * If `true`, current radio button will be disabled.
   */
  @Input('disabled')
  set disabled(isDisabled: boolean) {
    this._disabled = isDisabled !== false;
    this.updateDisabled();
  }

  set focused(isFocused: boolean) {
    if (this._label) {
      this._label.focused = isFocused;
    }
    if (!isFocused) {
      this._group.onTouched();
    }
  }

  get checked() { return this._checked; }

  get disabled() { return this._group.disabled || this._disabled; }

  get value() { return this._value; }

  get nameAttr() { return this.name || this._group.name; }

  constructor(
      private _group: NgbRadioGroup, private _label: NgbButtonLabel, private _renderer: Renderer2,
      private _element: ElementRef<HTMLInputElement>, private _cd: ChangeDetectorRef) {
    this._group.register(this);
    this.updateDisabled();
  }

  ngOnDestroy() { this._group.unregister(this); }

  onChange() { this._group.onRadioChange(this); }

  updateValue(value) {
    // label won't be updated, if it is inside the OnPush component when [ngModel] changes
    if (this.value !== value) {
      this._cd.markForCheck();
    }

    this._checked = this.value === value;
    this._label.active = this._checked;
  }

  updateDisabled() { this._label.disabled = this.disabled; }
}


text:
using System;
using System.IO;
using BDDoc.Core;
using NUnit.Framework;
using System.Diagnostics.CodeAnalysis;

namespace BDDoc.Generator.UnitTest.Core
{
    [ExcludeFromCodeCoverage]
    public class ConsoleLoggerTests
    {
        //Tests

        [Test]
        public void Logging_InvalidMessage_AnExceptionIsThrown()
        {
            var logger = new ConsoleLogger();
            Assert.Throws<ArgumentNullException>(() => logger.Info(null));
            Assert.Throws<ArgumentNullException>(() => logger.Info(string.Empty));
            Assert.Throws<ArgumentNullException>(() => logger.Error(null));
            Assert.Throws<ArgumentNullException>(() => logger.Error(string.Empty));
        }

        [Test]
        public void Logging_ValidMessage_MessageLogged()
        {
            var logger = new ConsoleLogger();

            var newOut = new StringWriter();
            Console.SetOut(newOut);

            const string str1 = "InfoMessage";
            logger.Info(str1);
            Assert.AreEqual(str1 +"\r\n", newOut.ToString());

            newOut = new StringWriter();
            Console.SetOut(newOut);

            const string str2 = "ErrorMessage";
            logger.Info(str2);
            Assert.AreEqual(str2 + "\r\n", newOut.ToString());

        }
    }
}


text:
.. _installation:

Installation
============

Flask-Kibble is meant for deployment on Google App Engine. There are a number of
installation options available.

Copy Paste
----------

The simplest option, is to copy the entire flask-kibble module into your project. To
look something like this ::

    MyProject/
        app.yaml
        flask_kibble/
            __init__.py
            ...
        cron.yaml
        queue.yaml
        web.py

Package Bundling
----------------

Another option is to use a script to bundle packages into your project.

 * `fabengine`_ - ``fabengine.bundle`` will package .whl files into your project
   directory.

 .. _fabengine: http://github.com/xlevus/fabengine/

Static Assets
-------------

Kibble has its own HTML assets that you must configure your ``app.yaml``
to serve. Assuming you've copied Flask-Kibble to your project root, this
can be done like so ::

    - url: /kibble/static
      static_dir: flask_kibble/static


text:
from . import wsgi
import code
import gevent
import gevent.coros
import readline
import rlcompleter
readline.__name__  # silence pyflakes
rlcompleter.__name__  # silence pyflakes

class InteractiveMunger(object):
    def __init__(self):
        self.local = {}
        self.lock = gevent.coros.Semaphore()

    def munge(self, req):
        with self.lock:
            self.local.update(
                req=req,
                resp=None,
                )
            code.interact(
                banner=('Interactive HTTP proxy. '
                        + 'Mutate req, or set resp to a webob Response.\n'
                        + 'Press control-D to exit...'),
                local=self.local,
                )
            return self.local.get('resp')

def main():
    import gevent.monkey
    gevent.monkey.patch_all()

    import gevent.pywsgi

    inter = InteractiveMunger()

    print 'Serving on 8088...'
    proxy = wsgi.MungingHTTPProxy(munge=inter.munge)
    try:
        gevent.pywsgi.WSGIServer(('0.0.0.0', 8088), proxy.wsgi).serve_forever()
    except KeyboardInterrupt:
        pass


text:
echo Crystal
../xtime.rb ./bin_cr 11
echo C
../xtime.rb ./bin_c 11
echo Ruby
../xtime.rb ruby fannkuchredux.rb 11
echo Topaz
../xtime.rb topaz fannkuchredux.rb 11


text:
  <select onchange="if (this.value) window.location.href=this.value">
    <option value="">Navigate the docs…</option>
    <optgroup label="Getting started">
      <option value="{{ site.url }}/docs/home">欢迎</option>
      <option value="{{ site.url }}/docs/coding-style">编码规范</option>
      <option value="{{ site.url }}/docs/project-layout">项目布局</option>
    </optgroup>
    <optgroup label="Django Projects">
    </optgroup>
    <optgroup label="Django Applications">
    </optgroup>
    <optgroup label="Deployment">
    </optgroup>
    <optgroup label="Miscellaneous">
      <option value="{{ site.url }}/docs/how-to-contribute">如何贡献内容</option>
    </optgroup>
    <optgroup label="Great Readings">
    </optgroup>
  </select>


text:
using System.Runtime.Serialization;

namespace AspNetCore.XmlRpc.MetaWeblog.Models
{
    public class BlogInfo
    {
        [DataMember(Name = "url")]
        public string Url { get; set; }

        [DataMember(Name = "blogid")]
        public string Blogid { get; set; }

        [DataMember(Name = "blogName")]
        public string BlogName { get; set; }
    }
}


text:
import "@nivinjoseph/n-ext";
import { ClientApp, DefaultDialogService, DialogLocation } from "./../../src/index";
import { ScoreBoardViewModel } from "./components/score-board/score-board-view-model";
import { ComponentInstaller, Registry } from "@nivinjoseph/n-ject";
import { InmemoryTodoRepository } from "./services/todo-repository/inmemory-todo-repository";
import { DashboardViewModel } from "./pages/dashboard/dashboard-view-model";
import { TestViewModel } from "./pages/test/test-view-model";
import { TodoViewModel } from "./pages/todo/todo-view-model";
import * as Routes from "./pages/routes";
// import { BindingTestViewModel } from "./components/binding-test/binding-test-view-model";
import { ScopedService } from "./services/scoped-service";

// Vue.material.registerTheme("default", {
//     primary: "blue",
//     accent: "red",
//     warn: "red",
//     background: "grey"
// });

class Installer implements ComponentInstaller
{
    public install(registry: Registry): void
    {
        registry
            .registerSingleton("TodoRepository", InmemoryTodoRepository)
            .registerScoped("ScopedService", ScopedService)
            ;
    }
}

const pages = [DashboardViewModel, TestViewModel, TodoViewModel];
// const pages = [DashboardViewModel, TestViewModel];

const dialogService = new DefaultDialogService({
    accentColor: "#7ab53b",
    dialogLocation: DialogLocation.bottomRight,
    newestOnTop: true,
    enableCloseButton: true
    // loadingScreen: "spinner"
});

const app = new ClientApp("#app", "router-view")
    .registerDialogService(dialogService)
    .useInstaller(new Installer())
    .registerComponents(ScoreBoardViewModel)
    .registerPages(...pages)
    .useHistoryModeRouting()
    .useAsInitialRoute(Routes.dashboard)
    .useAsUnknownRoute(Routes.test)
    // .useAsDefaultPageTitle("fooo")
    // .useAsDefaultPageMetadata({name: "description", content: "this is the default description"})
    ;

app.bootstrap();


text:
package layer3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import layer2.CSV;
import layer2.Layer2;

import org.jsoup.nodes.Document;

public class Layer3 {

	public static final String ddMMyyyy = "dd.MM.yyyy";
	public static final String yyyyMMdd = "yyyy-MM-dd";

	public static String download(String inStrURL, File inFile) throws IOException {
		Document aDoc = Layer2.read(inStrURL);
		return Layer2.write(inFile, aDoc);
	}

	public static String formatDate(Date inDate) {
		return Layer3.formatDate(inDate, Layer3.ddMMyyyy);
	}

	public static String formatDate(Date inDate, String inPattern) {
		return new SimpleDateFormat(inPattern).format(inDate);
	}

	public static String formatDate(String inValue, String inPatternIn,
			String inPatternOut) {
		String formattedString = "";
		try{
			formattedString = new SimpleDateFormat(inPatternOut).format(
					new SimpleDateFormat(inPatternIn).parse(inValue))
					.toString();
		} catch (ParseException e) {
			formattedString  = inValue;
		}
		return formattedString;
	}

	/**
	 * Read file and return Jsoup.Document
	 * @param inFile
	 * @param inStrBaseURI
	 * @return
	 * @throws IOException
	 */
	public static SourceDocument readDocument(File inFile, String inStrBaseURI,
			Source inSource) throws IOException {
		Document readDocument = null;
		if (Layer2.exists(inFile)) {
			readDocument = Layer2.parse(inFile, inStrBaseURI);
		} else {
			throw new FileNotFoundException();
		}
		return new SourceDocument(readDocument, inSource);
	}

	public static Document readDocument(File inFile, String inStrBaseURI) throws IOException {
		Document readDocument = null;
		if (Layer2.exists(inFile)) {
			readDocument = Layer2.parse(inFile, inStrBaseURI);
		} else {
			throw new FileNotFoundException();
		}
		return readDocument;
	}

	/**
	 * Read URL from inStrURL and write to file
	 * @param inStrURL
	 * @param inFile
	 * @return
	 * @throws IOException
	 */
	public static SourceDocument readDocument(String inStrURL, File inFile, Source inSource) throws IOException {
		Document readDocument = Layer3.readDocument(inStrURL, inFile);
		return new SourceDocument(readDocument, inSource);
	}

	private static Document readDocument(String inStrURL, File inFile) throws IOException {
		Document readDocument = null;
		readDocument = Layer2.read(inStrURL);
		Layer2.write(inFile, readDocument);
		return readDocument;
	}

	public static String stampToday() {
		return Layer3.formatDate(new Date(), Layer3.yyyyMMdd);
	}

	public static Date toDate(String inString) {
		 Date d1 = null;
		try {
			SimpleDateFormat formatter=new SimpleDateFormat(Layer3.ddMMyyyy);
	        d1 = formatter.parse(inString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d1;
	}

	public static Date toDateyyyyMMdd(String inString) {
		 Date d1 = null;
		try {
			SimpleDateFormat formatter=new SimpleDateFormat(Layer3.yyyyMMdd);
	        d1 = formatter.parse(inString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d1;
	}

	public static String write(CSV inCSV) throws IOException {
		return Layer2.write(inCSV);
	}

	public static String write(File inFile, ArrayList<Stock> inRows) throws IOException {
		return Layer3.write(CSV.from(inFile, inRows));
	}

	public static ArrayList<String> readCSV(String inStrFileStock) throws IOException {
		return Layer2.read_(new File(inStrFileStock));
	}
}


text:
COMMAND="$1" # operation type
IPADDR=`grep "IPADDR" engine.cfg | awk -F'=' '{print $2}'` # read IP address from cfg
PORT=`grep "PORT" engine.cfg | awk -F'=' '{print $2}'` # read IP address from cfg
echo "[+]This Django instance runs \"${COMMAND}\" on ${IPADDR}:${PORT}"

case $COMMAND in
start)
	echo "[+]Starting instance on ${IPADDR}:${PORT}"
	nohup python2.7 manage.py runserver ${IPADDR}:${PORT} --settings=pdfmergeWEB.settings 2>/dev/null &
	echo "[+]Done."
	;;
stop)
	echo "[+]Stoping instance on ${IPADDR}:${PORT}"
	PID=`ps -ef | grep "runserver ${IPADDR}:${PORT}" | grep -v grep | awk '{print $2}'`
	if [ x"$PID" = x ];then
		echo "[+]Django instance NOT running. Exit."
	else
		echo "---[-]Killing PID: ${PID}"
		ps -ef | grep "runserver ${IPADDR}:${PORT}" | grep -v grep | awk '{print $2}' | xargs kill -9
		echo "[+]Done."
	fi
	;;
*)
	echo "Args not accpect, showing the instance status. You can use \"start\" or \"stop\" to enable\kill this instance."
	PID=`ps -ef | grep "runserver ${IPADDR}:${PORT}" | grep -v grep | awk '{print $2}'`
	if [ x"$PID" = x ];then
		echo "[+]Django instance NOT running as well."
	else
		echo "[+]Django instance:"
		ps -ef | grep "runserver ${IPADDR}:${PORT}" | grep -v grep
	fi
	exit 1
esac


text:
package com.spotify.helios.cli.command;

import static com.spotify.helios.cli.Utils.printMap;

import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.Json;
import com.spotify.helios.common.descriptors.ExecHealthCheck;
import com.spotify.helios.common.descriptors.HealthCheck;
import com.spotify.helios.common.descriptors.HttpHealthCheck;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.common.descriptors.PortMapping;
import com.spotify.helios.common.descriptors.RolloutOptions;
import com.spotify.helios.common.descriptors.ServicePorts;
import com.spotify.helios.common.descriptors.TcpHealthCheck;
import java.io.BufferedReader;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;

public class JobInspectCommand extends WildcardJobCommand {

  private static final DateFormat DATE_FORMATTER =
      new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");

  private static final Function<String, String> QUOTE = new Function<String, String>() {
    @Override
    public String apply(final String input) {
      return quote(input);
    }
  };

  private static final Function<PortMapping, String> FORMAT_PORTMAPPING =
      new Function<PortMapping, String>() {
        @Override
        public String apply(final PortMapping input) {
          final StringBuilder builder = new StringBuilder();
          if (input.getIp() != null) {
            builder.append(input.getIp());
          }
          builder.append(":").append(input.getInternalPort());
          if (input.getExternalPort() != null) {
            builder.append(":").append(input.getExternalPort());
          }
          if (input.getProtocol() != null) {
            builder.append("/").append(input.getProtocol());
          }
          return builder.toString();
        }
      };

  private static final Function<ServicePorts, String> FORMAT_SERVICE_PORTS =
      new Function<ServicePorts, String>() {
        @Override
        public String apply(final ServicePorts input) {
          return Joiner.on(", ").join(Ordering.natural().sortedCopy(input.getPorts().keySet()));
        }
      };

  private static String formatHealthCheck(final HealthCheck healthCheck) {
    if (healthCheck == null) {
      return "";
    }
    String str = String.format("type: %s", String.valueOf(healthCheck.getType()));
    if (healthCheck instanceof HttpHealthCheck) {
      final HttpHealthCheck httpHealthCheck = (HttpHealthCheck) healthCheck;
      str += String.format(", port: %s, path: %s", httpHealthCheck.getPort(),
          httpHealthCheck.getPath());
    } else if (healthCheck instanceof TcpHealthCheck) {
      final TcpHealthCheck tcpHealthCheck = (TcpHealthCheck) healthCheck;
      str += String.format(", port: %s", tcpHealthCheck.getPort());
    } else if (healthCheck instanceof ExecHealthCheck) {
      final ExecHealthCheck execHealthCheck = (ExecHealthCheck) healthCheck;
      str += String.format(", command: %s", Joiner.on(" ").join(execHealthCheck.getCommand()));
    }
    return str;
  }

  private static String formatRolloutOptions(final RolloutOptions options) {
    if (options == null) {
      return "";
    }

    final List<String> output = new ArrayList<>();
    output.add(String.format("timeout: %d", options.getTimeout()));
    output.add(String.format("parallelism: %d", options.getParallelism()));
    output.add(String.format("migrate: %s", options.getMigrate()));
    output.add(String.format("overlap: %s", options.getOverlap()));
    output.add(String.format("token: %s", options.getToken()));
    output.add(String.format("ignoreFailures: %s", options.getIgnoreFailures()));
    return Joiner.on(", ").join(output);
  }

  public JobInspectCommand(final Subparser parser) {
    super(parser);
    parser.help("print the configuration of a job");
  }

  public JobInspectCommand(final Subparser parser, final TimeZone timeZone) {
    super(parser);
    DATE_FORMATTER.setTimeZone(timeZone);
    parser.help("print the configuration of a job");
  }

  @Override
  protected int runWithJob(final Namespace options, final HeliosClient client,
                           final PrintStream out, final boolean json, final Job job,
                           final BufferedReader stdin)
      throws ExecutionException, InterruptedException {

    if (json) {
      out.println(Json.asPrettyStringUnchecked(job));
    } else {
      out.printf("Id: %s%n", job.getId());
      out.printf("Image: %s%n", job.getImage());
      out.printf("Created: %s%n",
          job.getCreated() == null ? "" : DATE_FORMATTER.format(new Date(job.getCreated())));
      out.printf("Expires: %s%n",
          job.getExpires() == null ? "never" : DATE_FORMATTER.format(job.getExpires()));
      out.printf("Hostname: %s%n", job.getHostname());
      out.printf("Command: %s%n", quote(job.getCommand()));
      printMap(out, "Env:   ", QUOTE, job.getEnv());
      out.printf("Health check: %s%n", formatHealthCheck(job.getHealthCheck()));
      out.printf("Grace period (seconds): %s%n", job.getGracePeriod());
      out.printf("Time to wait before kill (seconds): %s%n", job.getSecondsToWaitBeforeKill());
      printMap(out, "Metadata: ", QUOTE, job.getMetadata());
      printMap(out, "Ports: ", FORMAT_PORTMAPPING, job.getPorts());
      printMap(out, "Reg: ", FORMAT_SERVICE_PORTS, job.getRegistration());
      out.printf("Security options: %s%n", job.getSecurityOpt());
      out.printf("Network mode: %s%n", job.getNetworkMode());
      out.printf("Token: %s%n", job.getToken());
      printVolumes(out, job.getVolumes());
      out.printf("Add capabilities: %s%n", Joiner.on(", ").join(job.getAddCapabilities()));
      out.printf("Drop capabilities: %s%n", Joiner.on(", ").join(job.getDropCapabilities()));
      out.printf("Runtime: %s%n", job.getRuntime());
      out.printf("Rollout options (null options will fallback to defaults at "
                 + "rolling-update time): %s%n", formatRolloutOptions(job.getRolloutOptions()));
    }

    return 0;
  }

  private void printVolumes(final PrintStream out, final Map<String, String> volumes) {
    final String prefix = "Volumes: ";
    out.print(prefix);
    boolean first = true;
    for (final Map.Entry<String, String> entry : volumes.entrySet()) {
      if (!first) {
        out.print(Strings.repeat(" ", prefix.length()));
      }
      final String path = entry.getValue();
      final String source = entry.getKey();
      if (source == null) {
        out.printf("%s%n", path);
      } else {
        // Note that we're printing this in value:key order as that's the host:container:[rw|ro]
        // order used by docker and the helios create command.
        out.printf("%s:%s%n", path, source);
      }
      first = false;
    }
    if (first) {
      out.println();
    }
  }

  private static String quote(final String str) {
    if (str == null) {
      return "";
    }
    return CharMatcher.whitespace().matchesAnyOf(str)
           ? '"' + str + '"'
           : str;
  }

  private static List<String> quote(final List<String> ss) {
    final List<String> output = Lists.newArrayList();
    for (final String s : ss) {
      output.add(quote(s));
    }
    return output;
  }
}


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

    <title>Oxyd Demo</title>
    <meta http-equiv="Content-Type" content="text/HTML; charset=UTF-8" />
    <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <meta http-equiv="Content-Language" content="fr" />

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

Loading

            <form id="loginForm" action="#" >
                Login
                <input type="text" name="txtLogin" id="txtLogin" value=""/>
                Password
                <input type="password" name="txtPwd" id="txtPwd" value=""/>
                <input id="validLogin" value="Login" onclick='login(this.form.txtLogin.value, this.form.txtPwd.value)' type="button" />
            </form>
            <form id="openUrl" action="#" >
                Url
                <input type="text" name="txtUrl" id="txtUrl" value=""/>
                <input id="validOpenUrl" value="Valid" onclick='openWikiUrl(this.form.txtUrl.value)' type="button" />
            </form>
            <form id="formopendoc" action="#" >
                Workspace
                <input type="text" name="txtSpaceName" id="txtSpaceName" value=""/>
                Document
                <input type="text" name="txtDocName" id="txtDocName" value=""/>
                <input id="createButton" value="Create" onclick='createDocument(this.form.txtSpaceName.value, this.form.txtDocName.value)' type="button" />
                <input id="openButton" value="Open" onclick='getDocument(this.form.txtSpaceName.value, this.form.txtDocName.value)' type="button" />
            </form>

                        document: .

                        version:

Users

Actions

                                Save the document in the wiki

                                Close the document

XWiki ::
Codehaus


text:
import java.util.Scanner;
/**
 * implement accumNum() method
 * from the labs-misc Part 0
 *
 * 360-420-DW Intro to Java
 * @author PMCampbell
 * @version today
 **/
public class DriveAccum {
    public static void main(String[] args) {
			int [] test;
			test = accumNum();
			for (int i=0; i < test.length; i++)
				System.out.print(i+": " + test[i] +" ");

			System.out.println();
        } //main()
	public static int[] accumNum() {
		Scanner sc = new Scanner(System.in);
		int num, large, small, sum=0,count=0;
		int result[];
		System.out.print("enter a number: ");
		num = sc.nextInt();
		large = small = num;
		while ( num >= 0 ) {
			if (num < small) {
				small = num;
			}
			if (num > large ) {
				large = num;
			}
			count++;
			sum += num;
			System.out.print("enter a number: ");
			num = sc.nextInt();
		}
		result = new int[3];
		result[0] = large;
		result[1] = small;
		result[2] = sum/count;
		return result;
	} // accumNum()

} // class


text:
package com.amazonaws.services.directconnect.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Container for the parameters to the DescribeInterconnects operation.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeInterconnectsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    private String interconnectId;

    /**
     * @param interconnectId
     */

    public void setInterconnectId(String interconnectId) {
        this.interconnectId = interconnectId;
    }

    /**
     * @return
     */

    public String getInterconnectId() {
        return this.interconnectId;
    }

    /**
     * @param interconnectId
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeInterconnectsRequest withInterconnectId(String interconnectId) {
        setInterconnectId(interconnectId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInterconnectId() != null)
            sb.append("InterconnectId: ").append(getInterconnectId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeInterconnectsRequest == false)
            return false;
        DescribeInterconnectsRequest other = (DescribeInterconnectsRequest) obj;
        if (other.getInterconnectId() == null ^ this.getInterconnectId() == null)
            return false;
        if (other.getInterconnectId() != null && other.getInterconnectId().equals(this.getInterconnectId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInterconnectId() == null) ? 0 : getInterconnectId().hashCode());
        return hashCode;
    }

    @Override
    public DescribeInterconnectsRequest clone() {
        return (DescribeInterconnectsRequest) super.clone();
    }

}


text:
using System.ComponentModel;

namespace NMockaroo.Attributes
{
    /// <summary>
    ///     Represents the Mockaroo Words type
    /// </summary>
    public class MockarooWordsAttribute : MockarooInfoAttribute
    {
        /// <summary>
        ///     The minimum number of words
        /// </summary>
        [DefaultValue(10)]
        public int Min { get; set; }

        /// <summary>
        ///     The maximum number of words
        /// </summary>
        [DefaultValue(20)]
        public int Max { get; set; }
    }
}


text:
@interface SettingsViewController ()

- (void) notifyResetAndSync;

@end

@implementation SettingsViewController

@synthesize switchCell, switchWidget;
@synthesize username;

@synthesize longOperationDialogView;
@synthesize longOperationLabel;

+ (SettingsViewController*) settingsViewControllerWithSyncEnabled
{
  [SettingsHelper setIsSyncEnabled:YES];
  return [self settingsViewController];
}
+ (SettingsViewController*) settingsViewController
{
  return [[[SettingsViewController alloc] initWithNibName:@"SettingsView" bundle:nil] autorelease];
}

- (UITableViewCell*)switchCell
{
  if (!switchCell)
  {
    self.switchCell = [[UITableViewCell alloc] init];
    [self.switchCell release];

    self.switchWidget = [[UISwitch alloc] init];
    [self.switchWidget release];

    CGFloat x = self.switchCell.frame.size.width - 112;
    self.switchWidget.frame = CGRectMake(x,9,0,0);
    [self.switchCell addSubview:self.switchWidget];

    [self.switchWidget addTarget:self
                          action:@selector(onClickSwitch:)
                forControlEvents:UIControlEventValueChanged];
  }
  return switchCell;
}
- (UISwitch *)switchWidget
{
  // Call this first to make sure it's instantiated.
  self.switchCell;
  return switchWidget;
}

- (void)viewDidLoad
{
  [super viewDidLoad];

  self.title = @"Settings";

  self.longOperationDialogView.frame = self.navigationController.view.frame;
  [self.longOperationDialogView setAlpha:0.0];
  [self.navigationController.view addSubview:self.longOperationDialogView];

  self.isSyncEnabled = [SettingsHelper isSyncEnabled];
  self.username = [SettingsHelper username];
}

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];

  if ([self.navigationController.viewControllers count] == 1)
  {
    // In a modal view; add a button
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                          target:self
                                                                          action:@selector(dismiss:)];
    self.navigationItem.rightBarButtonItem = done;
    [done release];
  }

  [self.tableView reloadData];
}

- (void) viewDidDisappear:(BOOL)animated
{
  [super viewDidDisappear:animated];

  if ([self.navigationController.viewControllers count] > 1)
  {
    // If we go deeper (ie. to edit the username/pass), do not do this. Only do this if we go further up.
    return;
  }

  if ([SettingsHelper isSyncEnabled] && ![SettingsHelper hasUsername])
  {
    // If they don't set a username, just set sync to be disabled.
    [SettingsHelper setIsSyncEnabled:NO];
    self.isSyncEnabled = NO;
  }
}

- (void) dismiss:(id)sender
{
  [self dismissViewControllerAnimated:YES completion:nil];
}

//
// PROPERTY ACCESSOR / MUTATOR
//
- (BOOL) isSyncEnabled
{
  return self.switchWidget.on;
}
- (void) setIsSyncEnabled:(BOOL)enabled
{
  self.switchWidget.on = enabled;
}

- (void) onClickSwitch:(id)sender
{
  BOOL on = self.switchWidget.on;

  if (on == [SettingsHelper isSyncEnabled])
  {
    return;
  }

  [SettingsHelper setIsSyncEnabled:on];

  NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
  if (on)
  {
    [self.tableView insertSections:set withRowAnimation:UITableViewRowAnimationFade];
  }
  else
  {
    [self.tableView deleteSections:set withRowAnimation:UITableViewRowAnimationFade];
  }

  if ([SettingsHelper hasUsername])
  {
    [self notifyResetAndSync];
  }
}

- (void) notifyResetAndSync
{
  NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
  [dnc postNotificationName:DonezoShouldResetAndSyncNotification object:self userInfo:nil];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return 1 + self.isSyncEnabled;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  switch (section)
  {
    case 0:
      return 1;
    case 1:
      return 2;
    default:
      return 0;
  }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell *cell;

  if ([indexPath section] == 0)
  {
    cell = self.switchCell;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = @"Sync to done-zo.com";
  }
  else
  {
    NSString *cellIdentifier = @"Cell";
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                     reuseIdentifier:cellIdentifier] autorelease];
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if ([indexPath row] == 0)
    {
      cell.textLabel.text = @"Google Username";
      cell.detailTextLabel.text = self.username ? self.username : @"";
    }
    else
    {
      cell.textLabel.text = @"Google Password";
      cell.detailTextLabel.text = [SettingsHelper hasPassword] ? @"••••••••" : @"";
    }
  }

  return cell;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  if ([indexPath section] != 1)
  {
    return nil;
  }

  TextFieldViewController *tfvc = [TextFieldViewController textFieldViewController];

  tfvc.target = self;

  if ([indexPath row] == 0)
  {
    tfvc.title = @"Google Username";
    tfvc.placeholder = @"john.smith@gmail.com";
    tfvc.text = self.username;
    tfvc.textField.autocorrectionType = UITextAutocorrectionTypeNo;
    tfvc.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    tfvc.textField.keyboardType = UIKeyboardTypeEmailAddress;
    tfvc.saveAction = @selector(saveUsername:);
  }
  else
  {
    tfvc.title = @"Google Password";
    tfvc.textField.secureTextEntry = YES;
    tfvc.saveAction = @selector(savePassword:);
  }

  [self.navigationController pushViewController:tfvc animated:YES];

  return nil;
}

- (void)reallySaveUsername
{
  if ([SettingsHelper hasUsername])
  {
    // It is possible that there is no username set currently, if they first set it to a blank box.
    [[NSNotificationCenter defaultCenter] postNotificationName:DonezoShouldSyncNotification object:self];
  }

  [self.longOperationLabel setText:@"Syncing existing account..."];

  [UIView beginAnimations:@"Show View" context:nil];
  [self.longOperationDialogView setAlpha:1.0];
  [UIView commitAnimations];

  [self performSelectorInBackground:@selector(reallySaveUsernameOperation:) withObject:self];
}

- (void)reallySaveUsernameOperation:(id)sender
{
  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

  DNZOAppDelegate *appDelegate = (DNZOAppDelegate *)[[UIApplication sharedApplication] delegate];
  [appDelegate waitForSyncToFinishAndReinitializeDatastore];

  [SettingsHelper setUsername:self.username];
  [SettingsHelper resetPassword];

  [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];

  [[NSNotificationCenter defaultCenter] postNotificationName:DonezoShouldResetNotification object:self];

  [UIView beginAnimations:@"Hide View" context:nil];
  [self.longOperationDialogView setAlpha:0.0];
  [UIView commitAnimations];

  [pool release];
}

- (void)dontSaveUsername
{
  self.username = [SettingsHelper username];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  switch(buttonIndex)
  {
    // save:
    case 1:
      [self reallySaveUsername];
      break;

    // cancel
    case 0:
    default:
      [self dontSaveUsername];
      [self.tableView reloadData];
      break;
  }
}

- (void)saveUsername:(id)sender
{
  TextFieldViewController *tfvc = (TextFieldViewController*)sender;
  self.username = [tfvc.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

  if ([self.username length] == 0)
  {
    // Do not change the sync'd username; that is, the app has had a chance to sync
    // to a different account already, so don't erase the fact that it has synced.
    [SettingsHelper setUsername:self.username];
  }
  else if ([SettingsHelper hasSyncedUsername] &&
           ![[self.username lowercaseString] isEqualToString:[[SettingsHelper syncedUsername] lowercaseString]])
  {
    UIAlertView *alertTest = [[UIAlertView alloc]
                              initWithTitle:@"Really change user?"
                                    message:@"Changing your synced account will remove the tasks stored "
                                             "on your phone. After setting the new account's password, "
                                             "the new tasks will be downloaded."
                                   delegate:self
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"Change User",nil ];

    [alertTest show];
    [alertTest autorelease];
  }
  else
  {
    [SettingsHelper setUsername:self.username];
  }
}

- (void)savePassword:(id)sender
{
  TextFieldViewController *tfvc = (TextFieldViewController*)sender;
  [SettingsHelper setPassword:tfvc.text];

  [self notifyResetAndSync];
}

- (void)dealloc
{
  [username release];
  [switchCell release];
  [switchWidget release];
  [longOperationDialogView release];
  [longOperationLabel release];
  [super dealloc];
}

@end


text:
package threadlocal的使用;

public class Test {

	private static class TestClient extends Thread {
		private Test sn;
		public TestClient(Test sn) {
			this.sn = sn;
		}
		public void run() {
			for (int i = 0; i < 3; i++) {
				// ④每个线程打出3个序列值
				System.out.println("thread[" + Thread.currentThread().getName() + "] --> sn[" + sn.getNextNum() + "]");
			}
		}
	}

	// ①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
	private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
		public Integer initialValue() {
			return 0;
		}
	};

	// ②获取下一个序列值
	public int getNextNum() {
		seqNum.set(seqNum.get() + 1);
		return seqNum.get();
	}

	public static void main(String[] args) {
		Test sn = new Test();
		// ③ 3个线程共享sn,各自产生序列号
		TestClient t1 = new TestClient(sn);
		TestClient t2 = new TestClient(sn);
		TestClient t3 = new TestClient(sn);
		t1.start();
		t2.start();
		t3.start();
	}

}


text:
/*
 * [ECE XX37] - Embedded Systems
 * Spring 2017
 *
 * Team 6
 * Authors: Robert Duenez, Katherine Perez, Sikender Shahid
 *
 * Milestone 10: Rewriting of main in RTOS
 *
 */

//----------------------------------------
// BIOS header files
//----------------------------------------
#include <xdc/std.h>  						//mandatory - have to include first, for BIOS types
#include <ti/sysbios/BIOS.h> 				//mandatory - if you call APIs like BIOS_start()
#include <xdc/runtime/Log.h>				//needed for any Log_info() call
#include <xdc/cfg/global.h>

#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "inc/hw_gpio.h"
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/adc.h"
#include "driverlib/debug.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "driverlib/pwm.h"
#include "driverlib/rom.h"
#include "driverlib/sysctl.h"
#include "driverlib/timer.h"
#include "driverlib/uart.h"
#include "utils/uartstdio.c"
#include "string.h"

/********************************************************************************************************
 *                                     ADC get_adc_value Functions                                      *
 ********************************************************************************************************/
uint32_t rightDistance(void){
    //ADC_CTL_CH0
	uint32_t ui32ADC0Value[4];
	ADCIntClear(ADC0_BASE, 1);
	ADCProcessorTrigger(ADC0_BASE, 1);
	while(!ADCIntStatus(ADC0_BASE, 1, false)){}
	ADCSequenceDataGet(ADC0_BASE, 1, ui32ADC0Value);
    return ui32ADC0Value[0];
}
uint32_t frontDistance(void){
    //ADC_CTL_CH1
	uint32_t ui32ADC0Value[4];
	ADCIntClear(ADC0_BASE, 2);
	ADCProcessorTrigger(ADC0_BASE, 2);
	while(!ADCIntStatus(ADC0_BASE, 2, false)){}
	ADCSequenceDataGet(ADC0_BASE, 2, ui32ADC0Value);
    return ui32ADC0Value[0];
}
/********************************************************************************************************
 *                                             PWM Functions                                            *
 ********************************************************************************************************/
#define PWM_FREQUENCY 10000

unsigned int ui32Load = 0;
unsigned int ui32PWMClock = 0;
unsigned int ui8Adjust = 83;

void move_forward(void){
	GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_2|GPIO_PIN_7, GPIO_PIN_2|GPIO_PIN_7);
}

void move_reverse(void){
    GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_2|GPIO_PIN_7, 0|0);
}

void move_cw(void){
    GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_2|GPIO_PIN_7, GPIO_PIN_2|0);
}

void move_ccw(void){
    GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_2|GPIO_PIN_7, GPIO_PIN_7|0);
}

void PWMStart(void){
	PWMOutputState(PWM1_BASE, (PWM_OUT_0_BIT|PWM_OUT_1_BIT), true);
	PWMSetSpeed(ui32Load, ui32Load);
}

void PWMStop(void){
	PWMOutputState(PWM1_BASE, (PWM_OUT_0_BIT|PWM_OUT_1_BIT), false);
}

void PWMUserSetSpeed(void){
	unsigned char inSpeed[3];
	UARTprintf("Enter Speed (1-100): ");
	UARTgets(inSpeed, 4);
	PWMSetSpeed(atoi(inSpeed), atoi(inSpeed));
}

void PWMSetSpeed(unsigned int left_adjust, unsigned int right_adjust){
    PWMPulseWidthSet(PWM1_BASE, PWM_OUT_0, left_adjust * ui32Load/100);
    PWMPulseWidthSet(PWM1_BASE, PWM_OUT_1, right_adjust * ui32Load/100);
}
/********************************************************************************************************
 *                                          Double Buffer                                               *
 ********************************************************************************************************/

char distanceBuffer[20];
char distanceBuffer2[20];
int distanceBufferCount = 0;
void distanceBufferLog(int ErrorValue){
    if(distanceBufferCount != 20){
        distanceBuffer[distanceBufferCount] = ErrorValue;
        distanceBufferCount++;
    }
    else{
        for(distanceBufferCount = 0 ; distanceBufferCount <20 ; distanceBufferCount++){
            UARTprintf("%d", distanceBuffer[distanceBufferCount]);
            UARTprintf("\n");
        }
        swap(distanceBuffer, distanceBuffer2);
        distanceBufferCount = 0;
    }
}

void swap(char * buffer1 , char * buffer2 ){
    char * temp = buffer1;
    buffer1 = buffer2;
    buffer2 = temp;
}

/********************************************************************************************************
 *                                       PID Control Functions                                          *
 ********************************************************************************************************/
uint32_t initialCount, finalCount, count1;
bool blackLineFound(void)
{

//  while(GPIOPinRead(GPIO_PORTE_BASE, GPIO_PIN_4) > 0 || GPIOPinRead(GPIO_PORTE_BASE, GPIO_PIN_5) > 0)
//  {
//      TimerCount++;
//      if(TimerCount > 1400) {
//          UARTprintf("Stop at timer count %d \n", TimerCount);
//          PWMStop();
//          return false;
//      }
//  }
    //UARTprintf("      Count %d \n", TimerCount);

//  if(TimerCount > 1000)
//      {
//          UARTprintf("FLAG TOGGLE %d \n\n", TimerCount);
//          return true;
//      }
//  else
//      return false;
    ///////
    TimerDisable(TIMER2_BASE, TIMER_A);
    TimerEnable(TIMER0_BASE,TIMER_BOTH);
    GPIOPinTypeGPIOOutput(GPIO_PORTE_BASE, GPIO_PIN_4 );
    GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_4  , GPIO_PIN_4  );
    SysCtlDelay(100);
    GPIOPinTypeGPIOInput(GPIO_PORTE_BASE, GPIO_PIN_4  );
    count1 = 0;
    initialCount = TimerValueGet(TIMER0_BASE, TIMER_A);
    while(GPIOPinRead(GPIO_PORTE_BASE, GPIO_PIN_4 )){
    };
    finalCount = TimerValueGet(TIMER0_BASE, TIMER_A);
    count1 = finalCount - initialCount;
    UARTprintf("count %u \n", count1);
    if (count1 >= 10000){
        PWMStop();
        return false;
    }
//    if (count1 >= 600 && count1 <10000){
//        return true;
//    }
    TimerDisable(TIMER0_BASE, TIMER_BOTH);
    TimerEnable(TIMER2_BASE, TIMER_A);
    return false;
}

void PIDStart(void) {
	// enable Timer2, SubtimerA
	TimerEnable(TIMER2_BASE, TIMER_A);
	unsigned int speed = 2840;
	PWMSetSpeed(speed, speed);
	PWMStart();
	move_forward();
}

const uint32_t front_target = 2200;
uint32_t cur_pos;
const uint32_t target_dist = 2000;
int proportional =0;
int last_proportional = 0;
int derivative = 0;
int integral = 0;
const float p_const = 10;
const float i_const =  3500;
const float d_const = .0075;
const int max = 100;
int dataCollectionToggle = 0;
int power_difference = 0;
bool lineDetectToggle= 0;

int computePID(void){
	if(blackLineFound()){
		lineDetectToggle = !(lineDetectToggle);
	}

	// PID calculations
	cur_pos = rightDistance();
	proportional = cur_pos - target_dist;
	derivative = proportional - last_proportional;
	integral += proportional;
	last_proportional = proportional;

	power_difference = proportional/p_const + derivative * d_const + integral/i_const;

	if(lineDetectToggle && dataCollectionToggle){
	    distanceBufferLog(power_difference);
	}
	dataCollectionToggle = 1 - dataCollectionToggle; // or dataCollectionToggle = !dataCollectionToggle;

	if (power_difference > max){
		power_difference = max;}
	if (power_difference < -max){
		power_difference = -max;}

//	UARTprintf("Power Difference: %d\n",power_difference);

	  if(power_difference < 0){
		  PWMSetSpeed(max, 101 + power_difference);
	  }
	  else if(power_difference > 0){
		  PWMSetSpeed(max + 1 -power_difference, max);
	  }
	  else{
		  PWMSetSpeed(max, max);
	  }
	  //front_target = 2200
	  if(frontDistance() > front_target){
		  while (!(frontDistance() < 1500))
	  			move_cw();
		  move_forward();
	  }

	  if(rightDistance() < 800 )
	  {
		  while(!(rightDistance() > 2400))
	  		{
	  			move_forward();
	  			PWMPulseWidthSet(PWM1_BASE, PWM_OUT_0, ui32Load);
	  			PWMPulseWidthSet(PWM1_BASE, PWM_OUT_1, ui32Load/2);
	  		}
	  	}
	return power_difference;
}

/********************************************************************************************************
 *                                     Timer2 Interrupt Handler                                         *
 ********************************************************************************************************/

void Timer2IntHandler(void) {
	TimerIntClear(TIMER2_BASE, TIMER_TIMA_TIMEOUT);
	Swi_post(PIDswi);
}

/********************************************************************************************************
 *                                     UART Handler and Command Functions                               *
 ********************************************************************************************************/

typedef enum{
    HH=0,
    MS=2,
    P0=4,
    MF=6,
    RR=8,
    SS=10,
    LR=12,
    LG=14,
    GO=16,
    R0=18,
    R1=20,
    TD=22,
    DS=24,
    ES=26,
    DC=28,
    ER=30,
    BL=32
}Commands;

uint8_t CharacterCount = 0;

char responseGet(char chars[]){
    static const char * LookupTable[] = {
            "HH", " Enter 2char function      ",
            "MS", " PWM enable                ",
            "P0", " PWM disable               ",
            "MF", " Moving Forward            ",
            "RR", " Right Wheel Reverse       ",
            "SS", " Set Speed                 ",
            "LR", " Left Wheel Reverse        ",
            "LG", " Light Get                 ",
            "GO", " PID initiated             ",
            "R0", " Read Front Distance Sensor",
            "R1", " Read Right Distance Sensor",
            "TD", " Toggle Data Acquisition   ",
            "DS", " Post Drive Semaphore      ",
            "ES", " Emergency Stop            ",
            "DC", " Drive Clock Start         ",
            "ER", " Error                     ",
            "BL", " Black Line                ",
    };

    char index = 0;
    if(!strcmp(chars,"HH"))
        index = HH;
    else if(!strcmp(chars,"MS"))
        index = MS;
    else if(!strcmp(chars,"P0"))
        index = P0;
    else if(!strcmp(chars,"MF"))
        index = MF;
    else if(!strcmp(chars,"RR"))
        index = RR;
    else if(!strcmp(chars,"SS"))
        index = SS;
    else if(!strcmp(chars,"LR"))
        index = LR;
    else if(!strcmp(chars,"LG"))
    	index = LG;
    else if(!strcmp(chars,"GO"))
        index = GO;
    else if(!strcmp(chars,"R0"))
        index = R0;
    else if(!strcmp(chars,"R1"))
        index = R1;
    else if(!strcmp(chars,"TD"))
        index = TD;
    else if(!strcmp(chars,"DS"))
        index = DS;
    else if(!strcmp(chars,"ES"))
        index = ES;
    else if(!strcmp(chars,"DC"))
        index = DC;
    else if(!strcmp(chars,"BL"))
        index = BL;
    else
        index = ER;

    UARTprintf("\n");
    UARTprintf(LookupTable[index]);
    UARTCharPut(UART1_BASE, 0x20);
    UARTprintf(LookupTable[index + 1]);
    UARTprintf(" \r\n");
    return index;
}

void getFunction(char function){
    switch (function) {
    case R1:
        rightDistance();
        frontDistance();
        break;
    case MF:
    	move_forward();
        break;
    case RR:
    	move_cw();
        break;
    case LR:
    	move_ccw();
        break;
    case ES:
        PWMStop();
        break;
    case SS:
    	PWMUserSetSpeed();
        break;
    case MS:
        PWMStart();
        break;
    case GO:
        PIDStart();
        break;
    case BL:
        blackLineFound();
        break;
    default:
        UARTprintf("Error \n");
        break;
    }
}

void UARTIntHandler(void)
{
    char characters[2] = " ";
    char function = 0;
    uint32_t ui32Status;
    //get interrupt status
    ui32Status = UARTIntStatus(UART1_BASE, true);
    //clear the asserted interrupts
    UARTIntClear(UART1_BASE, ui32Status);
    UARTgets(characters, 3);
    function = responseGet(characters);
    getFunction(function);
    UARTprintf("Enter Command: ");
}
/********************************************************************************************************
 *                                     Interface Initialization Functions                               *
 ********************************************************************************************************/

void UARTInit(void){
    // UART Module 1
    // Port PB0 RX
    // Port PB1 TX

	SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
	// configuration of GPIO pins and types
	GPIOPinConfigure(GPIO_PB0_U1RX);
    GPIOPinConfigure(GPIO_PB1_U1TX);
	GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);
	// set clock and standard I/O
	UARTClockSourceSet(UART1_BASE, UART_CLOCK_PIOSC);
	UARTStdioConfig(1, 115200, 16000000);
	// Interrupt Enabled for Data on TX and RX
	IntEnable(INT_UART1);
	UARTIntEnable(UART1_BASE, UART_INT_RX | UART_INT_RT);
}

void ADCInit(void) {
    //  Port PE3 AIN-0 - ADC_CTL_CH0 - RIGHT DISTANCE SENSOR
    //  Port PE2 AIN-1 - ADC_CTL_CH1 - FRONT DISTANCE SENSOR
    //  Port PE5 AIN-8 - ADC_CTL_CH8 - RIGHT LIGHT SENSOR
    //  Port PE4 AIN-9 - ADC_CTL_CH9 - LEFT LIGHT SENSOR

	SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);

	GPIOPinTypeADC(GPIO_PORTE_BASE, GPIO_PIN_3 | GPIO_PIN_2);

	ADCSequenceConfigure(ADC0_BASE, 1, ADC_TRIGGER_PROCESSOR, 0);

	ADCSequenceConfigure(ADC0_BASE, 2, ADC_TRIGGER_PROCESSOR, 0);

	ADCSequenceStepConfigure(ADC0_BASE, 1, 0, ADC_CTL_CH0 | ADC_CTL_END | ADC_CTL_IE);
	ADCSequenceStepConfigure(ADC0_BASE, 2, 0, ADC_CTL_CH1 | ADC_CTL_END | ADC_CTL_IE);

	ADCSequenceEnable(ADC0_BASE, 1);
	ADCSequenceEnable(ADC0_BASE, 2);
}

void PWMInit(void)
{
    //  Port PE1 - MODE = 1
    //  Port PD3 - PHASE PIN - RIGHT MOTOR  // changed to PD7
    //  Port PD1 - PWM PIN   - RIGHT MOTOR
    //  Port PD2 - PHASE PIN - LEFT MOTOR
    //  Port PD0 - PWM PIN   - LEFT MOTOR
    // FORWARD 0 BITMASKED  // LOGIC SWITCHED - > FORWARD 1 BITMASKED
    // REVERSE 1 BITMASKED  // LOGIC SWITCHED - > REVERSE 0 BITMASKED

	SysCtlPWMClockSet(SYSCTL_PWMDIV_64);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM1);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);

	// hardware unlock for gpio pd7
	HWREG(GPIO_PORTD_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
	HWREG(GPIO_PORTD_BASE + GPIO_O_CR) |= 0x80;
    HWREG(GPIO_PORTD_BASE + GPIO_O_AFSEL) &= ~0x80;
    HWREG(GPIO_PORTD_BASE + GPIO_O_DEN) |= 0x80;
    HWREG(GPIO_PORTD_BASE + GPIO_O_LOCK) = 0;

	GPIOPinTypePWM(GPIO_PORTD_BASE, GPIO_PIN_0 | GPIO_PIN_1);
	GPIOPinTypeGPIOOutput(GPIO_PORTD_BASE,GPIO_PIN_2 | GPIO_PIN_7);
	GPIOPinTypeGPIOOutput(GPIO_PORTE_BASE,GPIO_PIN_1);
	GPIOPinConfigure(GPIO_PD0_M1PWM0);
	GPIOPinConfigure(GPIO_PD1_M1PWM1);

	ui32PWMClock = SysCtlClockGet() / 64;
	ui32Load = (ui32PWMClock / PWM_FREQUENCY) - 1;
	PWMGenConfigure(PWM1_BASE, PWM_GEN_0, PWM_GEN_MODE_DOWN);
	PWMGenPeriodSet(PWM1_BASE, PWM_GEN_0, ui32Load);
	// enable mode = 1
	GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_1, GPIO_PIN_1);

	PWMPulseWidthSet(PWM1_BASE, PWM_OUT_0, 1);
	PWMPulseWidthSet(PWM1_BASE, PWM_OUT_1, 1);
	PWMGenEnable(PWM1_BASE, PWM_GEN_0);
}

void TimerInit(void) {

	uint32_t ui32Period;

	SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER2);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
	// enable timer0 as 32-bit timer in periodic mode
	TimerConfigure(TIMER2_BASE, TIMER_CFG_A_PERIODIC);
	TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC_UP);
	// Interrupt at 20Hz
	ui32Period = (SysCtlClockGet() / 20);
	TimerLoadSet(TIMER2_BASE, TIMER_A, ui32Period-1);
	// enable timer2a interrupt vector
	IntEnable(INT_TIMER2A);
	// enable specific vector within timer to generate an interrupt
	TimerIntEnable(TIMER2_BASE, TIMER_TIMA_TIMEOUT);
}

int main(void) {
	//Set CPU Clock to 40MHz. 400MHz PLL/2 = 200 DIV 4 = 50MHz
	SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);

	UARTInit();
	ADCInit();
	PWMInit();
	TimerInit();

	UARTprintf("Embedded Systems - TEAM 6\r\n");
	UARTprintf("Type command:");

	BIOS_start();
}


text:
#include <limits>
#include "RayTracer.h"
#include "Image.h"
#include "Object.h"
#include "Sphere.h"
#include "Triangle.h"
#include "Intersection.h"
#include "Light.h"
#include "Air.h"
#include "ShinyColor.h"
#include "FlatColor.h"
#include "Checkerboard.h"
#include "Marble.h"
#include "Wood.h"
#include "Glass.h"
#include "NormalMap.h"
#include "Turbulence.h"
#include "CrissCross.h"
#include "BSP.h"

using namespace std;

RayTracer::RayTracer(int width_, int height_, int maxReflections_, int superSamples_,
 int depthComplexity_) : width(width_), height(height_),
 maxReflections(maxReflections_), superSamples(superSamples_), camera(Camera()),
 imageScale(1), depthComplexity(depthComplexity_), dispersion(5.0f), raysCast(0),
 startingMaterial(new Air()) {}

RayTracer::~RayTracer() {
   for (vector<Object*>::iterator itr = objects.begin(); itr < objects.end(); itr++) {
      delete *itr;
   }

   for (vector<Light*>::iterator itr = lights.begin(); itr < lights.end(); itr++) {
      delete *itr;
   }

   delete startingMaterial;
}

void RayTracer::traceRays(string fileName) {
   int columnsCompleted = 0;
   camera.calculateWUV();
   Image image(width, height);

   // Reset depthComplexity to avoid unnecessary loops.
   if (dispersion < 0) {
      depthComplexity = 1;
   }

   imageScale = camera.screenWidth / (float)width;

   #pragma omp parallel for
   for (int x = 0; x < width; x++) {
      // Update percent complete.
      columnsCompleted++;
      float percentage = columnsCompleted/(float)width * 100;
      cout << '\r' << (int)percentage << '%';
      fflush(stdout);

      for (int y = 0; y < height; y++) {
         image.pixel(x, y, castRayForPixel(x, y));
      }
   }

   cout << "\rDone!" << endl;
   cout << "Rays cast: " << raysCast << endl;

   image.WriteTga(fileName.c_str(), false);
}

Color RayTracer::castRayForPixel(int x, int y) {
   double rayX = (x - width / 2)/2.0;
   double rayY = (y - height / 2)/2.0;
   double pixelWidth = rayX - (x + 1 - width / 2)/2.0;
   double sampleWidth = pixelWidth / superSamples;
   double sampleStartX = rayX - pixelWidth/2.0;
   double sampleStartY = rayY - pixelWidth/2.0;
   double sampleWeight = 1.0 / (superSamples * superSamples);
   Color color;

   for (int x = 0; x < superSamples; x++) {
      for (int y = 0; y < superSamples; y++) {
         Vector imagePlanePoint = camera.lookAt -
          (camera.u * (sampleStartX + (x * sampleWidth)) * imageScale) +
          (camera.v * (sampleStartY + (y * sampleWidth)) * imageScale);

         color = color + (castRayAtPoint(imagePlanePoint) * sampleWeight);
      }
   }

   return color;
}

Color RayTracer::castRayAtPoint(const Vector& point) {
   Color color;

   for (int i = 0; i < depthComplexity; i++) {
      Ray viewRay(camera.position, point - camera.position, maxReflections,
       startingMaterial);

      if (depthComplexity > 1) {
         Vector disturbance(
          (dispersion / RAND_MAX) * (1.0f * rand()),
          (dispersion / RAND_MAX) * (1.0f * rand()),
          0.0f);

         viewRay.origin = viewRay.origin + disturbance;
         viewRay.direction = point - viewRay.origin;
         viewRay.direction = viewRay.direction.normalize();
      }

      color = color + (castRay(viewRay) * (1 / (float)depthComplexity));
   }

   return color;
}

Color RayTracer::castRay(const Ray& ray) {
   raysCast++;
   Intersection intersection = getClosestIntersection(ray);

   if (intersection.didIntersect) {
      return performLighting(intersection);
   } else {
      return Color();
   }
}

bool RayTracer::isInShadow(const Ray& ray, double lightDistance) {
   Intersection intersection = getClosestIntersection(ray);

   return intersection.didIntersect && intersection.distance < lightDistance;
}

Intersection RayTracer::getClosestIntersection(const Ray& ray) {
   // Merely use the BSP for intersections.
   return bsp->getClosestIntersection(ray);
}

Color RayTracer::performLighting(const Intersection& intersection) {
   Color color = intersection.getColor();
   Color ambientColor = getAmbientLighting(intersection, color);
   Color diffuseAndSpecularColor = getDiffuseAndSpecularLighting(intersection, color);
   Color reflectedColor = getReflectiveRefractiveLighting(intersection);

   return ambientColor + diffuseAndSpecularColor + reflectedColor;
}

Color RayTracer::getAmbientLighting(const Intersection& intersection, const Color& color) {
   return color * 0.2;
}

Color RayTracer::getDiffuseAndSpecularLighting(const Intersection& intersection,
 const Color& color) {
   Color diffuseColor(0.0, 0.0, 0.0);
   Color specularColor(0.0, 0.0, 0.0);

   for (vector<Light*>::iterator itr = lights.begin(); itr < lights.end(); itr++) {
      Light* light = *itr;
      Vector lightOffset = light->position - intersection.intersection;
      double lightDistance = lightOffset.length();
      /**
       * TODO: Be careful about normalizing lightOffset too.
       */
      Vector lightDirection = lightOffset.normalize();
      double dotProduct = intersection.normal.dot(lightDirection);

      /**
       * Intersection is facing light.
       */
      if (dotProduct >= 0.0f) {
         Ray shadowRay = Ray(intersection.intersection, lightDirection, 1,
          intersection.ray.material);

         if (isInShadow(shadowRay, lightDistance)) {
            /**
             * Position is in shadow of another object - continue with other lights.
             */
            continue;
         }

         diffuseColor = (diffuseColor + (color * dotProduct)) *
          light->intensity;
         specularColor = specularColor + getSpecularLighting(intersection, light);
      }
   }

   return diffuseColor + specularColor;
}

Color RayTracer::getSpecularLighting(const Intersection& intersection,
 Light* light) {
   Color specularColor(0.0, 0.0, 0.0);
   double shininess = intersection.endMaterial->getShininess();

   if (shininess == NOT_SHINY) {
      /* Don't perform specular lighting on non shiny objects. */
      return specularColor;
   }

   Vector view = (intersection.ray.origin - intersection.intersection).normalize();
   Vector lightOffset = light->position - intersection.intersection;
   Vector reflected = reflectVector(lightOffset.normalize(), intersection.normal);

   double dot = view.dot(reflected);

   if (dot <= 0) {
      return specularColor;
   }

   double specularAmount = pow(dot, shininess) * light->intensity;

   specularColor.r = specularAmount;
   specularColor.g = specularAmount;
   specularColor.b = specularAmount;

   return specularColor;
}

Color RayTracer::getReflectiveRefractiveLighting(const Intersection& intersection) {
   double reflectivity = intersection.endMaterial->getReflectivity();
   double startRefractiveIndex = intersection.startMaterial->getRefractiveIndex();
   double endRefractiveIndex = intersection.endMaterial->getRefractiveIndex();
   int reflectionsRemaining = intersection.ray.reflectionsRemaining;

   /**
    * Don't perform lighting if the object is not reflective or refractive or we have
    * hit our recursion limit.
    */
   if (reflectivity == NOT_REFLECTIVE && endRefractiveIndex == NOT_REFRACTIVE ||
    reflectionsRemaining <= 0) {
      return Color();
   }

   // Default to exclusively reflective values.
   double reflectivePercentage = reflectivity;
   double refractivePercentage = 0;

   // Refractive index overrides the reflective property.
   if (endRefractiveIndex != NOT_REFRACTIVE) {
      reflectivePercentage = getReflectance(intersection.normal,
       intersection.ray.direction, startRefractiveIndex, endRefractiveIndex);

      refractivePercentage = 1 - reflectivePercentage;
   }

   // No ref{ra,le}ctive properties - bail early.
   if (refractivePercentage <= 0 && reflectivePercentage <= 0) {
      return Color();
   }

   Color reflectiveColor;
   Color refractiveColor;

   if (reflectivePercentage > 0) {
      Vector reflected = reflectVector(intersection.ray.origin,
       intersection.normal);
      Ray reflectedRay(intersection.intersection, reflected, reflectionsRemaining - 1,
       intersection.ray.material);

      reflectiveColor = castRay(reflectedRay) * reflectivePercentage;
   }

   if (refractivePercentage > 0) {
      Vector refracted = refractVector(intersection.normal,
       intersection.ray.direction, startRefractiveIndex, endRefractiveIndex);
      Ray refractedRay = Ray(intersection.intersection, refracted, 1,
       intersection.endMaterial);

      refractiveColor = castRay(refractedRay) * refractivePercentage;
   }

   return reflectiveColor + refractiveColor;
}

double RayTracer::getReflectance(const Vector& normal, const Vector& incident,
 double n1, double n2) {
   double n = n1 / n2;
   double cosI = -normal.dot(incident);
   double sinT2 = n * n * (1.0 - cosI * cosI);

   if (sinT2 > 1.0) {
      // Total Internal Reflection.
      return 1.0;
   }

   double cosT = sqrt(1.0 - sinT2);
   double r0rth = (n1 * cosI - n2 * cosT) / (n1 * cosI + n2 * cosT);
   double rPar = (n2 * cosI - n1 * cosT) / (n2 * cosI + n1 * cosT);
   return (r0rth * r0rth + rPar * rPar) / 2.0;
}

Vector RayTracer::refractVector(const Vector& normal, const Vector& incident,
 double n1, double n2) {
   double n = n1 / n2;
   double cosI = -normal.dot(incident);
   double sinT2 = n * n * (1.0 - cosI * cosI);

   if (sinT2 > 1.0) {
      cerr << "Bad refraction vector!" << endl;
      exit(EXIT_FAILURE);
   }

   double cosT = sqrt(1.0 - sinT2);
   return incident * n + normal * (n * cosI - cosT);
}

Vector RayTracer::reflectVector(Vector vector, Vector normal) {
   return normal * 2 * vector.dot(normal) - vector;
}

void RayTracer::readScene(istream& in) {
   string type;

   in >> type;

   while (in.good()) {
      if (type[0] == '#') {
         // Ignore comment lines.
         getline(in, type);
      } else if (type.compare("model") == 0) {
         string model;
         int size;
         Vector translate;
         Material* material;

         in >> model;
         in >> size;
         in >> translate.x >> translate.y >> translate.z;

         material = readMaterial(in);
         readModel(model, size, translate, material);
      } else if (type.compare("material") == 0) {
         addMaterial(in);
      } else if (type.compare("triangle") == 0) {
         Vector v0, v1, v2;
         Material* material;

         in >> v0.x >> v0.y >> v0.z;
         in >> v1.x >> v1.y >> v1.z;
         in >> v2.x >> v2.y >> v2.z;
         material = readMaterial(in);

         addObject(new Triangle(v0, v1, v2, material));
      } else if (type.compare("sphere") == 0) {
         Vector center;
         double radius;
         Material* material;

         in >> center.x >> center.y >> center.z;
         in >> radius;
         material = readMaterial(in);

         addObject(new Sphere(center, radius, material));
      } else if (type.compare("light") == 0) {
         Vector position;
         double intensity;

         in >> position.x >> position.y >> position.z;
         in >> intensity;

         addLight(new Light(position, intensity));
      } else if (type.compare("dispersion") == 0) {
         in >> dispersion;
      } else if (type.compare("maxReflections") == 0) {
         in >> maxReflections;
      } else if (type.compare("startingMaterial") == 0) {
         startingMaterial = readMaterial(in);
      } else if (type.compare("cameraUp") == 0) {
         in >> camera.up.x;
         in >> camera.up.y;
         in >> camera.up.z;
      } else if (type.compare("cameraPosition") == 0) {
         in >> camera.position.x;
         in >> camera.position.y;
         in >> camera.position.z;
      } else if (type.compare("cameraLookAt") == 0) {
         in >> camera.lookAt.x;
         in >> camera.lookAt.y;
         in >> camera.lookAt.z;
      } else if (type.compare("cameraScreenWidth") == 0) {
         in >> camera.screenWidth;
      } else {
         cerr << "Type not found: " << type << endl;
         exit(EXIT_FAILURE);
      }

      in >> type;
   }

   // Construct the top level BSP that contains all the objects..
   bsp = new BSP(0, 'x', objects);
}

void RayTracer::readModel(string model, int size, Vector translate, Material* material) {
   string type;
   vector<Vector> vertices;
   Vector centerOffset;
   double minX, maxX, minY, maxY, minZ, maxZ;
   double offX = 0.0, offY = 0.0, offZ = 0.0, scale = 0.0;

   cout << model;

   ifstream in;
   in.open(model.c_str(), ifstream::in);

   if (in.fail()) {
      cerr << "Failed opening model file" << endl;
      exit(EXIT_FAILURE);
   }

   in >> type;
   while (in.good()) {
      if (type.compare("Vertex") == 0) {
         int index;
         Vector v;

         in >> index;
         in >> v.x >> v.y >> v.z;

         minX = min(minX, v.x);
         minY = min(minY, v.y);
         minZ = min(minZ, v.z);

         maxX = max(maxX, v.x);
         maxY = max(maxY, v.y);
         maxZ = max(maxZ, v.z);

         vertices.push_back(v);
      } else if (type.compare("Face") == 0) {
         // We are guaranteed to have all Vertices before Faces so we set this
         // once for the first Face.
         if (scale == 0.0) {
            offX = (maxX + minX) / 2;
            offY = (maxY + minY) / 2;
            offZ = (maxZ + minZ) / 2;
            centerOffset = Vector(offX, offY, offZ);

            double distance = sqrt((maxX - minX) * (maxX - minX) +
                                   (maxY - minY) * (maxY - minY) +
                                   (maxZ - minZ) * (maxZ - minZ));

            if (distance == 0.0)
               exit(EXIT_FAILURE);

            scale = size / distance;
         }

         int face, v0, v1, v2;

         in >> face >> v0 >> v1 >> v2;

         Vector a = (vertices[v0 - 1] - centerOffset) * scale + translate;
         Vector b = (vertices[v1 - 1] - centerOffset) * scale + translate;
         Vector c = (vertices[v2 - 1] - centerOffset) * scale + translate;

         addObject(new Triangle(a, b, c, material));
      }

      in >> type;
   }

   in.close();
}

/**
 * Parses the input stream and makes a new Material.
 */
Material* RayTracer::readMaterial(istream& in) {
   Material* material;
   string type;
   in >> type;

   if (type.compare("FlatColor") == 0) {
      material = new FlatColor(in);
   } else if (type.compare("ShinyColor") == 0) {
      material = new ShinyColor(in);
   } else if (type.compare("Checkerboard") == 0) {
      material = new Checkerboard(in);
   } else if (type.compare("Glass") == 0) {
      material = new Glass(in);
   } else if (type.compare("Turbulence") == 0) {
      material = new Turbulence(in);
   } else if (type.compare("Marble") == 0) {
      material = new Marble(in);
   } else if (type.compare("CrissCross") == 0) {
      material = new CrissCross(in);
   } else if (type.compare("Wood") == 0) {
      material = new Wood(in);
   } else if (materials.count(type) > 0) {
      material = materials[type];

      // Stored material already has the NormalMap so return here to avoid
      // scene parsing problems below.
      return material;
   } else {
      cerr << "Material not found: " << type << endl;
      exit(EXIT_FAILURE);
   }

   material->setNormalMap(readNormalMap(in));

   return material;
}

NormalMap* RayTracer::readNormalMap(istream& in) {
   string type;
   in >> type;

   if (type.compare("null") == 0) {
      return NULL;
   } else if (type.compare("NormalMap") == 0) {
      return new NormalMap(in);
   } else {
      cerr << "NormalMap not found: " << type << endl;
      exit(EXIT_FAILURE);
   }
}

void RayTracer::addMaterial(istream& in) {
   string materialName;

   in >> materialName;

   for (string::iterator itr = materialName.begin(); itr < materialName.end(); itr++) {
      if (isupper(*itr)) {
         cerr << "Invalid material name: " << materialName << endl;
         exit(EXIT_FAILURE);
      }
   }

   if (materials.count(materialName) > 0) {
      cerr << "Duplicate material name: " << materialName << endl;
      exit(EXIT_FAILURE);
   }

   Material* material = readMaterial(in);
   materials.insert(pair<string, Material*>(materialName, material));
}


text:
var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(
  function(cosλcosφ) { return Math.sqrt(2 / (1 + cosλcosφ)); },
  function(ρ) { return 2 * Math.asin(ρ / 2); }
);

(d3.geo.azimuthalEqualArea = function() {
  return d3_geo_projection(d3_geo_azimuthalEqualArea);
}).raw = d3_geo_azimuthalEqualArea;