text:
using System;
using System.Collections;

namespace NUnit.Framework.Internal
{
    /// <summary>
    /// Summary description for PlatformHelperTests.
    /// </summary>
    [TestFixture]
    public class PlatformDetectionTests
    {
        private static readonly PlatformHelper win95Helper = new PlatformHelper(
            new OSPlatform( PlatformID.Win32Windows , new Version( 4, 0 ) ),
            new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );

        private static readonly PlatformHelper winXPHelper = new PlatformHelper(
            new OSPlatform( PlatformID.Win32NT , new Version( 5,1 ) ),
            new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ) );

        private void CheckOSPlatforms( OSPlatform os,
            string expectedPlatforms )
        {
            Assert.That(expectedPlatforms, Is.SubsetOf(PlatformHelper.OSPlatforms).IgnoreCase,
                "Error in test: one or more expected platforms is not a valid OSPlatform.");

            CheckPlatforms(
                new PlatformHelper( os, RuntimeFramework.CurrentFramework ),
                expectedPlatforms,
                PlatformHelper.OSPlatforms );
        }

        private void CheckRuntimePlatforms( RuntimeFramework runtimeFramework,
            string expectedPlatforms )
        {
            CheckPlatforms(
                new PlatformHelper( OSPlatform.CurrentPlatform, runtimeFramework ),
                expectedPlatforms,
                PlatformHelper.RuntimePlatforms + ",NET-1.0,NET-1.1,NET-2.0,NET-3.0,NET-3.5,NET-4.0,NET-4.5,MONO-1.0,MONO-2.0,MONO-3.0,MONO-3.5,MONO-4.0,MONOTOUCH,NETCF-2.0,NETCF-3.5,SL-3.0,SL-4.0,SL-5.0" );
        }

        private void CheckPlatforms( PlatformHelper helper,
            string expectedPlatforms, string checkPlatforms )
        {
            string[] expected = expectedPlatforms.Split( new char[] { ',' } );
            string[] check = checkPlatforms.Split( new char[] { ',' } );

            foreach( string testPlatform in check )
            {
                bool shouldPass = false;

                foreach( string platform in expected )
                    if ( shouldPass = platform.ToLower() == testPlatform.ToLower() )
                        break;

                bool didPass = helper.IsPlatformSupported( testPlatform );

                if ( shouldPass && !didPass )
                    Assert.Fail( "Failed to detect {0}", testPlatform );
                else if ( didPass && !shouldPass )
                    Assert.Fail( "False positive on {0}", testPlatform );
                else if ( !shouldPass && !didPass )
                    Assert.AreEqual( "Only supported on " + testPlatform, helper.Reason );
            }
        }

        [Test]
        public void DetectWin95()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32Windows, new Version( 4, 0 ) ),
                "Win95,Win32Windows,Win32,Win" );
        }

        [Test]
        public void DetectWin98()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32Windows, new Version( 4, 10 ) ),
                "Win98,Win32Windows,Win32,Win" );
        }

        [Test]
        public void DetectWinMe()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32Windows, new Version( 4, 90 ) ),
                "WinMe,Win32Windows,Win32,Win" );
        }

        [Test]
        public void DetectWinCE()
        {
            PlatformID winCE = (PlatformID)Enum.Parse(typeof(PlatformID), "WinCE", false);
            CheckOSPlatforms(
                new OSPlatform(winCE, new Version(1, 0)),
                "WinCE,Win32,Win" );
        }

        [Test]
        public void DetectNT3()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32NT, new Version( 3, 51 ) ),
                "NT3,Win32NT,Win32,Win" );
        }

        [Test]
        public void DetectNT4()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32NT, new Version( 4, 0 ) ),
                "NT4,Win32NT,Win32,Win" );
        }

        [Test]
        public void DetectWin2K()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32NT, new Version( 5, 0 ) ),
                "Win2K,NT5,Win32NT,Win32,Win" );
        }

        [Test]
        public void DetectWinXP()
        {
            CheckOSPlatforms(
                new OSPlatform( PlatformID.Win32NT, new Version( 5, 1 ) ),
                "WinXP,NT5,Win32NT,Win32,Win" );
        }

        [Test]
        public void DetectWinXPProfessionalX64()
        {
                CheckOSPlatforms(
                        new OSPlatform( PlatformID.Win32NT, new Version( 5, 2 ), OSPlatform.ProductType.WorkStation ),
                        "WinXP,NT5,Win32NT,Win32,Win" );
        }

        [Test]
        public void DetectWin2003Server()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(5, 2), OSPlatform.ProductType.Server),
                "Win2003Server,NT5,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectVista()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.WorkStation),
                "Vista,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWin2008ServerOriginal()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 0), OSPlatform.ProductType.Server),
                "Win2008Server,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWin2008ServerR2()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.Server),
                "Win2008Server,Win2008ServerR2,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindows7()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 1), OSPlatform.ProductType.WorkStation),
                "Win7,Windows7,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindows2012ServerOriginal()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.Server),
                "Win2012Server,Win2012ServerR1,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindows2012ServerR2()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.Server),
                "Win2012Server,Win2012ServerR2,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindows8()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 2), OSPlatform.ProductType.WorkStation),
                "Win8,Windows8,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindows81()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(6, 3), OSPlatform.ProductType.WorkStation),
                "Win8.1,Windows8.1,NT6,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindows10()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.WorkStation),
                "Win10,Windows10,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectWindowsServer()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Win32NT, new Version(10, 0), OSPlatform.ProductType.Server),
                "WindowsServer10,Win32NT,Win32,Win");
        }

        [Test]
        public void DetectUnixUnderMicrosoftDotNet()
        {
            CheckOSPlatforms(
                new OSPlatform(OSPlatform.UnixPlatformID_Microsoft, new Version(0,0)),
                "UNIX,Linux");
        }

        [Test]
        public void DetectUnixUnderMono()
        {
            CheckOSPlatforms(
                new OSPlatform(OSPlatform.UnixPlatformID_Mono, new Version(0,0)),
                "UNIX,Linux");
        }

#if !NETCF
        [Test]
        public void DetectXbox()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.Xbox, new Version(0, 0)),
                "Xbox");
        }

        [Test]
        public void DetectMacOSX()
        {
            CheckOSPlatforms(
                new OSPlatform(PlatformID.MacOSX, new Version(0, 0)),
                "MacOSX");
        }
#endif

        [Test]
        public void DetectNet10()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.Net, new Version( 1, 0, 3705, 0 ) ),
                "NET,NET-1.0" );
        }

        [Test]
        public void DetectNet11()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.Net, new Version( 1, 1, 4322, 0 ) ),
                "NET,NET-1.1" );
        }

        [Test]
        public void DetectNet20()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.Net, new Version( 2, 0, 50727, 0 ) ),
                "Net,Net-2.0" );
        }

        [Test]
        public void DetectNet30()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Net, new Version(3, 0)),
                "Net,Net-2.0,Net-3.0");
        }

        [Test]
        public void DetectNet35()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Net, new Version(3, 5)),
                "Net,Net-2.0,Net-3.0,Net-3.5");
        }

        [Test]
        public void DetectNet40()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Net, new Version(4, 0, 30319, 0)),
                "Net,Net-4.0");
        }

        [Test]
        public void DetectNetCF()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.NetCF, new Version( 1, 1, 4322, 0 ) ),
                "NetCF" );
        }

        [Test]
        public void DetectSSCLI()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.SSCLI, new Version( 1, 0, 3, 0 ) ),
                "SSCLI,Rotor" );
        }

        [Test]
        public void DetectMono10()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.Mono, new Version( 1, 1, 4322, 0 ) ),
                "Mono,Mono-1.0" );
        }

        [Test]
        public void DetectMono20()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework( RuntimeType.Mono, new Version( 2, 0, 50727, 0 ) ),
                "Mono,Mono-2.0" );
        }

        [Test]
        public void DetectMono30()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Mono, new Version(3, 0)),
                "Mono,Mono-2.0,Mono-3.0");
        }

        [Test]
        public void DetectMono35()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Mono, new Version(3, 5)),
                "Mono,Mono-2.0,Mono-3.0,Mono-3.5");
        }

        [Test]
        public void DetectMono40()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319)),
                "Mono,Mono-4.0");
        }

        [Test]
        public void DetectMonoTouch()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.MonoTouch, new Version(4, 0, 30319)),
                "MonoTouch");
        }

        [Test]
        public void DetectSilverlight30()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Silverlight, new Version(3, 0)),
                "Silverlight,SL-3.0");
        }

        [Test]
        public void DetectSilverlight40()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Silverlight, new Version(4, 0)),
                "Silverlight,SL-4.0");
        }

        [Test]
        public void DetectSilverlight50()
        {
            CheckRuntimePlatforms(
                new RuntimeFramework(RuntimeType.Silverlight, new Version(5, 0)),
                "Silverlight,SL-5.0");
        }

        [Test]
        public void DetectExactVersion()
        {
            Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322" ) );
            Assert.IsTrue( winXPHelper.IsPlatformSupported( "net-1.1.4322.0" ) );
            Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4323.0" ) );
            Assert.IsFalse( winXPHelper.IsPlatformSupported( "net-1.1.4322.1" ) );
        }

        [Test]
        public void ArrayOfPlatforms()
        {
            string[] platforms = new string[] { "NT4", "Win2K", "WinXP" };
            Assert.IsTrue( winXPHelper.IsPlatformSupported( platforms ) );
            Assert.IsFalse( win95Helper.IsPlatformSupported( platforms ) );
        }

        [Test]
        public void PlatformAttribute_Include()
        {
            PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
            Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
            Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
            Assert.AreEqual("Only supported on Win2K,WinXP,NT4", win95Helper.Reason);
        }

        [Test]
        public void PlatformAttribute_Exclude()
        {
            PlatformAttribute attr = new PlatformAttribute();
            attr.Exclude = "Win2K,WinXP,NT4";
            Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
            Assert.AreEqual( "Not supported on Win2K,WinXP,NT4", winXPHelper.Reason );
            Assert.IsTrue( win95Helper.IsPlatformSupported( attr ) );
        }

        [Test]
        public void PlatformAttribute_IncludeAndExclude()
        {
            PlatformAttribute attr = new PlatformAttribute( "Win2K,WinXP,NT4" );
            attr.Exclude = "Mono";
            Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
            Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
            Assert.IsTrue( winXPHelper.IsPlatformSupported( attr ) );
            attr.Exclude = "Net";
            Assert.IsFalse( win95Helper.IsPlatformSupported( attr ) );
            Assert.AreEqual( "Only supported on Win2K,WinXP,NT4", win95Helper.Reason );
            Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
            Assert.AreEqual( "Not supported on Net", winXPHelper.Reason );
        }

        [Test]
        public void PlatformAttribute_InvalidPlatform()
        {
            PlatformAttribute attr = new PlatformAttribute( "Net-1.0,Net11,Mono" );
            Assert.IsFalse( winXPHelper.IsPlatformSupported( attr ) );
            Assert.That( winXPHelper.Reason, Does.StartWith("Invalid platform name"));
            Assert.That( winXPHelper.Reason, Does.Contain("Net11"));
        }

        [Test]
        public void PlatformAttribute_ProcessBitNess()
        {
            PlatformAttribute attr32 = new PlatformAttribute("32-Bit");
            PlatformAttribute attr64 = new PlatformAttribute("64-Bit");
            PlatformHelper helper = new PlatformHelper();

            // This test verifies that the two labels are known,
            // do not cause an error and return consistent results.
            bool is32BitProcess = helper.IsPlatformSupported(attr32);
            bool is64BitProcess = helper.IsPlatformSupported(attr64);
            Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit");

#if NET_4_0 || NET_4_5 || PORTABLE
            // For .NET 4.0 and 4.5, we can check further
            Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess));
#endif
        }

#if NET_4_0 || NET_4_5 || PORTABLE
        [Test]
        public void PlatformAttribute_OperatingSystemBitNess()
        {
            PlatformAttribute attr32 = new PlatformAttribute("32-Bit-OS");
            PlatformAttribute attr64 = new PlatformAttribute("64-Bit-OS");
            PlatformHelper helper = new PlatformHelper();

            bool is64BitOS = Environment.Is64BitOperatingSystem;
            Assert.That(helper.IsPlatformSupported(attr32), Is.Not.EqualTo(is64BitOS));
            Assert.That(helper.IsPlatformSupported(attr64), Is.EqualTo(is64BitOS));
        }
#endif
    }
}
#endif


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/html; charset=utf-8" />
<title>
  Module: LogViewer

    — Documentation by YARD 0.8.6.1

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" />

    Index (L) »

    LogViewer

(no frames)

      Class List

      Method List

      File List

Module: LogViewer

Defined in:

lib/log_viewer.rb,

  lib/log_viewer/engine.rb,
 lib/log_viewer/version.rb,
 app/helpers/log_viewer/log_helper.rb,
 app/helpers/log_viewer/application_helper.rb,
 app/controllers/log_viewer/log_controller.rb,
 app/controllers/log_viewer/application_controller.rb

Defined Under Namespace

      Modules: ApplicationHelper, LogHelper

      Classes: ApplicationController, Engine, LogController

Constant Summary

VERSION =

"0.0.1"

  Generated on Mon Oct  7 14:35:44 2013 by
  yard
  0.8.6.1 (ruby-1.9.3).

redpajama_set_name: RedPajamaGithub


text:
@interface ChosenContactListViewController : ContentListViewController<ABPeoplePickerNavigationControllerDelegate, UIActionSheetDelegate, ABNewPersonViewControllerDelegate, ABPersonViewControllerDelegate> {
	ABAddressBookRef addressBook;
	BOOL firstTimeDisplayed;

    NSManagedObjectContext *_tempContext;
    NSPersistentStore *_tempStore;
    BOOL _picking;
}

@end


text:
Update Schema

  <form novalidate class="simple-form">

        category
        {{m.selected_schema.category}}

        desciption

          <textarea ng-model="m.selected_schema.description">
          </textarea>

    Fields:

        key
        type
        English name
        English description
        English possible values
        Arabic possible values
        Arabic description
        Arabic name

        {{field.key}}

          <input type="text" ng-model="field.type">

          <input type="text" ng-model="field.name">

          <input type="text" ng-model="field.description">

          <textarea ng-model="field.possible_values" ng-list="/\n/"></textarea>

          <textarea ng-model="field.possible_values" ng-list="/\n/"></textarea>

          <input type="text" ng-model="field.description">

          <input type="text" ng-model="field.name">

    Add Field

    Save
    Cancel
  </form>


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/kr/pretty"
	"golang.org/x/net/context"
	"googlemaps.github.io/maps"
)

var (
	apiKey    = flag.String("key", "", "API Key for using Google Maps API.")
	clientID  = flag.String("client_id", "", "ClientID for Maps for Work API access.")
	signature = flag.String("signature", "", "Signature for Maps for Work API access.")
	input     = flag.String("input", "", "Text string on which to search.")
	language  = flag.String("language", "", "The language in which to return results.")
	offset    = flag.Uint("offset", 0, "The character position in the input term at which the service uses text for predictions.")
	location  = flag.String("location", "", "The latitude/longitude around which to retrieve place information. This must be specified as latitude,longitude.")
	radius    = flag.Uint("radius", 0, "Defines the distance (in meters) within which to bias place results. The maximum allowed radius is 50,000 meters.")
)

func usageAndExit(msg string) {
	fmt.Fprintln(os.Stderr, msg)
	fmt.Println("Flags:")
	flag.PrintDefaults()
	os.Exit(2)
}

func check(err error) {
	if err != nil {
		log.Fatalf("fatal error: %s", err)
	}
}

func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.QueryAutocompleteRequest{
		Input:    *input,
		Language: *language,
		Radius:   *radius,
		Offset:   *offset,
	}

	parseLocation(*location, r)

	resp, err := client.QueryAutocomplete(context.Background(), r)
	check(err)

	pretty.Println(resp)
}

func parseLocation(location string, r *maps.QueryAutocompleteRequest) {
	if location != "" {
		l, err := maps.ParseLatLng(location)
		check(err)
		r.Location = &l
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="author" content="Ville Talonpoika">
    <meta name="description" content="Website">
    <meta name="keywords" content="blog,developer,designer,personal">
    <meta name="theme-color" content="#DBFFF7">

    <base href="https://villetalonpoika.com">
    <title>Ville Talonpoika</title>

    <link rel="canonical" href="">

    <link href="https://fonts.googleapis.com/css?family=Merriweather+Sans:400,700|Merriweather:300,700|Source+Code+Pro:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css" integrity="sha256-oSrCnRYXvHG31SBifqP2PM1uje7SJUyX0nTwO2RJV54=" crossorigin="anonymous" />

    <link rel="stylesheet" href="https://villetalonpoika.com/css/main.min.a5e8856538824b14696fc90e7d55f39e38f6233d056a66ef8e2a7f8641b7121a.css" integrity="sha256-peiFZTiCSxRpb8kOfVXznjj2Iz0Fambvjip/hkG3Eho=" media="screen">

    <link rel="icon" type="image/png" href="https://villetalonpoika.com/images/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="https://villetalonpoika.com/images/favicon-16x16.png" sizes="16x16">

      Ville Talonpoika

    <input type="checkbox" id="menu-toggle" />

            Games

            Software

            Blog

            About

404

Page Not Found

Sorry, this page does not exist.
You can head back to homepage.

© Ville Talonpoika 2018


text:
package maze.net;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface IServer extends Remote {
    public String sendMsg(String msg) throws RemoteException;
}


text:
package co.uk.noor

import java.awt.Color
import java.awt.image.BufferedImage

class PixelInfo(colour: Color) {

  val red = colour.getRed
  val green = colour.getGreen
  val blue = colour.getBlue

  val hue = Color.RGBtoHSB(red, green, blue, null)(0)
  val brightness = 0.3 * red + 0.59 * green + 0.11 * blue

  def isBrightnessSimilar(other: PixelInfo)(implicit tolerance: Tolerance): Boolean = {
    Math.abs(this.brightness - other.brightness) < tolerance.minBrightness
  }

  def isRGBSimilar(other: PixelInfo)(implicit tolerance: Tolerance): Boolean = {
    def isColorSimilar(a: Int, b: Int, colour: Int): Boolean = {
      val absDiff = Math.abs(a - b)

      if (a == b || absDiff < colour) {
        return true
      } else {
        return false
      }
    }

    val red = isColorSimilar(this.red, other.red, tolerance.red)
    val green = isColorSimilar(this.green, other.green, tolerance.green)
    val blue = isColorSimilar(this.blue, other.blue, tolerance.blue)

    red && green && blue
  }

  def isContrasting(other: PixelInfo)(implicit tolerance: Tolerance) = {
    Math.abs(this.brightness - other.brightness) > tolerance.maxBrightness
  }

  def isRGBSame(other: PixelInfo) = {
    val red = this.red == other.red
    val green = this.green == other.green
    val blue = this.blue == other.blue
    red && green && blue
  }

  def copyGrayScalePixel(target: BufferedImage, x: Int, y: Int) {
    val grey = new Color(brightness.toInt, brightness.toInt, brightness.toInt)
    target.setRGB(x, y, grey.getRGB)
  }

  def copyPixel(target: BufferedImage, x: Int, y: Int) {
    target.setRGB(x, y, colour.getRGB)
  }

}

object PixelInfo {
  def apply(colour: Int): PixelInfo = {
    new PixelInfo(new Color(colour))
  }
}


text:
A convention-based bootstrapper for LoopBack applications.

For full documentation, see the official StrongLoop documentation: [Defining boot scripts](https://loopback.io/doc/en/lb2/Defining-boot-scripts) and [Creating a LoopBack application](https://loopback.io/doc/en/lb2/Creating-an-application).

## Overview

The loopback-boot module initializes (bootstraps) a LoopBack application.  Specifically, it:
 - Configures data-sources.
 - Defines custom models
 - Configures models and attaches models to data-sources.
 - Configures application settings
 - Runs additional boot scripts, so you can put custom setup code in multiple small files instead of in the main application file.

For more information, see [Defining boot scripts](https://loopback.io/doc/en/lb2/Defining-boot-scripts).

### Version notes

The version range `1.x` is backwards compatible with `app.boot` provided
by LoopBack 1.x versions and the project layout scaffolded by `slc lb project`
up to slc version 2.5.

The version range `2.x` supports the new project layout as scaffolded by
`yo loopback`.

This document describes the configuration conventions of the `2.x` versions.

## Installation

    npm install loopback-boot

## Usage

```js
var loopback = require('loopback');
var boot = require('loopback-boot');

var app = loopback();
boot(app, __dirname);

app.use(loopback.rest());
app.listen();
```

See [API docs](http://apidocs.strongloop.com/loopback-boot/) for
complete API reference.

## License

This module is provided under dual MIT/StrongLoop license.  See [LICENSE](LICENSE) for details.


text:
if [ $UID -ne 0 ]; then
    echo This script must be ran as root > /dev/stderr
    exit 1
fi
DIR=/opt/cabsgraph/
cd "$(dirname "${BASH_SOURCE[0]}")"/..
mkdir -p $DIR
install -v ./src/create_db.sh "$DIR"
install -v ./src/mkgraph_lib.sh "$DIR"
install -v ./src/update.sh "$DIR"
install -vm 600 ./conf/my.cnf.TEMPLATE "$DIR"
install -vm 644 ./conf/cabsgraph.conf.TEMPLATE "$DIR"
install -vm 644 ./conf/cabsgraph.service /etc/systemd/system/
echo
echo "You must edit $DIR/my.cnf.TEMPLATE and rename to my.cnf"
echo "You must edit $DIR/cabsgraph.conf.TEMPLATE and rename to cabsgraph.conf"
echo "Then run \`$DIR/create_db.sh\` to set up the databases."
echo "After that, don't forget to run \`systemctl start cabsgraph; systemctl enable cabsgraph\`"


text:
//go:generate go run github.com/mailru/easyjson/easyjson $GOFILE

package graph

import (
	"fmt"
	"reflect"
	"strings"

	"github.com/fatih/structs"
	"github.com/mohae/deepcopy"
	"github.com/spf13/cast"

	"github.com/skydive-project/skydive/graffiti/filters"
	"github.com/skydive-project/skydive/graffiti/getter"
)

// Metadata describes the graph node metadata type. It implements ElementMatcher
// based only on Metadata.
// easyjson:json
type Metadata map[string]interface{}

// Copy returns a copy of the metadata
func (m Metadata) Copy() Metadata {
	m2 := Metadata{}
	for k, v := range m {
		m2[k] = v
	}
	return m2
}

// Match returns true if the the given element matches the metadata.
func (m Metadata) Match(g getter.Getter) bool {
	f, err := m.Filter()
	if err != nil {
		return false
	}
	return f.Eval(g)
}

// Filter returns a filter corresponding to the metadata
func (m Metadata) Filter() (*filters.Filter, error) {
	var termFilters []*filters.Filter
	for k, v := range m {
		switch v := v.(type) {
		case int64:
			termFilters = append(termFilters, filters.NewTermInt64Filter(k, v))
		case string:
			termFilters = append(termFilters, filters.NewTermStringFilter(k, v))
		case bool:
			termFilters = append(termFilters, filters.NewTermBoolFilter(k, v))
		case Metadata:
			filters, err := v.Filter()
			if err != nil {
				return nil, err
			}
			termFilters = append(termFilters, filters)
		case map[string]interface{}:
			sm := Metadata(v)
			filters, err := sm.Filter()
			if err != nil {
				return nil, err
			}
			termFilters = append(termFilters, filters)
		default:
			i, err := cast.ToInt64E(v)
			if err != nil {
				return nil, err
			}
			termFilters = append(termFilters, filters.NewTermInt64Filter(k, i))
		}
	}
	return filters.NewAndFilter(termFilters...), nil
}

// GetFieldBool returns the value of a bool field
func (m Metadata) GetFieldBool(key string) (bool, error) {
	value, err := GetMapField(m, key)
	if err != nil {
		return false, err
	}

	if b, ok := value.(bool); ok {
		return b, nil
	}

	return false, getter.ErrFieldNotFound
}

// GetFieldInt64 returns the value of a integer field
func (m Metadata) GetFieldInt64(key string) (int64, error) {
	value, err := GetMapField(m, key)
	if err != nil {
		return 0, err
	}

	return cast.ToInt64E(value)
}

// GetFieldString returns the value of a string field
func (m Metadata) GetFieldString(key string) (string, error) {
	value, err := GetMapField(m, key)
	if err != nil {
		return "", err
	}

	if s, ok := value.(string); ok {
		return s, nil
	}

	return "", getter.ErrFieldNotFound
}

// GetField returns the field with the given name
func (m Metadata) GetField(key string) (interface{}, error) {
	return GetMapField(m, key)
}

// MatchBool implements Getter interface
func (m Metadata) MatchBool(key string, predicate getter.BoolPredicate) bool {
	if index := strings.Index(key, "."); index != -1 {
		first := key[:index]
		if v, found := m[first]; found {
			if getter, found := v.(getter.Getter); found {
				return getter.MatchBool(key[index+1:], predicate)
			}
		}
	}

	field, err := m.GetField(key)
	if err != nil {
		return false
	}

	switch field := field.(type) {
	case []interface{}:
		for _, intf := range field {
			if b, ok := intf.(bool); ok && predicate(b) {
				return true
			}
		}
	case []bool:
		for _, v := range field {
			if predicate(v) {
				return true
			}
		}
	case bool:
		return predicate(field)
	}

	return false
}

// MatchInt64 implements Getter interface
func (m Metadata) MatchInt64(key string, predicate getter.Int64Predicate) bool {
	if index := strings.Index(key, "."); index != -1 {
		first := key[:index]
		if v, found := m[first]; found {
			if getter, found := v.(getter.Getter); found {
				return getter.MatchInt64(key[index+1:], predicate)
			}
		}
	}

	field, err := m.GetField(key)
	if err != nil {
		return false
	}

	switch field := field.(type) {
	case []interface{}:
		for _, intf := range field {
			if v, err := cast.ToInt64E(intf); err == nil && predicate(v) {
				return true
			}
		}
	case []int64:
		for _, v := range field {
			if predicate(v) {
				return true
			}
		}
	case int64:
		return predicate(field)
	default:
		if v, err := cast.ToInt64E(field); err == nil {
			return predicate(v)
		}
	}

	return false
}

// MatchString implements Getter interface
func (m Metadata) MatchString(key string, predicate getter.StringPredicate) bool {
	if index := strings.Index(key, "."); index != -1 {
		first := key[:index]
		if v, found := m[first]; found {
			if getter, found := v.(getter.Getter); found {
				return getter.MatchString(key[index+1:], predicate)
			}
		}
	}

	field, err := m.GetField(key)
	if err != nil {
		return false
	}

	switch field := field.(type) {
	case []interface{}:
		for _, intf := range field {
			if s, ok := intf.(string); ok && predicate(s) {
				return true
			}
		}
	case []string:
		for _, s := range field {
			if predicate(s) {
				return true
			}
		}
	case string:
		return predicate(field)
	}

	return false
}

func getFieldKeys(obj map[string]interface{}, path string) []string {
	var fields []string

	if path != "" {
		path += "."
	}

	for k, v := range obj {
		fields = append(fields, path+k)

		switch v.(type) {
		case getter.Getter:
			keys := v.(getter.Getter).GetFieldKeys()
			for _, subkey := range keys {
				fields = append(fields, k+"."+subkey)
			}
		case map[string]interface{}:
			subfields := getFieldKeys(v.(map[string]interface{}), path+k)
			fields = append(fields, subfields...)
		}
	}

	return fields
}

// GetMapFieldKeys returns all the keys using dot notation
func GetMapFieldKeys(obj map[string]interface{}) []string {
	return getFieldKeys(obj, "")
}

// GetFieldKeys returns all the keys of the medata
func (m Metadata) GetFieldKeys() []string {
	return GetMapFieldKeys(m)
}

// SetField set metadata value based on dot key ("a.b.c.d" = "ok")
func (m *Metadata) SetField(k string, v interface{}) bool {
	return SetMapField(*m, k, v)
}

// DelField removes a dot based key from metadata
func (m Metadata) DelField(k string) bool {
	return DelField(m, k)
}

// SetFieldAndNormalize set metadata value after normalization (and deepcopy)
func (m *Metadata) SetFieldAndNormalize(k string, v interface{}) bool {
	return SetMapField(*m, k, NormalizeValue(v))
}

// ApplyUpdates applies a serie of partial updates to a graph element
func (m *Metadata) ApplyUpdates(ops ...PartiallyUpdatedOp) error {
	for _, op := range ops {
		if op.Type == PartiallyUpdatedAddOpType {
			m.SetField(op.Key, op.Value)
		} else {
			m.DelField(op.Key)
		}
	}

	return nil
}

// SetMapField set a value in a tree based on dot key ("a.b.c.d" = "ok")
func SetMapField(obj map[string]interface{}, k string, v interface{}) bool {
	components := strings.Split(k, ".")
	for n, component := range components {
		if n == len(components)-1 {
			obj[component] = v
		} else {
			m, ok := obj[component]
			if !ok {
				m := make(map[string]interface{})
				obj[component] = m
				obj = m
			} else if obj, ok = m.(map[string]interface{}); !ok {
				return false
			}
		}
	}
	return true
}

// NormalizeValue returns a version of the passed value
// that can be safely marshalled to JSON
func NormalizeValue(obj interface{}) interface{} {
	// TODO(sbaubeau) should return Metadata
	obj = deepcopy.Copy(obj)
	if structs.IsStruct(obj) {
		obj = structs.Map(obj)
	}
	switch v := obj.(type) {
	case map[string]interface{}:
		m := make(map[string]interface{}, len(v))
		for key, value := range v {
			SetMapField(m, key, NormalizeValue(value))
		}
		return m
	case map[interface{}]interface{}:
		m := make(map[string]interface{}, len(v))
		for key, value := range v {
			SetMapField(m, key.(string), NormalizeValue(value))
		}
		return m
	case map[string]string:
		m := make(map[string]interface{}, len(v))
		for key, value := range v {
			SetMapField(m, key, value)
		}
		return m
	case []interface{}:
		for i, val := range v {
			v[i] = NormalizeValue(val)
		}
	case string:
		return v
	case nil:
		return ""
	}
	return obj
}

// DelField deletes a value in a tree based on dot key
func DelField(obj map[string]interface{}, k string) bool {
	components := strings.Split(k, ".")
	o, ok := obj[components[0]]
	if !ok {
		return false
	}
	if len(components) == 1 {
		oldLength := len(obj)
		delete(obj, k)
		return oldLength != len(obj)
	}

	object, ok := o.(map[string]interface{})
	if !ok {
		return false
	}
	removed := DelField(object, strings.SplitN(k, ".", 2)[1])
	if removed && len(object) == 0 {
		delete(obj, components[0])
	}

	return removed
}

// GetMapField retrieves a value from a tree from the dot key like "a.b.c.d"
func GetMapField(obj map[string]interface{}, k string) (interface{}, error) {
	components := strings.Split(k, ".")
	for n, component := range components {
		i, ok := obj[component]
		if !ok {
			return nil, getter.ErrFieldNotFound
		}

		if n == len(components)-1 {
			return i, nil
		}

		subkey := strings.Join(components[n+1:], ".")

		switch i.(type) {
		case getter.Getter:
			return i.(getter.Getter).GetField(subkey)
		case []interface{}:
			var results []interface{}
			for _, v := range i.([]interface{}) {
				switch v := v.(type) {
				case getter.Getter:
					if obj, err := v.(getter.Getter).GetField(subkey); err == nil {
						results = append(results, obj)
					}
				case map[string]interface{}:
					if obj, err := GetMapField(v, subkey); err == nil {
						results = append(results, obj)
					}
				}
			}
			return results, nil
		case map[string]interface{}:
			obj = i.(map[string]interface{})
		default:
			return nil, fmt.Errorf("%s is not a supported type(%+v)", component, reflect.TypeOf(obj))
		}
	}

	return obj, nil
}


text:
package com.sillysoft.lux;

import com.sillysoft.lux.*;
import com.sillysoft.lux.util.BoardHelper;
import com.sillysoft.lux.util.ContinentIterator;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.geom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.imageio.*;
import java.awt.image.*;

public class Terrorism implements LuxMapGenerator  {

  //random number generator
  Random rand;
  MapLoader m;
  private String boardSize;   // a value from the choices array
  int boardSeed; // seed number used in file names

  //lux map variables
  String version;
  String width;
  String height;
  String theme;
  String author;
  String email;
  String webpage;
  String title;
  String description;
  String playerinfo;
  String shortContLabels;

  //vectors to hold repeated map variables
  private int numCountries;
  private Country[] countries;
  private Vector connections;
  private Vector countryPolygons;
  private Vector countryNames;
  private Vector countryArmyLocations;
  private Vector contNames;
  private Vector contBonus;
  private Vector contColor;
  private Vector contLabelLoc;
  private Vector lines;
  private Vector players;
  private Vector initialOwners;
  private Vector initialArmies;
  private Vector terrorCoords;

  boolean success = false;

  String mapFile;

  int terrorCount; //number of terrorism links to add
  double terrorPercent;

  //the game calls this when it wants a new map
  //write a map xml to "out"
  public boolean generate(PrintWriter out, String choice, int seed, MapLoader loader) {

    debug("SEED = " + seed);

    //seed must completely determine our map
    rand = new Random(seed);
    m = loader;
    boardSize = choice;
    boardSeed = seed;

    //initialize vars
    countryPolygons = new Vector();
    connections = new Vector();
    //deadCountries = new Vector();
    //newCountryIDs = new Vector();
    //origCountryIDs = new Vector();
    countryNames = new Vector();
    countryArmyLocations = new Vector();
    contNames = new Vector();
    contBonus = new Vector();
    contColor = new Vector();
    lines = new Vector();
    contLabelLoc = new Vector();
    initialOwners = new Vector();
    initialArmies = new Vector();
    terrorCoords = new Vector();

    InitMapChoice(boardSize);

    debug ("mapFile= " + mapFile);
    debug ("terrorPercent= " + terrorPercent);

    //how many countries are in this map?
    numCountries = GetMapSize(mapFile);
    debug ("numCountries= " + numCountries);

    //determine the number of countries to waste
    terrorCount = Math.round((float)(numCountries * terrorPercent));
    debug ("terrorCount= " + terrorCount);

    //minimum of 1 terror link
    if (terrorCount==0) {
        terrorCount = 1;
    }

    //init country array
    countries = new Country[numCountries];

    //init vectors because we may get the countries out of order (they are grouped by cont)
    //and this ensure there is a space relating to the countryID for each value
    for (int i = 0; i < numCountries; i++) {
           countryPolygons.add ("");
           connections.add  ("");
           countryNames.add  ("");
           countryArmyLocations.add  ("");
           initialOwners.add  ("");
           initialArmies.add  ("");
    }

    //read map into variables
    ReadXMLMap (mapFile);

    //try to get terrorCount # of links
    for (int iTerrorLoop = 0; iTerrorLoop < terrorCount; iTerrorLoop++) {
        //randomly pick a country to start
        int fromCountryID = rand.nextInt(numCountries);
        //randomly pick a country to target
        int targetCountryID = rand.nextInt(numCountries);

        //get list of adjoining country codes from original map
        int[] joiningList = countries[fromCountryID].getAdjoiningCodeList();

        boolean bFound;

        bFound = false;

        //for each connection that the original country had
        for (int iConn = 0; iConn < joiningList.length; iConn++) {
            //get the ID joining country
            int toJoinID = joiningList[iConn];

            //if the country we are joining to is the same as our terror link
            if (toJoinID == targetCountryID) {
                bFound = true;
            }
        }

        if (bFound == false) {
            //create country object
            Country toJoin = countries[targetCountryID];

            //add to map connections
            countries[fromCountryID].addToAdjoiningList(toJoin, this);

            terrorCoords.add(countryArmyLocations.get(fromCountryID));
        }

     }

    //write new map file
    WriteMap(out);

    return true;
  }

  private void InitMapChoice(String choice) {
      //determine map file and percentage from choice
    if(choice.equals(CHOICE_CLASSIC_L)) {
      mapFile = "Classic.luxb";
      terrorPercent = .05;
    } else if(choice.equals(CHOICE_CLASSIC_M)) {
      mapFile = "Classic.luxb";
      terrorPercent = .1;
    } else if(choice.equals(CHOICE_CLASSIC_H)) {
      mapFile = "Classic.luxb";
      terrorPercent = .15;
    } else if(choice.equals(CHOICE_CLASSIC_E)) {
      mapFile = "Classic.luxb";
      terrorPercent = .2;
    }  else if(choice.equals(CHOICE_DEUX_L)) {
      mapFile = "DEUX REDUX.luxb";
      terrorPercent = .05;
    }  else if(choice.equals(CHOICE_DEUX_M)) {
      mapFile = "DEUX REDUX.luxb";
      terrorPercent = .1;
    } else if (choice.equals(CHOICE_DEUX_H)) {
      mapFile = "DEUX REDUX.luxb";
      terrorPercent = .15;
    } else if(choice.equals(CHOICE_DEUX_E)) {
      mapFile = "DEUX REDUX.luxb";
      terrorPercent = .2;
    }
  }

  //this function reads a luxb file and determines the number of countries within it.
  //we do this first because our variable loading routines need to know the number of countries
  private int GetMapSize(String mapName) {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

    int countryCount = 0;

    try {
        //try to get the file path
      File support = new File(m.getMapGeneratorPath()).getParentFile();
      String LuxbPath = support.getPath() + File.separator + "Boards" + File.separator +
                                "Saved" + File.separator + mapName;

      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse (new File(LuxbPath));

      //add up the number of countries in each continent
      NodeList nodeList = doc.getElementsByTagName("continent");
      for (int iCont = 0; iCont < nodeList.getLength(); iCont++) {
          Element contNode = (Element) nodeList.item(iCont);
          NodeList countryList = contNode.getElementsByTagName("country");
          countryCount = countryCount + countryList.getLength();
      }

    } catch(Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Could not load the map file. Install the "+mapName+" map and try again.");
    }

    return countryCount;
  }

 //reads a map file to determine how many players are in the starting scenario
 private int HowManyPlayersInMap() {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

    try {
      players = new Vector();

      //try to get the file path
      File support = new File(m.getMapGeneratorPath()).getParentFile();
      String LuxbPath = support.getPath() + File.separator + "Boards" + File.separator +
                                "Saved" + File.separator + mapFile;

      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse (new File(LuxbPath));

      //for each country, add the player ID to our player vector (if new player)
      NodeList nodeList = doc.getElementsByTagName("continent");
      for (int iCont = 0; iCont < nodeList.getLength(); iCont++) {
          Element contNode = (Element) nodeList.item(iCont);
          NodeList countryList = contNode.getElementsByTagName("country");
          for (int iCountry=0; iCountry < countryList.getLength(); iCountry++) {
               Element countryNode = (Element) countryList.item(iCountry);

              NodeList countryChildNode = countryNode.getElementsByTagName("initialOwner");
              Element luxbNode = (Element) countryChildNode.item(0);
              Integer playerID = Integer.parseInt(getCharacterDataFromElement(luxbNode));

              if (!(players.contains(playerID))) {
                  players.add(playerID);
              }
          }
      }

    } catch(Exception e) {
      e.printStackTrace();
    }

    //return how many players we found
    return players.size();
 }

  //this function loads all the variables with the ones from our map
  private void ReadXMLMap(String mapName) {
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

    try {
      File support = new File(m.getMapGeneratorPath()).getParentFile();
      String LuxbPath = support.getPath() + File.separator + "Boards" + File.separator +
                                "Saved" + File.separator + mapName;

      debug("Path= " + LuxbPath);

        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File(LuxbPath));

//<?xml version="1.0" encoding="UTF-8"?>
//<luxboard>

    //<version>1.7</version>
    NodeList nodeList = doc.getElementsByTagName("version");
    Element luxbNode = (Element) nodeList.item(0);
    version = getCharacterDataFromElement(luxbNode);

    //<width>799</width>
    nodeList = doc.getElementsByTagName("width");
    luxbNode = (Element) nodeList.item(0);
    width = getCharacterDataFromElement(luxbNode);

    //<height>511</height>
    nodeList = doc.getElementsByTagName("height");
    luxbNode = (Element) nodeList.item(0);
    height = getCharacterDataFromElement(luxbNode);

    //<theme>Ocean</theme>
    nodeList = doc.getElementsByTagName("theme");
    luxbNode = (Element) nodeList.item(0);
    theme = getCharacterDataFromElement(luxbNode);

    //<author>AJ Bertenshaw</author>
    nodeList = doc.getElementsByTagName("author");
    luxbNode = (Element) nodeList.item(0);
    author = getCharacterDataFromElement(luxbNode);

    //<email>aj@bertenshaw.net</email>
    nodeList = doc.getElementsByTagName("email");
    luxbNode = (Element) nodeList.item(0);
    email = getCharacterDataFromElement(luxbNode);

    //<webpage>http://Bertenshaw.Net/fun/lux/</webpage>
    nodeList = doc.getElementsByTagName("webpage");
    luxbNode = (Element) nodeList.item(0);
    webpage = getCharacterDataFromElement(luxbNode);

    //<title>Classic</title>
    nodeList = doc.getElementsByTagName("title");
    luxbNode = (Element) nodeList.item(0);
    title = getCharacterDataFromElement(luxbNode);

    //<description>The original map layout from the boardgame Risk. This map is included with Lux.</description>
    nodeList = doc.getElementsByTagName("description");
    luxbNode = (Element) nodeList.item(0);
    description = getCharacterDataFromElement(luxbNode);

    //<playerInfoLocation>341,-1</playerInfoLocation>
    nodeList = doc.getElementsByTagName("playerInfoLocation");
    luxbNode = (Element) nodeList.item(0);
    playerinfo = getCharacterDataFromElement(luxbNode);

    //<playerInfoLocation>341,-1</playerInfoLocation>
    nodeList = doc.getElementsByTagName("shortContinentLabels");
    luxbNode = (Element) nodeList.item(0);
    shortContLabels = getCharacterDataFromElement(luxbNode);

//<continent>
//	<continentname>Australia</continentname>
//	<bonus>2</bonus>
//	<color>0.8/0.0/0.8</color>
//	<country>
//      ...
//	</country>
//</continent>

        //read existing map file and store values into our country collection
        nodeList = doc.getElementsByTagName("continent");
        for (int iCont = 0; iCont < nodeList.getLength(); iCont++) {
          Element contNode = (Element) nodeList.item(iCont);

          NodeList contChildNode = contNode.getElementsByTagName("continentname");
          luxbNode = (Element) contChildNode.item(0);
          String contName = getCharacterDataFromElement(luxbNode);

          contChildNode = contNode.getElementsByTagName("bonus");
          luxbNode = (Element) contChildNode.item(0);
          String bonus = getCharacterDataFromElement(luxbNode);

          contChildNode = contNode.getElementsByTagName("color");
          luxbNode = (Element) contChildNode.item(0);
          String color = getCharacterDataFromElement(luxbNode);

          //label location
          contChildNode = contNode.getElementsByTagName("labellocation");
          luxbNode = (Element) contChildNode.item(0);
          String contLabel = getCharacterDataFromElement(luxbNode);

          //store continent values
          contNames.add(contName);
          contBonus.add(bonus);
          contColor.add(color);
          contLabelLoc.add(contLabel);

//		<id>0</id>
//		<name>Eastern Australia</name>
//		<initialOwner>3</initialOwner>
//		<initialArmies>4</initialArmies>
//		<adjoining>1,2</adjoining>
//		<armylocation>693,107</armylocation>
//		<polygon>699,84 687,85 682,93 676,95 672,101 666,118 673,123 676,144 686,139 690,158 695,147 698,135 712,120 713,107 705,89</polygon>

          NodeList countryNodes = contNode.getElementsByTagName("country");
          for (int iCountry = 0; iCountry < countryNodes.getLength(); iCountry++) {
              Element countryNode = (Element) countryNodes.item(iCountry);

              NodeList countryChildNode = countryNode.getElementsByTagName("id");
              luxbNode = (Element) countryChildNode.item(0);
              Integer countryId = Integer.parseInt(getCharacterDataFromElement(luxbNode));

              countryChildNode = countryNode.getElementsByTagName("name");
              luxbNode = (Element) countryChildNode.item(0);
              String countryName = getCharacterDataFromElement(luxbNode);

              countryChildNode = countryNode.getElementsByTagName("adjoining");
              luxbNode = (Element) countryChildNode.item(0);
              String adjoining = getCharacterDataFromElement(luxbNode);

              countryChildNode = countryNode.getElementsByTagName("armylocation");
              luxbNode = (Element) countryChildNode.item(0);
              String armylocation = getCharacterDataFromElement(luxbNode);

              countryChildNode = countryNode.getElementsByTagName("initialOwner");
              luxbNode = (Element) countryChildNode.item(0);
              String initOwner = getCharacterDataFromElement(luxbNode);

              countryChildNode = countryNode.getElementsByTagName("initialArmies");
              luxbNode = (Element) countryChildNode.item(0);
              String initArmy = getCharacterDataFromElement(luxbNode);

              //if no army specified, set it to 1 (the default)
              if (initArmy == "") {
                  initArmy = "1";
              }

              //create country
              countries[countryId] = new Country(countryId, iCont, this);

              //init polygon vector because a country can have multiple
              countryPolygons.set(countryId, new Vector());

              //save country name and army location
              countryNames.set (countryId, countryName);
              countryArmyLocations.set (countryId, armylocation);
              initialOwners.set (countryId, initOwner);
              initialArmies.set (countryId, initArmy);

              //save the polygon tags for each country
              countryChildNode = countryNode.getElementsByTagName("polygon");
              for (int iPolygons = 0; iPolygons < countryChildNode.getLength(); iPolygons++) {
                  luxbNode = (Element) countryChildNode.item(iPolygons);
                  String polygon = getCharacterDataFromElement(luxbNode);

                  ((Vector)countryPolygons.get(countryId)).add(polygon);
              }

              //create a vector for storing adjoining countries individually
              Vector adjList = new Vector();
              String[] adjListArray = adjoining.split(",");
              for (int iAdj = 0; iAdj < adjListArray.length; iAdj++) {
                  adjList.add(adjListArray[iAdj]);
              }

              //save connection vector
              connections.set(countryId, adjList);
          }
       }

       //set up connections, once all countries exist
       for (int iOrig = 0; iOrig < numCountries; iOrig++) {
            for (int iConn = 0; iConn < ((Vector)connections.get(iOrig)).size(); iConn++) {
                Vector connect = (Vector)connections.get(iOrig);

                //get country object for adjoining country
                int countryIndex = Integer.parseInt(connect.get(iConn).toString());
                Country toJoin = countries[countryIndex];

                //add connection
                countries[iOrig].addToAdjoiningList(toJoin, this);
            }
       }

        //<line><position>463,123 481,123</position></line>
        //<line><position>236,386 266,407</position><color>1.0/0.6/0.0</color><width>3</width></line>

        //read lines from map file
       nodeList = doc.getElementsByTagName("line");
       for (int iLine = 0; iLine < nodeList.getLength(); iLine++) {
          Element lineNode = (Element) nodeList.item(iLine);

          NodeList lineChildNode = lineNode.getElementsByTagName("position");
          luxbNode = (Element) lineChildNode.item(0);
          String position = getCharacterDataFromElement(luxbNode);

          lineChildNode = lineNode.getElementsByTagName("color");
          luxbNode = (Element) lineChildNode.item(0);
          String color = getCharacterDataFromElement(luxbNode);

          lineChildNode = lineNode.getElementsByTagName("width");
          luxbNode = (Element) lineChildNode.item(0);
          String linewidth = getCharacterDataFromElement(luxbNode);

          //just store as one string to rewrite later
          String sLine = "";
          sLine = "<position>" + position + "</position>";
          if (color != "") {
              sLine = sLine + "<color>" + color + "</color>";
          }
          if (linewidth != "") {
              sLine = sLine + "<width>" + linewidth + "</width>";
          }
          lines.add(sLine);
       }

    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  //function to read characters from an XML element
  public static String getCharacterDataFromElement(Element e) {
   if (e != null) {
     Node child = e.getFirstChild();
     if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
     }
   }
   return "";
 }

  //this function writes our new mapfile to the print writer
  private void WriteMap(PrintWriter out) {
       //first write the map info. the theme is dynamic based on the original map's theme and the seed
           out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
              "<luxboard>\n" +
              "<version>1.0</version>\n" +
              "<width>" + width + "</width>\n" +
              "<height>" + height + "</height>\n" +
              "<theme>" + theme  + "</theme>\n" +
              "<author>TerrorismLux by RandomGuy</author>\n" +
              "<email></email>\n" +
              "<webpage>www.sillysoft.net</webpage>\n" +
              "<title>" + title + " - TerrorismLux</title>\n" +
              "<description>TerrorismLux map generator modified map. Original map description: " + description + " Type: " + boardSize + "seed: " + boardSeed + "</description>\n");

           //player info location
           out.write("<playerInfoLocation>" +  playerinfo + "</playerInfoLocation>\n");

           //short continent labels
           if (shortContLabels != "") {
               out.write("<shortContinentLabels>" +  shortContLabels + "</shortContinentLabels>\n");
           }

           //for each continent in original file
           for (int i=0; i<contNames.size(); i++) {
              //if we still have countries in the continent in our map
              if (BoardHelper.getContinentSize(i, countries) > 0) {
                  //write the continent
                   out.write("<continent>\n" +
                     	"  <continentname>" + contNames.get(i) + "</continentname>\n" +
                        "  <bonus>" + contBonus.get(i) + "</bonus>\n");

                   //cont color
                   if (contColor.get(i) != "") {
                       out.write("  <color>" + contColor.get(i) + "</color>\n");
                   }

                   //label location
                   if (contLabelLoc.get(i) != "") {
                       out.write("  <labellocation>" + contLabelLoc.get(i) + "</labellocation>\n");
                   }

                   //now iterate through each country in the continent
                   ContinentIterator contIt = new ContinentIterator(i, countries);

                   //we know we have one country
                   do  {
                       Country ctry = contIt.next();

                       //get the country code, and determine the original country id to serve as an index to our vectors
                      int newCode = ctry.getCode();

                      debug("Country: " + countryNames.get(newCode).toString());
                      debug("Code: " + ctry.getCode());
                      debug("initialOwner: " + initialOwners.get(newCode).toString());
                      debug("initialArmies: " + initialArmies.get(newCode).toString());
                      debug("armylocation: " + countryArmyLocations.get(newCode));

                      //write the country tag
                      out.write("  <country>\n" +
                                "    <id>" + ctry.getCode() + "</id>\n" +
                                "    <name>" + countryNames.get(newCode).toString() + "</name>\n" +
                                 "   <initialOwner>" + initialOwners.get(newCode).toString() + "</initialOwner>\n" +
                                 "   <initialArmies>" + initialArmies.get(newCode).toString() + "</initialArmies>\n" +
                                "    <armylocation>" + countryArmyLocations.get(newCode) + "</armylocation>\n");

                      //subroutines for writing connection list
                      writeConnections(out, ctry.getAdjoiningCodeList());

                      //how many polygon tags do we have?
                      int numPolygons = ((Vector)countryPolygons.get(newCode)).size();
                      debug("numPolygons: " + numPolygons);

                      //write out each one
                      for (int iPoly = 0; iPoly < numPolygons; iPoly++) {
                         debug("polygon: " + ((Vector)countryPolygons.get(newCode)).get(iPoly).toString());
                         writePolygon(out, ((Vector)countryPolygons.get(newCode)).get(iPoly).toString());
                      }

                      out.write("  </country>\n");
                   } while (contIt.hasNext());

                   //close cont tag
                   out.write("</continent>\n");
               }
           }

           //lines
           for (int i=0; i< lines.size(); i++) {
               out.write("<line>" + lines.get(i) + "</line>");
           }

           out.write("</luxboard>\n");
           out.flush();
  }

  //write the xml representation of a country's adjoining list
  private void writeConnections(PrintWriter out, int[] conns) {
    out.write("<adjoining>");
    for(int i = 0; i < conns.length-1; i += 1) {
      out.write("" + conns[i] + ",");
    }
    if(conns.length > 0) out.write("" + conns[conns.length-1]);
    out.write("</adjoining>\n");
  }

   //write the xml representation of a country polygon (currently just uses a passed cdv string
  private void writePolygon(PrintWriter out, String polygon) {
    out.write("<polygon>" + polygon + "</polygon>\n");
  }

  //required interface function. should be true on release
  public boolean canCache() {
    return false;
  }

  public String description() {
    return "Terrorism takes an existing map file and generates hidden terrorist connections between countries. It creates hidden one-way connections between countries, representing foreign terror cells operating within another country's borders.";
  }

  //user size choices
  static final String CHOICE_CLASSIC_L = "Terrorism - Classic - Light";
  static final String CHOICE_CLASSIC_M = "Terrorism - Classic - Medium";
  static final String CHOICE_CLASSIC_H = "Terrorism - Classic - Heavy";
  static final String CHOICE_CLASSIC_E = "Terrorism - Classic - Extreme";
  static final String CHOICE_DEUX_L = "Terrorism - Deux - Light";
  static final String CHOICE_DEUX_M = "Terrorism - Deux - Medium";
  static final String CHOICE_DEUX_H = "Terrorism - Deux - Heavy";
  static final String CHOICE_DEUX_E = "Terrorism - Deux - Extreme";

  public java.util.List getChoices() {
    Vector v = new Vector();
    v.add(CHOICE_CLASSIC_L);
    v.add(CHOICE_CLASSIC_M);
    v.add(CHOICE_CLASSIC_H);
    v.add(CHOICE_CLASSIC_E);
    v.add(CHOICE_DEUX_L);
    v.add(CHOICE_DEUX_M);
    v.add(CHOICE_DEUX_H);
    v.add(CHOICE_DEUX_E);
    //v.add(CHOICE_TEST1);
    //v.add(CHOICE_TEST2);
    //v.add(CHOICE_TEST3);
   // v.add(CHOICE_ARMSRACE_L);
    return v;
  }

  //interface function used to return number of players for a map
  public String message(String message, Object data) {
   	{
	if ("scenarioPlayerCount".equals(message))
		{
                debug("get scenario number");
                //set map file
                InitMapChoice((String)data);

                //get how many players are in the map starting scenario
                int numPlayers = HowManyPlayersInMap();

		return String.valueOf(numPlayers);
		}

	return null;
	}
  }

  public String name() {
    return "Terrorism";
  }

  public float version() {
    return 1.2f;
  }

  private void debug(String s) {
    System.out.println(":" + s);
  }
}


text:
package info

import (
	"flag"
	"fmt"
	"sort"

	"github.com/hashicorp/consul/command/flags"
	"github.com/mitchellh/cli"
)

func New(ui cli.Ui) *cmd {
	c := &cmd{UI: ui}
	c.init()
	return c
}

type cmd struct {
	UI    cli.Ui
	flags *flag.FlagSet
	http  *flags.HTTPFlags
	help  string
}

func (c *cmd) init() {
	c.flags = flag.NewFlagSet("", flag.ContinueOnError)
	c.http = &flags.HTTPFlags{}
	flags.Merge(c.flags, c.http.ClientFlags())
	c.help = flags.Usage(help, c.flags)
}

func (c *cmd) Run(args []string) int {
	if err := c.flags.Parse(args); err != nil {
		return 1
	}

	client, err := c.http.APIClient()
	if err != nil {
		c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
		return 1
	}

	self, err := client.Agent().Self()
	if err != nil {
		c.UI.Error(fmt.Sprintf("Error querying agent: %s", err))
		return 1
	}
	stats, ok := self["Stats"]
	if !ok {
		c.UI.Error(fmt.Sprintf("Agent response did not contain 'Stats' key: %v", self))
		return 1
	}

	// Get the keys in sorted order
	keys := make([]string, 0, len(stats))
	for key := range stats {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	// Iterate over each top-level key
	for _, key := range keys {
		c.UI.Output(key + ":")

		// Sort the sub-keys
		subvals, ok := stats[key].(map[string]interface{})
		if !ok {
			c.UI.Error(fmt.Sprintf("Got invalid subkey in stats: %v", subvals))
			return 1
		}
		subkeys := make([]string, 0, len(subvals))
		for k := range subvals {
			subkeys = append(subkeys, k)
		}
		sort.Strings(subkeys)

		// Iterate over the subkeys
		for _, subkey := range subkeys {
			val := subvals[subkey]
			c.UI.Output(fmt.Sprintf("\t%s = %s", subkey, val))
		}
	}
	return 0
}

func (c *cmd) Synopsis() string {
	return synopsis
}

func (c *cmd) Help() string {
	return c.help
}

const synopsis = "Provides debugging information for operators."
const help = `
Usage: consul info [options]

  Provides debugging information for operators.
`


text:
package {{{staticPackage}}}.utils;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Wrapper for other memory caches that adds an expiration date to the hits
 *
 * @author Service Generator
 *
 * Generated Class - DO NOT MODIFY
 */
public class LimitedAgeMemoryCache<T, Q> implements CacheInterface<T, Q> {

    private final CacheInterface<T, Q> cache;
    private final long maximumAge;
    private final Map<T, Long> datesMap = Collections.synchronizedMap(new HashMap<T, Long>());

    /**
     * Applies a wrap layer to any memory cache system so we can add some maximum time the object
     * is valid on the cache.
     * @param cache any other memory cache system
     * @param maximumAge maximum time the cache is valid, in milliseconds
     */
    public LimitedAgeMemoryCache(CacheInterface<T,Q> cache, long maximumAge) {
        this.cache = cache;
        this.maximumAge = maximumAge;
    }

    @Override
    public void put(T request, Q response) {
        cache.put(request, response);
        datesMap.put(request, System.currentTimeMillis());
    }

    @Override
    public Q get(T request) {
        Long date = datesMap.get(request);
        if (date != null && System.currentTimeMillis() - date > maximumAge) {
            cache.remove(request);
            datesMap.remove(request);
        }
        return cache.get(request);
    }

    @Override
    public void remove(T key) {
        cache.remove(key);
        datesMap.remove(key);
    }

    @Override
    public Collection<T> keys() {
        return cache.keys();
    }

    @Override
    public void clear() {
        cache.clear();
        datesMap.clear();
    }
}


text:
#define j1850_active() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET)
#define j1850_passive() HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_RESET)

#define j1850_pwm_passive() {HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_RESET); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);}
#define j1850_pwm_active() {HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_SET);}

#define is_j1850_active() (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_6)==SET)
#define is_j1850_pwm_active() (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_5)==SET)

// define error return codes
#define J1850_RETURN_CODE_UNKNOWN    0
#define J1850_RETURN_CODE_OK         1
#define J1850_RETURN_CODE_BUS_BUSY   2
#define J1850_RETURN_CODE_BUS_ERROR  3
#define J1850_RETURN_CODE_DATA_ERROR 4
#define J1850_RETURN_CODE_NO_DATA    5
#define J1850_RETURN_CODE_DATA       6

// define J1850 VPW timing requirements in accordance with SAE J1850 standard
// all pulse width times in us
// transmitting pulse width
#define TX_SHORT	64		// Short pulse nominal time
#define TX_LONG		128		// Long pulse nominal time
#define TX_SOF		200		// Start Of Frame nominal time
#define TX_EOD		200		// End Of Data nominal time
#define TX_EOF		280		// End Of Frame nominal time
#define TX_BRK		300		// Break nominal time
#define TX_IFS		300		// Inter Frame Separation nominal time
#define PWM_TX_SOF 12  //32us actually
#define PWM_RX_SOF_MAX 13   //51us actually
#define PWM_TX_TP4 15  //48us actually
#define PWM_TX_EOF 60   //
#define PWM_TX_SHORT 5  //8us actually
#define PWM_TX_LONG 12   //16us actually
#define PWM_TX_BIT 22 //24us actually
#define PWM_RX_TP4_MIN 46
#define PWM_RX_TP4_MAX 63

// see SAE J1850 chapter 6.6.2.5 for preferred use of In Frame Respond/Normalization pulse
#define TX_IFR_SHORT_CRC	64	// short In Frame Respond, IFR contain CRC
#define TX_IFR_LONG_NOCRC 128	// long In Frame Respond, IFR contain no CRC

// receiving pulse width
#define RX_SHORT_MIN	34	// minimum short pulse time
#define RX_SHORT_MAX	96	// maximum short pulse time
#define RX_LONG_MIN		96	// minimum long pulse time
#define RX_LONG_MAX		163	// maximum long pulse time
#define RX_SOF_MIN		163	// minimum start of frame time
#define RX_SOF_MAX		239	// maximum start of frame time
#define RX_EOD_MIN		163	// minimum end of data time
#define RX_EOD_MAX		239	// maximum end of data time
#define RX_EOF_MIN		239	// minimum end of frame time, ends at minimum IFS
#define RX_BRK_MIN		239	// minimum break time
#define RX_IFS_MIN		280	// minimum inter frame separation time, ends at next SOF

// see chapter 6.6.2.5 for preferred use of In Frame Respond/Normalization pulse
#define RX_IFR_SHORT_MIN	34		// minimum short in frame respond pulse time
#define RX_IFR_SHORT_MAX	96		// maximum short in frame respond pulse time
#define RX_IFR_LONG_MIN		96		// minimum long in frame respond pulse time
#define RX_IFR_LONG_MAX		63		// maximum long in frame respond pulse time

#define MODE_UNKNOWN 0
#define MODE_VPW 1
#define MODE_PWM 2

extern int idletimeout;
extern u8 j1850_mode;
//extern u8 j1850_msg_pending;
extern u8 j1850_send[12];
extern u8 j1850_recv[12];
extern u8 j1850_msglen;
extern u8 j1850_ifr;

static inline void timer1_start(void)
{
	__HAL_TIM_SET_COUNTER(&htim3,0);
	HAL_TIM_Base_Start(&htim3);
}

static inline void timer1_stop(void)
{
	HAL_TIM_Base_Stop(&htim3);
}

static inline void timer1_set(uint16_t val)
{
	__HAL_TIM_SET_COUNTER(&htim3,val);
}

extern void j1850_vpw_init(void);
extern void j1850_pwm_init(void);
extern uint8_t j1850_vpw_recv_msg(uint8_t *msg_buf );
extern uint8_t j1850_vpw_send_msg(uint8_t *msg_buf, int8_t nbytes);
extern uint8_t j1850_crc(uint8_t *msg_buf, int8_t nbytes);
uint8_t j1850_pwm_send_msg(uint8_t *msg_buf, int8_t nbytes);
uint8_t j1850_pwm_recv_msg(uint8_t *msg_buf);

#endif // __J1850_H__


text:
module RailsAssist::Artifact
  RailsAssist.artifacts.each do |name|
    plural_name = name.to_s.pluralize
    class_eval %{
      module #{name.to_s.camelize}
        def remove_#{name} name
          remove_artifact name, :#{name}
        end

        def remove_#{plural_name} *names
          remove_artifacts :#{name}, *names
        end

        def remove_all_#{plural_name}
          RailsAssist::Artifact::Files.#{name}_files.each do |file_name|
            ::File.delete_file! file_name if ::File.file?(file_name)
          end
        end
        alias_method :delete_all_#{plural_name}, :remove_all_#{plural_name}

        def remove_#{plural_name} *names
          return remove_all_#{plural_name} if names.empty?
          names.to_strings.each do |name|
            file_name = #{name}_file(name)
            ::File.delete!(file_name) if file_name && ::File.file?(file_name)
          end
        end
        alias_method :delete_#{plural_name}, :remove_#{plural_name}
        alias_method :remove_#{name}, :remove_#{plural_name}
        alias_method :delete_#{name}, :remove_#{plural_name}
      end
    }
  end
end


text:
static eLongCalendarManager *curCalendar;

@implementation eLongCalendarManager
@synthesize calendar;

+ (id)shared{
    @synchronized(curCalendar){
        if (!curCalendar){
            [eLongCalendarManager initCurCalendar];
        }
        [eLongCalendarManager reset];
        return curCalendar;
    }
}

+ (void)initCurCalendar{
    curCalendar = [[eLongCalendarManager alloc] init];
    curCalendar.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [curCalendar.calendar setLocale:[NSLocale currentLocale]];
    [curCalendar.calendar setFirstWeekday:eLongCalendarStartDaySunday];
}

+ (void)reset{
    [curCalendar.calendar setLocale:[NSLocale currentLocale]];
}

- (NSDateComponents *)configureDateComponents:(NSDate *)date{
    NSDateComponents *comps = [self.calendar components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday) fromDate:date];
    return comps;
}

//本月的第一天
- (NSDate *)firstDayOfMonthContainingDate:(NSDate *)date{
    NSDateComponents *comps = [self configureDateComponents:date];
    [comps setDay:1];
    return [self.calendar dateFromComponents:comps];
}

//周一,周二,周三。。。
- (NSArray *)getDaysOfTheWeek {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // adjust array depending on which weekday should be first
    NSArray *weekdays = [dateFormatter shortWeekdaySymbols];
    NSInteger firstWeekdayIndex = [self.calendar firstWeekday] -1;
    if (firstWeekdayIndex > 0){
        weekdays = [[weekdays subarrayWithRange:NSMakeRange(firstWeekdayIndex, 7-firstWeekdayIndex)]
                    arrayByAddingObjectsFromArray:[weekdays subarrayWithRange:NSMakeRange(0,firstWeekdayIndex)]];
    }
    return weekdays;
}

- (NSInteger)dayOfWeekForDate:(NSDate *)date{
    NSDateComponents *comps = [self configureDateComponents:date];
    return comps.weekday;
}

- (BOOL)dateIsToday:(NSDate *)date{
    NSDateComponents *otherDay = [self configureDateComponents:date];
    NSDateComponents *today = [self configureDateComponents:[NSDate date]];
    return ([today day] == [otherDay day] &&
            [today month] == [otherDay month] &&
            [today year] == [otherDay year] &&
            [today era] == [otherDay era]);
}

- (BOOL)dateIsYesterday:(NSDate *)date{
    NSDateComponents *otherDay = [self configureDateComponents:date];
    NSDateComponents *yesterday = [self configureDateComponents:[NSDate dateWithTimeIntervalSinceNow:-(24*3600)]];
    return ([yesterday day] == [otherDay day] &&
            [yesterday month] == [otherDay month] &&
            [yesterday year] == [otherDay year] &&
            [yesterday era] == [otherDay era]);
}

- (BOOL)dateIsTomorrow:(NSDate *)date{
    NSDateComponents *otherDay = [self configureDateComponents:date];
    NSDateComponents *tmorrow = [self configureDateComponents:[NSDate dateWithTimeIntervalSinceNow:(24*3600)]];
    return ([tmorrow day] == [otherDay day] &&
            [tmorrow month] == [otherDay month] &&
            [tmorrow year] == [otherDay year] &&
            [tmorrow era] == [otherDay era]);
}

- (BOOL)dateIsDayAfterTomorrow:(NSDate *)date{
    NSDateComponents *otherDay = [self configureDateComponents:date];
    NSDateComponents *dayAfterTmorrow = [self configureDateComponents:[NSDate dateWithTimeIntervalSinceNow:(24*3600*2)]];
    return ([dayAfterTmorrow day] == [otherDay day] &&
            [dayAfterTmorrow month] == [otherDay month] &&
            [dayAfterTmorrow year] == [otherDay year] &&
            [dayAfterTmorrow era] == [otherDay era]);
}

- (BOOL)dateIsEqual:(NSDate *)firstDate secondDate:(NSDate *)secondDate{
    if(firstDate==nil||secondDate==nil)
        return NO;
    NSDateComponents *firstDay = [self configureDateComponents:firstDate];
    NSDateComponents *secondDay = [self configureDateComponents:secondDate];
    return ([firstDay day] == [secondDay day] &&
            [firstDay month] == [secondDay month] &&
            [firstDay year] == [secondDay year] &&
            [firstDay era] == [secondDay era]);
}

//-比较日期
- (int)compareDate:(NSDate *)date1 withCheckOutDate:(NSDate *)date2{
    if(date1==nil||date2==nil)
        return 100;

    NSDateComponents *firstDay = [self configureDateComponents:date1];
    NSDateComponents *secondDay = [self configureDateComponents:date2];

    NSInteger year0 = [firstDay year];
    NSInteger year1 = [secondDay year];
    NSInteger month0 = [firstDay month];
    NSInteger month1 = [secondDay month];
    NSInteger day0 = [firstDay day];
    NSInteger day1 = [secondDay day];

    if (year0 > year1) {
        return 1;
    }else if(year0 == year1){
        if (month0 > month1) {
            return 1;
        }else if(month0 == month1){
            if (day0 > day1) {
                return 1;
            }else if(day0 == day1){
                return 0;
            }else{
                return -1;
            }
        }else{
            return -1;
        }
    }else {
        return -1;
    }
}

//计算相差几天
- (int)getalldays:(NSDate *)checkin withCheckOutDate:(NSDate *)checkout{
    if(checkin==nil||checkout==nil)
        return 0;

    int compareValue = [self compareDate:checkin withCheckOutDate:checkout];
    if(compareValue == 1 || compareValue == 0){
        return 0;
    }
    NSTimeInterval time = [checkout timeIntervalSinceDate:checkin];
    int days = ((int)time) / (3600*24);
    return days;
}

- (NSInteger)weekNumberInMonthForDate:(NSDate *)date{
    NSDateComponents *comps = [self configureDateComponents:date];
    return comps.weekOfMonth;
}

- (int)numberOfWeeksInMonthContainingDate:(NSDate *)date{
    return (int)[self.calendar rangeOfUnit:NSCalendarUnitWeekOfMonth inUnit:NSCalendarUnitMonth forDate:date].length;
}

- (BOOL)dateIsInMonthShowing:(NSDate *)date otherDate:(NSDate *)otherDate{
    NSDateComponents *comps1 = [self configureDateComponents:otherDate];
    NSDateComponents *comps2 = [self configureDateComponents:date];
    return comps1.month == comps2.month;
}

- (NSString *)monthKey:(NSDate *)date{
    NSString *monthKey = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)[self year:date],(long)[self month:date],(long)[self day:date]];
    return monthKey;
}

- (NSDate *)nextDay:(NSDate *)date{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:1];
    NSDate *nextDay = [self.calendar dateByAddingComponents:comps toDate:date options:0];
    return nextDay;
}

- (NSDate *)preDay:(NSDate *)date{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:-1];
    NSDate *preDay = [self.calendar dateByAddingComponents:comps toDate:date options:0];
    return preDay;
}

- (NSDate *)nextMonth:(NSDate *)date{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:1];
    NSDate *nextMonth = [self.calendar dateByAddingComponents:comps toDate:date options:0];
    return nextMonth;
}

- (NSDate *)addMonth:(NSDate *)date addValue:(int)addValue{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMonth:addValue];
    NSDate *re = [self.calendar dateByAddingComponents:comps toDate:date options:0];
    return re;
}

- (NSInteger)getDayCountOfMonth:(NSDate *)date{
    NSDate *fromDate = [self firstDayOfMonthContainingDate:date];
    NSDate *toDate = [self nextMonth:fromDate];
    NSDateComponents *comps = [self.calendar components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    return comps.day;
}

- (NSInteger)hour:(NSDate *)date{
    NSDateComponents *components= [self configureDateComponents:date];
    return [components hour];
}

- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components= [self configureDateComponents:date];
    return [components month];
}

- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components= [self configureDateComponents:date];
    return [components day];
}

-(NSInteger) year:(NSDate *)date{
    NSDateComponents *components= [self configureDateComponents:date];
    return [components year];
}

@end


text: Simple ToDo app for android device


text:
This type provides the capability to manage firewall rules within
puppet.

Current support includes:

* iptables
* ip6tables

### Disclaimer

Warning! While this software is written in the best interest of quality it has
not been formally tested by our QA teams. Use at your own risk, but feel free
to enjoy and perhaps improve it while you do.

Please see the included Apache Software License for more legal details
regarding warranty.

Also as this is a 0.x release the API is still in flux and may change. Make sure
you read the release notes before upgrading.

### Downloading

If you are intending to use this module it is recommended you obtain this from the
forge and not Github:

    http://forge.puppetlabs.com/puppetlabs/firewall

The forge releases are vetted releases. Using code from Github means you are
accessing a development version or early release of the code.

### Installation

Using the puppet-module gem, you can install it into your Puppet's
module path. If you are not sure where your module path is try
this command:

    puppet --configprint modulepath

Firstly change into that directory. For example:

    cd /etc/puppet/modules

Then run the module tool:

    puppet-module install puppetlabs-firewall

This module uses both Ruby based providers so your Puppet configuration
(ie. puppet.conf) must include the following items:

    [agent]
    pluginsync = true

The module will not operate normally without these features enabled for the
client.

If you are using environments or with certain versions of Puppet you may
need to run Puppet on the master first:

    puppet agent -t --pluginsync --environment production

You may also need to restart Apache, although this shouldn't always be the
case.

### Examples

Basic accept ICMP request example:

    firewall { "000 accept all icmp requests":
      proto => "icmp",
      action => "accept",
    }

Drop all:

    firewall { "999 drop all other requests":
      action => "drop",
    }

Source NAT example (perfect for a virtualization host):

    firewall { '100 snat for network foo2':
      chain  => 'POSTROUTING',
      jump   => 'MASQUERADE',
      proto  => 'all',
      outiface => "eth0",
      source => ['10.1.2.0/24'],
      table  => 'nat',
    }

You can make firewall rules persistent with the following iptables example:

    exec { "persist-firewall":
      command => $operatingsystem ? {
        "debian" => "/sbin/iptables-save > /etc/iptables/rules.v4",
        /(RedHat|CentOS)/ => "/sbin/iptables-save > /etc/sysconfig/iptables",
      }
      refreshonly => true,
    }
    Firewall {
      notify => Exec["persist-firewall"]
    }

If you wish to ensure any reject rules are executed last, try using stages.
The following example shows the creation of a class which is where your
last rules should run, this however should belong in a puppet module.

    class my_fw::drop {
      iptables { "999 drop all":
        action => "drop"
      }
    }

    stage { pre: before => Stage[main] }
    stage { post: require => Stage[main] }

    class { "my_fw::drop": stage => "post" }

By placing the 'my_fw::drop' class in the post stage it will always be inserted
last thereby avoiding locking you out before the accept rules are inserted.

### Further documentation

More documentation is available from the forge for each release:

    <http://forge.puppetlabs.com/puppetlabs/firewall>

Or you can access the inline documentation:

    puppet describe firewall

Or:

    puppet doc -r type

(and search for firewall).

### Bugs

Bugs can be reported in the Puppetlabs Redmine project:

    <http://projects.puppetlabs.com/projects/modules/>

## Developer Guide

### Contributing

Make sure you read CONTRIBUTING.md before contributing.

Currently we support:

* iptables
* ip6tables

But plans are to support lots of other firewall implementations:

* FreeBSD (ipf)
* Mac OS X (ipfw)
* OpenBSD (pf)
* Cisco (ASA and basic access lists)

If you have knowledge in these technology, know how to code and wish to contribute
to this project we would welcome the help.

### Testing

Make sure you have:

    rake

Install the necessary gems:

    gem install rspec

And run the tests from the root of the source code:

    rake test


text:
<?php
/**
 * Footer file
 */
if (CLI) {
    return;
}
?>
</div>
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>


text:
package org.flowable.editor.language.xml;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;

public abstract class AbstractConverterTest {

  protected BpmnModel readXMLFile() throws Exception {
    InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(getResource());
    XMLInputFactory xif = XMLInputFactory.newInstance();
    InputStreamReader in = new InputStreamReader(xmlStream, "UTF-8");
    XMLStreamReader xtr = xif.createXMLStreamReader(in);
    return new BpmnXMLConverter().convertToBpmnModel(xtr);
  }

  protected BpmnModel exportAndReadXMLFile(BpmnModel bpmnModel) throws Exception {
    byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
    System.out.println("xml " + new String(xml, "UTF-8"));
    XMLInputFactory xif = XMLInputFactory.newInstance();
    InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(xml), "UTF-8");
    XMLStreamReader xtr = xif.createXMLStreamReader(in);
    return new BpmnXMLConverter().convertToBpmnModel(xtr);
  }

  protected void deployProcess(BpmnModel bpmnModel) {
    /*
     * byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel); ProcessEngineConfiguration configuration = ProcessEngineConfiguration. createStandaloneInMemProcessEngineConfiguration();
     * ProcessEngine processEngine = configuration.buildProcessEngine(); try { Deployment deployment = processEngine.getRepositoryService().createDeployment().name
     * ("test").addString("test.bpmn20.xml", new String(xml)).deploy(); processEngine .getRepositoryService().deleteDeployment(deployment.getId()); } finally { processEngine.close(); }
     */
  }

  protected abstract String getResource();
}


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

namespace Blargh
{
    public class KeyValueList<K, V> : IEquatable<K>
    {
        private List<KeyValuePair<K, V>> _list = new List<KeyValuePair<K, V>>();

        public void Add(K key, V value)
        {
            this._list.Add(new KeyValuePair<K, V>(key, value));
        }

        public void Insert(int index, K key, V value)
        {
            _list.Insert(index, new KeyValuePair<K, V>(key, value));
        }

        public void Clear()
        {
            _list.Clear();
        }

        public void RemoveAt(int index)
        {
            _list.RemoveAt(index);
        }

        public bool Equals(K other)
        {
            throw new NotImplementedException();
        }
    }
}


text:
AliMCTruthCent* AddTaskMCTruthCent(Bool_t doHists = kFALSE)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskMCTruthCent", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskMCTruthCent", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------
  TString name("AliMCTruthCent");
  AliMCTruthCent *eTask = new AliMCTruthCent(name);
  if (doHists) {
    eTask->SetFillHistos();
  }

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------
  mgr->AddTask(eTask);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1  = mgr->GetCommonInputContainer();
  mgr->ConnectInput  (eTask, 0,  cinput1 );

  if (doHists) {
    AliAnalysisDataContainer *coutput = mgr->CreateContainer("MCTruthCentStat",
                                                             TList::Class(),
                                                             AliAnalysisManager::kOutputContainer,
                                                             "MCTruthCent.root");
    mgr->ConnectOutput(eTask,1,coutput);
  }

  return eTask;
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Model;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

/**
 *
 * @author YuchenFeng
 */
public class KeyboardTutorialItem implements ITutorialItem{
   // private int fontsize = 30;

    public KeyboardTutorialItem(String text, int desiredKey){
        this.text = text;
        this.desiredKey = desiredKey;
        this.isHandled = false;
    }

    @Override
    public boolean handle(InputEvent e) {
        if(e instanceof KeyEvent){
            KeyEvent ke = (KeyEvent)e;

            if (ke.getKeyCode() == this.desiredKey) {
                this.isHandled = true;
            }
        }

        return this.isHandled;
    }

    @Override
    public void display(Graphics g) {
        if(!isHandled){
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            g.setFont(new Font("TimesRoman",Font.BOLD,40));
            g.setColor(Color.red);

            g.drawString(text, (int)(85), (int)(600));
            //g.drawString(text, (int)(screenSize.getWidth()/ 2), (int)(screenSize.getHeight() / 2));

        }
    }

    private String text;
    private int desiredKey;
    private boolean isHandled;
}


text:
PACMANIA
========

### Summary

Mr. Pacman is having mental difficulties, and is staying at a mental hospital. The objective of the player is to guide Pacman through his confused mind and consume all of his medication. Beware, however, Pacman has to get worse before he can get better.

For each pill Mr. Pacman collects, there is a chance of a 'ghost' spawning. The 'ghost' blends in to the labyrinth at first, but then You notice. The 'ghost' is pure darkness. It radiates negative light, darkening the environment around it. For each pill consumed the chance of spawning an additional 'ghost' into the labyrinth increases, making his own mind more and more hostile. Thusly, in order to beat PACMANIA, the player must navigate the labyrinth whilst hiding from the increasing number of 'ghosts' that patrols it.

PACMANIA is meant to be a challenge, as a too easy experience would negate the horror element. Because of this; the player will be forced to develop several strategies in order to avoid the 'ghosts' and beat the game.

### Video

[Trailer](http://youtu.be/Jga8JbxKtbc)

[Let's Play](http://youtu.be/RbJzp_pMvj4?t=14m42s)

### Concept Art

![Concept1](http://i.imgur.com/njSbIP1.png)

![Concept2](http://i.imgur.com/t2klEDp.jpg)


text:
package net.juniorbl.jtoyracing.core.monitor;

/**
 * Define methods to the health observers (Observer pattern).
 *
 * @version 1.0 Dec 23, 2007
 * @author Carlos Luz Junior
 */
public interface HealthObserver {

	void healthEnded();
}