text:
package org.txazo.framework.web.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Enumeration;

public class ContextCleanupListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        cleanupAttributes(event.getServletContext());
    }

    static void cleanupAttributes(ServletContext sc) {
        Enumeration<String> attrNames = sc.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = attrNames.nextElement();
            if (attrName.startsWith("org.springframework.")) {
                Object attrValue = sc.getAttribute(attrName);
                attrValue = null;
            }
        }
    }

}


text:
function codebook = train(obj, imlist)
%TRAIN Summary of this function goes here
%   Detailed explanation goes here

% -------------------------------------------------------------------------
% 1. Extract features for training into 'feats' matrix
%     applying any limits on number of features/images
% -------------------------------------------------------------------------

% if trainimage_count was not left at it's default value
% (indicating all detected images should be used for training)
% select a subset of the images
if obj.trainimage_limit > 0
    idxs = 1:length(imlist);
    idxs = vl_colsubset(idxs, obj.trainimage_limit);
    imlist = imlist(idxs);
end

if obj.descount_limit > 0
    % set truncation value for image features just a little bit
    % larger than descount_limit, so if there are any images
    % with fewer than descount_limit/numImages we still have
    % some chance of getting descount_limit descriptors in the end
    img_descount_limit = ceil(obj.descount_limit / ...
        length(imlist) * 1.1);
    fprintf('Extracting a maximum of %d features from each image...\n', ...
        img_descount_limit);
end

feats = cell(length(imlist),1);

% iterate through images, computing features
pfImcount = length(imlist);
parfor ii = 1:length(imlist)
    fprintf('Computing features for: %s %f %% complete\n', ...
        imlist{ii}, ii/pfImcount*100.00);

    im = imread(imlist{ii});
    im = featpipem.utility.standardizeImage(im);
    feats_all = obj.featextr.compute(im); %#ok<PFBNS>

    % if a descount limit applies, discard a fraction of features now to
    % save memory
    if obj.descount_limit > 0
        feats{ii} = vl_colsubset(feats_all, ...
                 img_descount_limit);
    else
        feats{ii} = feats_all;
    end
end
clear feats_all;
% concatenate features into a single matrix
feats = cat(2, feats{:});

extractedFeatCount = size(feats,2);
fprintf('%d features extracted\n', extractedFeatCount);

if obj.descount_limit > 0
    % select subset of features for training
    feats = vl_colsubset(feats, obj.descount_limit);
    % output status message
    fprintf('%d features will be used for training of codebook (%f %%)\n', ...
        obj.descount_limit, obj.descount_limit/extractedFeatCount*100.0);
end

% -------------------------------------------------------------------------
% 2. Cluster codebook centres
% -------------------------------------------------------------------------

fprintf('Clustering features...\n');

% if maxcomps is below 1, then use exact kmeans, else use approximate
% kmeans with maxcomps number of comparisons for distances
if obj.maxcomps < 1
    codebook = vl_kmeans(feats, obj.cluster_count, ...
        'verbose', 'algorithm', 'elkan');
else
    codebook = featpipem.lib.annkmeans(feats, obj.cluster_count, ...
        'verbose', true, 'MaxNumComparisons', obj.maxcomps, ...
        'MaxNumIterations', 150);
end

fprintf('Done training codebook!\n');

end

redpajama_set_name: RedPajamaGithub


text:
// -*- c++ -*-
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

//         O S C L _ S H A R E D _ P T R

// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

/*! \addtogroup osclbase OSCL Base
 *
 * @{
 */

/*! \file oscl_shared_ptr.h
    \brief This file defines a template class OsclSharedPtr which is a "smart pointer" to the parameterized type.
*/

#ifndef OSCL_SHARED_PTR_H_INCLUDED
#define OSCL_SHARED_PTR_H_INCLUDED

#ifndef OSCL_BASE_H_INCLUDED
#include "oscl_base.h"
#endif

#ifndef OSCL_REFCOUNTER_H_INCLUDED
#include "oscl_refcounter.h"
#endif

#define OSCL_DISABLE_WARNING_RETURN_TYPE_NOT_UDT
#include "osclconfig_compiler_warnings.h"

//! A parameterized smart pointer class.
template <class TheClass>
class OsclSharedPtr
{
    public:
        //! Constructor
        OsclSharedPtr() :
                mpRep(NULL), refcnt(NULL) {}

        //! Constructor
        /*!
          \param inClassPtr A pointer to an instance of the parameterized type that the new OsclSharedPtr will wrap.
        */
        OsclSharedPtr(TheClass* inClassPtr, OsclRefCounter* in_refcnt) :
                mpRep(inClassPtr), refcnt(in_refcnt) {};

        //! Copy constructor
        OsclSharedPtr(const OsclSharedPtr& inSharedPtr) :
                mpRep(inSharedPtr.mpRep), refcnt(inSharedPtr.refcnt)
        {
            if (refcnt)
            {
                refcnt->addRef();
            }
        }

        //! Destructor.
        virtual ~OsclSharedPtr()
        {
            if (refcnt != NULL)
            {
                refcnt->removeRef();
            }
        } // end destructor

        //! The dereferencing operator returns a pointer to the parameterized type and can be used to access member
        //! elements of TheClass.
        TheClass* operator->()
        {
            return mpRep;
        }

        //! The indirection operator returns a reference to an object of the parameterized type.
        TheClass& operator*()
        {
            return *mpRep;
        }

        //! Casting operator
        operator TheClass*()
        {
            return mpRep;
        }

        //! Use this function to get a pointer to the wrapped object.
        TheClass* GetRep()
        {
            return mpRep;
        }

        //! Get the refcount pointer.  This should primarily be used for conversion operations
        OsclRefCounter* GetRefCounter()
        {
            return refcnt;
        }

        //! Get a count of how many references to the object exist.
        int get_count()
        {
            return (refcnt == NULL) ? 0 : refcnt->getCount();
        }

        //! Use this function to bind an existing OsclSharedPtr to a already-wrapped object.
        void Bind(const OsclSharedPtr& inHandle);

        //! Use this function to bind an existing OsclSharedPtr to a new (unwrapped) object.
        void Bind(TheClass* ptr, OsclRefCounter* in_refcnt);

        //! Use this function of unbind an existing OsclSharedPtr.
        void Unbind()
        {
            Bind(NULL, NULL);
        };

        //! Assignment operator.
        OsclSharedPtr& operator=(const OsclSharedPtr& inSharedPtr)
        {
            Bind(inSharedPtr);
            return *this;
        }

        //! Test for equality to see if two PVHandles wrap the same object.
        bool operator==(const OsclSharedPtr& b) const;

    private:

        TheClass* mpRep;
        OsclRefCounter* refcnt;

};

template <class TheClass> inline bool OsclSharedPtr<TheClass>::operator==(const OsclSharedPtr<TheClass>& b) const
{
    if ((this->mpRep == b.mpRep) &&
            (this->refcnt == b.refcnt))
    {
        return true;
    }
    return false;
}

template <class TheClass> inline void OsclSharedPtr<TheClass>::Bind(const OsclSharedPtr& inSharedPtr)
{
    if (mpRep == inSharedPtr.mpRep) return;

    if (refcnt != NULL)
    {
        refcnt->removeRef();
    }

    refcnt = inSharedPtr.refcnt;
    mpRep = inSharedPtr.mpRep;

    if (refcnt != NULL)
    {
        refcnt->addRef();
    }

}

template <class TheClass> inline void OsclSharedPtr<TheClass>::Bind(TheClass* ptr,
        OsclRefCounter* in_refcnt)
{
    if (refcnt != NULL)
    {
        refcnt->removeRef();
    }

    mpRep = ptr;
    refcnt = in_refcnt;

}

#endif  // OSCL_SHARED_PTR_H_INCLUDED


text:
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverloadedStrings    #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Main where

import           Data.Aeson
import           Data.Aeson.Types
import qualified Data.HashMap.Strict as HM
import           Data.Text
import           Helery

data MyRouter = AHandlerRoute AHandler
              | BHandlerRoute BHandler
               deriving (Eq, Show)

instance Dispatchable MyRouter where
    dispatch (AHandlerRoute handler) = handle handler
    dispatch (BHandlerRoute handler) = handle handler

instance FromJSON MyRouter where
    parseJSON args@(Object v) =
        case HM.lookup "task" v of
            Just (String "AHandler") ->
                AHandlerRoute <$> (parseJSON args :: Parser AHandler)
            Just (String "BHandler") ->
                BHandlerRoute <$> (parseJSON args :: Parser BHandler)
            Nothing -> fail "Not Found routing"

-- ----------------------------------------------------------------------------
-- Define A Handler
-- ----------------------------------------------------------------------------
type AHandler = BaseHandler AHandlerArgs AHandlerKwargs

instance FromJSON AHandler where
    parseJSON (Object v) =
        case HM.lookup "task" v of
            Just (String "AHandler") ->
                BaseHandler <$> pure "AHandler"
                            <*> v .: "args"
                            <*> v .: "kwargs"

instance Handler AHandler where
    handle = print

-- | define Args type.
data AHandlerArgs = AHandlerArgs Int Int deriving (Eq, Show)

instance FromJSON AHandlerArgs where
    parseJSON jsn = do
        (a, b) <- parseJSON jsn
        return $ AHandlerArgs a b

-- | define Kwargs type.
data AHandlerKwargs = AHandlerKwargs
    { aName :: Text
    , aAge  :: Int }
    deriving (Eq, Show)

instance FromJSON AHandlerKwargs where
    parseJSON (Object v) =
        AHandlerKwargs <$> v .: "name"
                       <*> v .: "age"

-- ----------------------------------------------------------------------------
-- | Define B Handler
-- ----------------------------------------------------------------------------
type BHandler = BaseHandler BHandlerArgs BHandlerKwargs

instance FromJSON BHandler where
    parseJSON (Object v) =
        case HM.lookup "task" v of
            Just (String "BHandler") ->
                BaseHandler <$> pure "BHandler"
                            <*> v .: "args"
                            <*> v .: "kwargs"

instance Handler BHandler where
    handle = print

-- | define Args type.
data BHandlerArgs = BHandlerArgs Int Int deriving (Eq, Show)

instance FromJSON BHandlerArgs where
    parseJSON jsn = do
        (a, b) <- parseJSON jsn
        return $ BHandlerArgs a b

-- | define Kwargs type.
data BHandlerKwargs = BHandlerKwargs
    { bName :: Text
    , bAge  :: Int }
    deriving (Eq, Show)

instance FromJSON BHandlerKwargs where
    parseJSON (Object v) =
        BHandlerKwargs <$> v .: "name"
                       <*> v .: "age"

main :: IO ()
main = do
    options <- parseCommandLineOption
    print options  -- Debug for option value
    runApp options (routing :: RoutingType IO MyRouter)


text:
//
//  TKCalendarFXView.h
//  Telerik UI
//
//  Copyright (c) 2014 Telerik. All rights reserved.
//

@class TKViewTransition;

/**
 * @enum TKViewTransitionOrientation
 * @discussion Represents an enum that defines the available transition orientation options.
 */
typedef NS_ENUM(NSInteger, TKViewTransitionOrientation)
{
    /**
     *  The transition orientation is horizontal.
     */
    TKViewTransitionOrientationHorizontal,

    /**
     *  The transition orientation is vertical.
     */
    TKViewTransitionOrientationVertical

};

/**
 * @enum TKViewTransitionDirection
 * @discussion Represents an enum that defines the available transition direction options.
 */
typedef NS_ENUM(NSInteger, TKViewTransitionDirection)
{
    /**
     *  The transition direction is forward.
     */
    TKViewTransitionDirectionForward,

    /**
     *  The transition direction is backward.
     */
    TKViewTransitionDirectionBackward

};

/**
 *  @discussion A transition effect between two states of the same view.
 */
@interface TKViewTransition : UIView

/**
 *  Gets or sets the transition duration.
 */
@property (nonatomic) CGFloat transitionDuration;

/**
 *  Returns the transition orientation.

  @discussion The available orientation modes are specified below:

 typedef enum {
 TKViewTransitionOrientationHorizontal,  // The transition orientation is horizontal.
 TKViewTransitionOrientationVertical     // The transition orientation is vertical.
 } TKViewTransitionOrientation

 */
- (TKViewTransitionOrientation) orientation;

/**
 *  Returns the transition direction.

  @discussion The available direction modes are specified below:

 typedef enum {
 TKViewTransitionDirectionForward,   // The transition direction is forward.
 TKViewTransitionDirectionBackward   // The transition direction is backward.
 } TKViewTransitionDirection

 */
- (TKViewTransitionDirection) direction;

/**
 *  Returns YES when the transition is forward.
 */
@property (nonatomic, readonly) BOOL isForward;

/**
 *  Returns YES when the transition is vertical.
 */
@property (nonatomic, readonly) BOOL isVertical;

@end


text:
package org.terkwood.pathfinding.core.models

import org.scalatest.{FlatSpec, MustMatchers}

class GridSpec extends FlatSpec with MustMatchers {

  {
    val width = 10
    val height = 20
    val grid = Grid(width, height)

    "A grid, created without a matrix" must "have correct size" in {
      grid.width mustEqual width
      grid.height mustEqual height

      grid.nodes.length mustEqual height

      Range(0, height) foreach {
        grid.nodes(_).length mustEqual width
      }
    }

    it must "set all nodes' walkable attributes" in {
      for {
        i <- 0 until height
        j <- 0 until width
      } grid isWalkableAt(j, i) mustBe false
    }
  }

  {
    val matrix: IndexedSeq[IndexedSeq[WalkableStatus]] = IndexedSeq(
      IndexedSeq(NoWalk, Walk, Walk, NoWalk),
      IndexedSeq(Walk, NoWalk, Walk, Walk),
      IndexedSeq(Walk, NoWalk, Walk, Walk),
      IndexedSeq(Walk, Walk, Walk, Walk),
      IndexedSeq(NoWalk, Walk, Walk, NoWalk)
    )

    val width: Int = matrix.head.length
    val height: Int = matrix.length

    val grid = Grid(width, height, matrix)

    def enumPos2[A](f: (Int, Int) => A) =
      for {y <- 0 until height
           x <- 0 until width}
        yield
          f(x, y)

    def enumPos3[A](f: (Int, Int, Grid) => A) =
      for {y <- 0 until height
           x <- 0 until width}
        yield
          f(x, y, grid)

    "A grid, created with a matrix" must "have correct size" in {
      grid.width mustEqual width
      grid.height mustEqual height

      grid.nodes.length mustEqual height

      for {i <- 0 until height}
        grid.nodes(i).length mustEqual width
    }

    it must "correctly default all nodes' walkable attributes" in {
      enumPos3((x, y, g) => {
        matrix(y)(x) match {
          case NoWalk => g isWalkableAt(x, y) mustBe false
          case Walk => g isWalkableAt(x, y) mustBe true
        }
      })
    }

    it must "update all nodes' walkable attributes" in {
      var result = grid
      enumPos2 { (x, y) =>
        result = result.withWalkableAt(x, y, walkable = false)
      }

      enumPos2 { (x, y) =>
        withClue(s"#0: isWalkable($x,$y) failed") {
          result isWalkableAt(x, y) mustBe false
        }
      }

      enumPos2 { (x, y) =>
        result = result.withWalkableAt(x, y, walkable = true)
      }

      enumPos2 { (x, y) =>
        withClue(s"#1: isWalkable($x,$y) failed") {
          result isWalkableAt(x, y) mustBe true
        }
      }
    }

    it must "return the node at the coordinate requested" in {
      grid.nodeAt(0,0).get mustEqual Node(0,0,walkable = false)
    }
    it must "return a Failure if the given coordinate is outside the grid's x boundary" in {
      val attempt = grid.nodeAt(width + 5, 0)
      attempt.isFailure mustBe true
    }
    it must "return a Failure if the given coordinate is outside the grid's y boundary" in {
      val attempt = grid.nodeAt(0, height + 5)
      attempt.isFailure mustBe true
    }

    it must "return a correct answer for position validity query" in {
      val asserts = Seq(
        (0, 0, true),
        (0, height - 1, true),
        (width - 1, 0, true),
        (width - 1, height - 1, true),
        (-1, -1, false),
        (0, -1, false),
        (-1, 0, false),
        (0, height, false),
        (width, 0, false),
        (width, height, false)
      )

      asserts foreach { case (p, q, z) =>
        ((p, q) isInside grid) mustEqual z
      }
    }

    it must "return the correct neighbors" in {
      grid getNeighbors(grid.nodes(1)(0), DiagonalMovement.Never) mustEqual IndexedSeq(grid.nodes(2)(0))

      def compare(a: Node, b: Node) =
        a.x * 100 + a.y > b.x * 100 - b.y

      grid
        .getNeighbors(grid.nodes(0)(2), DiagonalMovement.IfAtMostOneObstacle)
        .sortWith(compare) mustEqual
        Seq(grid.nodes(0)(1), grid.nodes(1)(2), grid.nodes(1)(3))
          .sortWith(compare)
    }
  }

  {
    val matrix: IndexedSeq[IndexedSeq[WalkableStatus]] = Seq(
      Seq(true, false, false, true),
      Seq(false, true, false, false),
      Seq(false, true, false, false),
      Seq(false, false, false, false),
      Seq(true, false, false, true)).toWalkable

    val grid = Grid(matrix)

    "A grid, created with a matrix, and without width or height" must "have correct size" in {
      val height = matrix.length
      val width = matrix.head.length

      grid.width mustEqual width
      grid.height mustEqual height

      grid.nodes.length mustEqual height
      for {i <- 0 until height}
        grid.nodes(i).length mustEqual width
    }
  }
}


text:
package grapho

import "time"

type Post struct{}

func NewPost() *Post { return &Post{} }

type PostDraftedEvent struct {
	Id        string
	Title     string
	Body      string
	DraftedAt time.Time
}

func (self *PostDraftedEvent) EventType() string { return "post/drafted" }
func init()                                      { RegisterEvent(&PostDraftedEvent{}) }

type DraftPostCommand struct {
	PostId PostId
	Title  string
	Body   string
	Now    time.Time
}

func (self *Post) Draft(params *DraftPostCommand) (Events, error) {
	return Events{
		&PostDraftedEvent{
			Id:        params.PostId.String(),
			Title:     params.Title,
			Body:      params.Body,
			DraftedAt: params.Now,
		},
	}, nil
}


text:
package utils

import (
	"testing"

	"github.com/VirusTotal/gyp"
	"github.com/VirusTotal/gyp/ast"
	"github.com/google/go-cmp/cmp"
)

func TestMultipleInLoopWithIdents(t *testing.T) {
	condition := `false or for any i in (1..5):(true) and for any z in (1..5): (true or foo)`
	expected := map[string]int{"foo": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestNestedInLoopWithIdents(t *testing.T) {
	condition := `b or false or for any i in (1..5):(true and for any z in (1..5): (true or foo))`
	expected := map[string]int{"b": 0, "foo": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestInLoopWithIdents(t *testing.T) {
	condition := `foo_zz and for any i in (1..5): (foo and uint32(filesize - (i * 0x100) - 4) == (i * 0x00000100) + 4 and uint32(filesize - (i * 0x100)) == 0x10)`
	expected := map[string]int{"foo_zz": 0, "foo": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestInLoopWithNoIdents(t *testing.T) {
	condition := `foo_zz and for any i in (1..5): (uint32(filesize - (i * 0x100) - 4) == (i * 0x00000100) + 4 and uint32(filesize - (i * 0x100)) == 0x10)`
	expected := map[string]int{"foo_zz": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestLotsOfIdents(t *testing.T) {
	condition := `pe.exports("foo0")
    or pe.exports("foo1")
    or pe.exports("foo2")
    or pe.exports("foo3")`
	expected := map[string]int{"pe": 3}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestThreeDupIdents(t *testing.T) {
	condition := `foo_zz or foo_zz or foo_zz or $a`
	expected := map[string]int{"foo_zz": 2}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestOneIdents(t *testing.T) {
	condition := `foo_zz or $a`
	expected := map[string]int{"foo_zz": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestStrOffsetImport(t *testing.T) {
	condition := `$a at pe.entry_point`
	expected := map[string]int{"pe": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestNoIdents(t *testing.T) {
	condition := `all of ($a*) and ($a or $a)`
	expected := map[string]int{}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestNotIdent(t *testing.T) {
	condition := `not foo_zz`
	expected := map[string]int{"foo_zz": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestNestedIdents(t *testing.T) {
	condition := `(foo_zz or foo_zz) and $a or ($a and (foo_xx or a))`
	expected := map[string]int{"foo_zz": 1, "foo_xx": 0, "a": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestSingleDupIdent(t *testing.T) {
	condition := `(foo_zz or foo_zz)`
	expected := map[string]int{"foo_zz": 1}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestSingleGroupIdent(t *testing.T) {
	condition := `(foo_zz)`
	expected := map[string]int{"foo_zz": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func TestSingleIdent(t *testing.T) {
	condition := `foo_zz`
	expected := map[string]int{"foo_zz": 0}
	testGetYARARuleDependencies(t, condition, expected)
}

func testGetYARARuleDependencies(t *testing.T, condition string, expected map[string]int) {
	rulestr := "rule foo {strings:$a = \"test\" condition:" + condition + "}"
	ruleset, err := gyp.ParseString(rulestr)
	if err != nil {
		t.Errorf("Unable to parse rule")
	}
	results := GetUsedIdentifiers(*ruleset.Rules[0])
	if ok := cmp.Equal(results, expected); ok == false {
		t.Errorf("Condition not extracted correctly. Expected %v, but got %v", expected, results)
	}
}

func TestAddToIdentMapWithIgnoreList(t *testing.T) {
	expected := map[string]int{}
	ident := ast.Identifier{Identifier: "foo"}
	ruleIdentifiers := make(map[string]int)
	ignoreList := []string{"foo"}
	addToIdentMap(&ident, ruleIdentifiers, ignoreList)
	if ok := cmp.Equal(ruleIdentifiers, expected); ok == false {
		t.Errorf("Expected %v but got %v", expected, ruleIdentifiers)
	}
}

func TestAddToIdentMap(t *testing.T) {
	expected := map[string]int{"foo": 0}
	ident := ast.Identifier{Identifier: "foo"}
	ruleIdentifiers := make(map[string]int)
	ignoreList := []string{""}
	addToIdentMap(&ident, ruleIdentifiers, ignoreList)
	if ok := cmp.Equal(ruleIdentifiers, expected); ok == false {
		t.Errorf("Expected %v but got %v", expected, ruleIdentifiers)
	}
}

func TestAddNodeGrpIdentifierToIdentifiersMap(t *testing.T) {
	ruleset, err := gyp.ParseString("rule foo { condition:(foo)}")
	if err != nil {
		t.Fatalf("Unable to parse rule")
	}
	expected := map[string]int{"foo": 0}
	ruleIdentifiers := GetUsedIdentifiers(*ruleset.Rules[0])
	if ok := cmp.Equal(ruleIdentifiers, expected); ok == false {
		t.Errorf("Expected %v but got %v", expected, ruleIdentifiers)
	}
}

func TestAddNodeChildrenToQue(t *testing.T) {
	ruleset, err := gyp.ParseString("rule foo {condition:test and test2}")
	if err != nil {
		t.Fatalf("Unable to parse rule")
	}
	queue := append([]queueT{}, queueT{node: ruleset.Rules[0].Condition})
	addNodeChildrenToQue(&queue)
	if len(queue) != 3 {
		t.Fatalf("Did not add node children to queue")
	}
}

func TestSliceContains(t *testing.T) {
	animals := []string{"cat", "dog", "bird"}
	testStrs := []string{"fish", "d0g"}
	for _, testStr := range testStrs {
		if ok := sliceContains(testStr, animals); ok {
			t.Fatalf("sliceContains is reporting that %s exists in %v", testStr, animals)
		}
	}
	if ok := sliceContains("dog", animals); !ok {
		t.Fatalf("sliceContains is reporting that %s does not exist in %v", "dog", animals)
	}
}

func TestSortRules(t *testing.T) {
	rules := `rule a {condition:c} rule b {condition:false} rule c {condition:b}`
	ruleset, err := gyp.ParseString(rules)
	if err != nil {
		t.Fatalf("Unable to parse rules: %s", err)
	}
	results := SortRules(*ruleset)
	expectedResults := []string{"b", "c", "a"}
	for i := range results.Rules {
		if results.Rules[i].Identifier != expectedResults[i] {
			t.Fatalf("SortRules did not correctly sort the ruleset")
		}
	}
}
func TestGetDependenciesForRules(t *testing.T) {
	rulestr := `rule woo {condition:false} rule test {strings: $wooo = "1" condition:foo_zz or $wooo} rule test2 {strings: $gazunder = "woo" condition: wxs or pe.imports and wxs or wxs or wxs or foo and $gazunder or test or woo}`
	ruleset, err := gyp.ParseString(rulestr)
	if err != nil {
		t.Fatalf("Unable to parse rules: %s", err)
	}
	dependencies, err := GetDependenciesForRules(*ruleset, "test2")
	if err != nil {
		t.Fatalf("GetDependenciesForRules returned an error (%s)", err.Error())
	}
	expectedImports := []string{"pe"}
	expectedRules := []string{"woo", "test"}

	if !cmp.Equal(expectedImports, dependencies.Imports) || len(dependencies.Rules) != 2 {
		t.Fatalf("expected %+v, but got %+v", expectedImports, dependencies)
	}
	for _, rule := range dependencies.Rules {
		if !sliceContains(rule.Identifier, expectedRules) {
			t.Fatalf("expected %+v, but %s was not found", expectedRules, rule.Identifier)
		}
	}
}

func TestGetDependenciesForRulesEmptyRuleset(t *testing.T) {
	_, err := GetDependenciesForRules(ast.RuleSet{}, "test2")
	if err.Error() != "ruleset does not contain any rules" {
		t.Fatalf("Empty ruleset was provided to GetDependenciesForRules, but no error was thrown")
	}
}

func TestGetDependenciesForRulesMissingFromRuleset(t *testing.T) {
	rulestr := `rule woo {condition:false} rule test {condition:foo_zz or $wooo}`
	ruleset, _ := gyp.ParseString(rulestr)
	_, err := GetDependenciesForRules(*ruleset, "foo")
	if err.Error() != "foo does not exist in the ruleset" {
		t.Fatalf("Empty ruleset was provided to GetDependenciesForRules, but no error was thrown")
	}
}

func TestGetDependencyChainForRules(t *testing.T) {
	expectedImports := []string{"pe"}
	expectedRules := []string{"z", "c", "a"}
	rules := `rule a {condition:false or c} rule b {condition:false or a} rule c {condition:false and pe.exports and z} rule d {condition:false or b} rule z {condition:true}`
	ruleset, _ := gyp.ParseString(rules)
	rChain, err := GetRulesSubset(*ruleset, "b")
	if err != nil {
		t.Fatalf(err.Error())
	}
	if !cmp.Equal(rChain.Imports, expectedImports) {
		t.Fatalf("Expected %v, but got %v", expectedImports, rChain.Imports)
	}
	ruleNames := []string{}
	for _, rules := range rChain.Rules {
		ruleNames = append(ruleNames, rules.Identifier)
	}
	if !cmp.Equal(ruleNames, expectedRules) {
		t.Fatalf("Expected %v, but got %v", expectedRules, ruleNames)
	}
}

func TestGetDependencyChainErr(t *testing.T) {
	rules := `rule a {condition:false or c} rule b {condition:false or a} rule c {condition:false or b and pe.exports} rule d {condition:false or b}`
	ruleset, _ := gyp.ParseString(rules)
	_, err := GetRulesSubset(*ruleset, "woo")
	if err.Error() != "woo does not exist in the ruleset" {
		t.Fatalf("Empty ruleset was provided to GetDependenciesForRules, but no error was thrown")
	}
}

func TestAddNilNodeToQue(t *testing.T) {
	nkr := `
	rule foo_x {
		condition:
			true
	  }
	rule foo_y {
		strings:
		  $foo = "foo"
		  $foo2 = "foo2"
		condition:
		  foo_x and
		  (
			$foo in (@foo2 - 100..@foo2 + 100)
		  )
	  }`
	nrs, _ := gyp.ParseString(string(nkr))
	results, _ := GetRulesSubset(*nrs, "foo_y")
	expected := "foo_x"
	if results.Rules[0].Identifier != expected {
		t.Fatalf("Did not get expected value (%s)", expected)
	}
}


text:
				Add New Question

			<?php

			require 'add_question_code.php';

			echo "
			<form method=\"POST\" id=\"block_content\">

				*Author:
				<input id=\"Author\" name=\"Author\" maxlength=\"30\" type=\"text\" class=\"non_submit_input\">

				*Question:
				<input id=\"Question\" name=\"Question\" maxlength=\"50\" type=\"textfield\" class=\"non_submit_input\">

				*Answer:
				<input id=\"Answer\" name=\"Answer\" maxlength=\"30\" type=\"text\" class=\"non_submit_input\">

				<input type=\"submit\" name=\"AddQuestion\" id=\"submit_registration\" value=\"Submit Entry\">
			</form>";

			?>

				Created on 15.01.2013, 17:13

					by CharlieScarver


text:
set -exo pipefail

function build_linux () {
    local tags=osusergo,netgo,sqlite_foreign_keys,sqlite_json,static_build
    local cc
    case $(go env GOARCH) in
        amd64)
            cc=$(xcc linux x86_64)
            ;;
        arm64)
            cc=$(xcc linux aarch64)
            tags="$tags,noasm"
            ;;
        *)
            >&2 echo Error: Unknown arch $(go env GOARCH)
            exit 1
            ;;
    esac

    local -r extld="-fno-PIC -static -Wl,-z,stack-size=8388608"
    CGO_ENABLED=1 PKG_CONFIG=$(which pkg-config) CC="${cc}" go-test-compile \
        -tags "$tags" -o "${1}/" -ldflags "-extldflags '$extld'" ./...
}

function build_mac () {
    CGO_ENABLED=1 PKG_CONFIG=$(which pkg-config) CC="$(xcc darwin)" go-test-compile \
        -tags sqlite_foreign_keys,sqlite_json -o "${1}/" ./...
}

function build_windows () {
    CGO_ENABLED=1 PKG_CONFIG=$(which pkg-config) CC="$(xcc windows)" go-test-compile \
        -tags sqlite_foreign_keys,sqlite_json,timetzdata -o "${1}/" ./...
}

function build_test_tools () {
    # Copy pre-built gotestsum out of the cross-builder.
    local ext=""
    if [ "$(go env GOOS)" = windows ]; then
        ext=".exe"
    fi
    cp "/usr/local/bin/gotestsum_$(go env GOOS)_$(go env GOARCH)${ext}" "$1/gotestsum${ext}"

    # Build test2json from the installed Go distribution.
    CGO_ENABLED=0 go build -o "${1}/" -ldflags="-s -w" cmd/test2json
}

function write_test_metadata () {
    # Write version that should be reported in test results.
    echo "$(go env GOVERSION) $(go env GOOS)/$(go env GOARCH)" > "${1}/go.version"

    # Write list of all packages.
    go list ./... > "${1}/tests.list"
}

function main () {
    if [[ $# != 1 ]]; then
        >&2 echo Usage: $0 '<output-dir>'
        exit 1
    fi
    local -r out_dir="$1"

    mkdir -p "$out_dir"
    case $(go env GOOS) in
        linux)
            build_linux "$out_dir"
            ;;
        darwin)
            build_mac "$out_dir"
            ;;
        windows)
            build_windows "$out_dir"
            ;;
        *)
            >&2 echo Error: unknown OS $(go env GOOS)
            exit 1
            ;;
    esac

    # Build gotestsum and test2json so downstream jobs can use it without needing `go`.
    build_test_tools "$out_dir"
    # Write other metadata needed for testing.
    write_test_metadata "$out_dir"
}

main ${@}


text:
"""

.. module:: niftynet
   :synopsis: Entry points for the NiftyNet CLI.

"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

# Before doing anything else, check TF is installed
# and fail gracefully if not.
try:
    import tensorflow as tf
except ImportError:
    raise ImportError('NiftyNet is based on TensorFlow, which'
                      ' does not seem to be installed on your'
                      ' system.\n\nPlease install TensorFlow'
                      ' (https://www.tensorflow.org/) to be'
                      ' able to use NiftyNet.')

try:
    from distutils.version import LooseVersion

    minimal_required_version = LooseVersion("1.5")
    tf_version = LooseVersion(tf.__version__)
    if tf_version < minimal_required_version:
        tf.logging.fatal('TensorFlow %s or later is required.'
                         '\n\nPlease upgrade TensorFlow'
                         ' (https://www.tensorflow.org/) to be'
                         ' able to use NiftyNet.\nCurrently using '
                         'TensorFlow %s:\ninstalled at %s\n\n',
                         minimal_required_version, tf_version, tf.__file__)
        raise ImportError
    else:
        tf.logging.info('TensorFlow version %s', tf_version)
except AttributeError:
    pass

from niftynet.utilities.versioning import get_niftynet_version_string

__version__ = get_niftynet_version_string()

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
try:
    from tensorflow.python.util import module_wrapper as deprecation
except ImportError:
    from tensorflow.python.util import deprecation_wrapper as deprecation
deprecation._PER_MODULE_WARNING_LIMIT = 0

from niftynet.io.misc_io import set_logger, close_logger

set_logger()

from niftynet.utilities.util_import import require_module

require_module('blinker', descriptor='New dependency', mandatory=True)

from tensorflow.python.util import deprecation

deprecation._PRINT_DEPRECATION_WARNINGS = False

from niftynet.engine.signal import TRAIN, INFER, EVAL
import niftynet.utilities.util_common as util
import niftynet.utilities.user_parameters_parser as user_parameters_parser
from niftynet.engine.application_driver import ApplicationDriver
from niftynet.evaluation.evaluation_application_driver import \
    EvaluationApplicationDriver
from niftynet.io.misc_io import touch_folder
from niftynet.io.misc_io import resolve_module_dir
from niftynet.io.misc_io import to_absolute_path

def main():
    system_param, input_data_param = user_parameters_parser.run()
    if util.has_bad_inputs(system_param):
        return -1

    # print all parameters to txt file for future reference
    all_param = {}
    all_param.update(system_param)
    all_param.update(input_data_param)

    # Set up path for niftynet model_root
    # (rewriting user input with an absolute path)
    system_param['SYSTEM'].model_dir = resolve_module_dir(
        system_param['SYSTEM'].model_dir,
        create_new=system_param['SYSTEM'].action == TRAIN)

    # writing all params for future reference
    txt_file = 'settings_{}.txt'.format(system_param['SYSTEM'].action)
    txt_file = os.path.join(system_param['SYSTEM'].model_dir, txt_file)
    try:
        util.print_save_input_parameters(all_param, txt_file)
    except IOError:
        tf.logging.fatal(
            'Unable to write %s,\nplease check '
            'model_dir parameter, current value: %s',
            txt_file, system_param['SYSTEM'].model_dir)
        raise

    # keep all commandline outputs to model_root
    log_file_name = os.path.join(
        system_param['SYSTEM'].model_dir,
        '{}_{}'.format(all_param['SYSTEM'].action, 'niftynet_log'))
    set_logger(file_name=log_file_name)

    # set up all model folder related parameters here
    # see https://cmiclab.cs.ucl.ac.uk/CMIC/NiftyNet/issues/168
    # 1. resolve mapping file:
    try:
        if system_param['NETWORK'].histogram_ref_file:
            system_param['NETWORK'].histogram_ref_file = to_absolute_path(
                input_path=system_param['NETWORK'].histogram_ref_file,
                model_root=system_param['SYSTEM'].model_dir)
    except (AttributeError, KeyError):
        pass
    # 2. resolve output file:
    try:
        if system_param['INFERENCE'].save_seg_dir:
            system_param['INFERENCE'].save_seg_dir = to_absolute_path(
                input_path=system_param['INFERENCE'].save_seg_dir,
                model_root=system_param['SYSTEM'].model_dir)
    except (AttributeError, KeyError):
        pass
    # 3. resolve dataset splitting file:
    try:
        if system_param['SYSTEM'].dataset_split_file:
            system_param['SYSTEM'].dataset_split_file = to_absolute_path(
                input_path=system_param['SYSTEM'].dataset_split_file,
                model_root=system_param['SYSTEM'].model_dir)
    except (AttributeError, KeyError):
        pass

    # 4. resolve evaluation dir:
    try:
        if system_param['EVALUATION'].save_csv_dir:
            system_param['EVALUATION'].save_csv_dir = to_absolute_path(
                input_path=system_param['EVALUATION'].save_csv_dir,
                model_root=system_param['SYSTEM'].model_dir)
    except (AttributeError, KeyError):
        pass

    # start application
    driver_table = {
        TRAIN: ApplicationDriver,
        INFER: ApplicationDriver,
        EVAL: EvaluationApplicationDriver}
    app_driver = driver_table[system_param['SYSTEM'].action]()
    app_driver.initialise_application(system_param, input_data_param)
    app_driver.run(app_driver.app)

    if tf.get_default_session() is not None:
        tf.get_default_session().close()
    tf.reset_default_graph()
    close_logger()

    return 0


text:
namespace webkit_database {

const base::FilePath::CharType kDatabaseDirectoryName[] =
    FILE_PATH_LITERAL("databases");
const base::FilePath::CharType kIncognitoDatabaseDirectoryName[] =
    FILE_PATH_LITERAL("databases-incognito");
const base::FilePath::CharType kTrackerDatabaseFileName[] =
    FILE_PATH_LITERAL("Databases.db");
static const int kCurrentVersion = 2;
static const int kCompatibleVersion = 1;

const base::FilePath::CharType kTemporaryDirectoryPrefix[] =
    FILE_PATH_LITERAL("DeleteMe");
const base::FilePath::CharType kTemporaryDirectoryPattern[] =
    FILE_PATH_LITERAL("DeleteMe*");

OriginInfo::OriginInfo()
    : total_size_(0) {}

OriginInfo::OriginInfo(const OriginInfo& origin_info)
    : origin_(origin_info.origin_),
      total_size_(origin_info.total_size_),
      database_info_(origin_info.database_info_) {}

OriginInfo::~OriginInfo() {}

void OriginInfo::GetAllDatabaseNames(std::vector<string16>* databases) const {
  for (DatabaseInfoMap::const_iterator it = database_info_.begin();
       it != database_info_.end(); it++) {
    databases->push_back(it->first);
  }
}

int64 OriginInfo::GetDatabaseSize(const string16& database_name) const {
  DatabaseInfoMap::const_iterator it = database_info_.find(database_name);
  if (it != database_info_.end())
    return it->second.first;
  return 0;
}

string16 OriginInfo::GetDatabaseDescription(
    const string16& database_name) const {
  DatabaseInfoMap::const_iterator it = database_info_.find(database_name);
  if (it != database_info_.end())
    return it->second.second;
  return string16();
}

OriginInfo::OriginInfo(const string16& origin, int64 total_size)
    : origin_(origin), total_size_(total_size) {}

DatabaseTracker::DatabaseTracker(
    const base::FilePath& profile_path,
    bool is_incognito,
    quota::SpecialStoragePolicy* special_storage_policy,
    quota::QuotaManagerProxy* quota_manager_proxy,
    base::MessageLoopProxy* db_tracker_thread)
    : is_initialized_(false),
      is_incognito_(is_incognito),
      force_keep_session_state_(false),
      shutting_down_(false),
      profile_path_(profile_path),
      db_dir_(is_incognito_ ?
              profile_path_.Append(kIncognitoDatabaseDirectoryName) :
              profile_path_.Append(kDatabaseDirectoryName)),
      db_(new sql::Connection()),
      databases_table_(NULL),
      meta_table_(NULL),
      special_storage_policy_(special_storage_policy),
      quota_manager_proxy_(quota_manager_proxy),
      db_tracker_thread_(db_tracker_thread),
      incognito_origin_directories_generator_(0) {
  if (quota_manager_proxy) {
    quota_manager_proxy->RegisterClient(
        new DatabaseQuotaClient(db_tracker_thread, this));
  }
}

DatabaseTracker::~DatabaseTracker() {
  DCHECK(dbs_to_be_deleted_.empty());
  DCHECK(deletion_callbacks_.empty());
}

void DatabaseTracker::DatabaseOpened(const string16& origin_identifier,
                                     const string16& database_name,
                                     const string16& database_description,
                                     int64 estimated_size,
                                     int64* database_size) {
  if (shutting_down_ || !LazyInit()) {
    *database_size = 0;
    return;
  }

  if (quota_manager_proxy_)
    quota_manager_proxy_->NotifyStorageAccessed(
        quota::QuotaClient::kDatabase,
        DatabaseUtil::GetOriginFromIdentifier(origin_identifier),
        quota::kStorageTypeTemporary);

  InsertOrUpdateDatabaseDetails(origin_identifier, database_name,
                                database_description, estimated_size);
  if (database_connections_.AddConnection(origin_identifier, database_name)) {
    *database_size = SeedOpenDatabaseInfo(origin_identifier,
                                          database_name,
                                          database_description);
    return;
  }
  *database_size  = UpdateOpenDatabaseInfoAndNotify(origin_identifier,
                                                    database_name,
                                                    &database_description);
}

void DatabaseTracker::DatabaseModified(const string16& origin_identifier,
                                       const string16& database_name) {
  if (!LazyInit())
    return;
  UpdateOpenDatabaseSizeAndNotify(origin_identifier, database_name);
}

void DatabaseTracker::DatabaseClosed(const string16& origin_identifier,
                                     const string16& database_name) {
  if (database_connections_.IsEmpty()) {
    DCHECK(!is_initialized_);
    return;
  }

  // We call NotifiyStorageAccessed when a db is opened and also when
  // closed because we don't call it for read while open.
  if (quota_manager_proxy_)
    quota_manager_proxy_->NotifyStorageAccessed(
        quota::QuotaClient::kDatabase,
        DatabaseUtil::GetOriginFromIdentifier(origin_identifier),
        quota::kStorageTypeTemporary);

  UpdateOpenDatabaseSizeAndNotify(origin_identifier, database_name);
  if (database_connections_.RemoveConnection(origin_identifier, database_name))
    DeleteDatabaseIfNeeded(origin_identifier, database_name);
}

void DatabaseTracker::HandleSqliteError(
    const string16& origin_identifier,
    const string16& database_name,
    int error) {
  // We only handle errors that indicate corruption and we
  // do so with a heavy hand, we delete it. Any renderers/workers
  // with this database open will receive a message to close it
  // immediately, once all have closed, the files will be deleted.
  // In the interim, all attempts to open a new connection to that
  // database will fail.
  // Note: the client-side filters out all but these two errors as
  // a small optimization, see WebDatabaseObserverImpl::HandleSqliteError.
  if (error == SQLITE_CORRUPT || error == SQLITE_NOTADB) {
    DeleteDatabase(origin_identifier, database_name,
                   net::CompletionCallback());
  }
}

void DatabaseTracker::CloseDatabases(const DatabaseConnections& connections) {
  if (database_connections_.IsEmpty()) {
    DCHECK(!is_initialized_ || connections.IsEmpty());
    return;
  }

  // When being closed by this route, there's a chance that
  // the tracker missed some DatabseModified calls. This method is used
  // when a renderer crashes to cleanup its open resources.
  // We need to examine what we have in connections for the
  // size of each open databases and notify any differences between the
  // actual file sizes now.
  std::vector<std::pair<string16, string16> > open_dbs;
  connections.ListConnections(&open_dbs);
  for (std::vector<std::pair<string16, string16> >::iterator it =
           open_dbs.begin(); it != open_dbs.end(); ++it)
    UpdateOpenDatabaseSizeAndNotify(it->first, it->second);

  std::vector<std::pair<string16, string16> > closed_dbs;
  database_connections_.RemoveConnections(connections, &closed_dbs);
  for (std::vector<std::pair<string16, string16> >::iterator it =
           closed_dbs.begin(); it != closed_dbs.end(); ++it) {
    DeleteDatabaseIfNeeded(it->first, it->second);
  }
}

void DatabaseTracker::DeleteDatabaseIfNeeded(const string16& origin_identifier,
                                             const string16& database_name) {
  DCHECK(!database_connections_.IsDatabaseOpened(origin_identifier,
                                                 database_name));
  if (IsDatabaseScheduledForDeletion(origin_identifier, database_name)) {
    DeleteClosedDatabase(origin_identifier, database_name);
    dbs_to_be_deleted_[origin_identifier].erase(database_name);
    if (dbs_to_be_deleted_[origin_identifier].empty())
      dbs_to_be_deleted_.erase(origin_identifier);

    PendingDeletionCallbacks::iterator callback = deletion_callbacks_.begin();
    while (callback != deletion_callbacks_.end()) {
      DatabaseSet::iterator found_origin =
          callback->second.find(origin_identifier);
      if (found_origin != callback->second.end()) {
        std::set<string16>& databases = found_origin->second;
        databases.erase(database_name);
        if (databases.empty()) {
          callback->second.erase(found_origin);
          if (callback->second.empty()) {
            net::CompletionCallback cb = callback->first;
            cb.Run(net::OK);
            callback = deletion_callbacks_.erase(callback);
            continue;
          }
        }
      }

      ++callback;
    }
  }
}

void DatabaseTracker::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void DatabaseTracker::RemoveObserver(Observer* observer) {
  // When we remove a listener, we do not know which cached information
  // is still needed and which information can be discarded. So we just
  // clear all caches and re-populate them as needed.
  observers_.RemoveObserver(observer);
  ClearAllCachedOriginInfo();
}

void DatabaseTracker::CloseTrackerDatabaseAndClearCaches() {
  ClearAllCachedOriginInfo();

  if (!is_incognito_) {
    meta_table_.reset(NULL);
    databases_table_.reset(NULL);
    db_->Close();
    is_initialized_ = false;
  }
}

string16 DatabaseTracker::GetOriginDirectory(
    const string16& origin_identifier) {
  if (!is_incognito_)
    return origin_identifier;

  OriginDirectoriesMap::const_iterator it =
      incognito_origin_directories_.find(origin_identifier);
  if (it != incognito_origin_directories_.end())
    return it->second;

  string16 origin_directory =
      base::IntToString16(incognito_origin_directories_generator_++);
  incognito_origin_directories_[origin_identifier] = origin_directory;
  return origin_directory;
}

base::FilePath DatabaseTracker::GetFullDBFilePath(
    const string16& origin_identifier,
    const string16& database_name) {
  DCHECK(!origin_identifier.empty());
  if (!LazyInit())
    return base::FilePath();

  int64 id = databases_table_->GetDatabaseID(
      origin_identifier, database_name);
  if (id < 0)
    return base::FilePath();

  base::FilePath file_name = base::FilePath::FromWStringHack(
      UTF8ToWide(base::Int64ToString(id)));
  return db_dir_.Append(base::FilePath::FromWStringHack(
      UTF16ToWide(GetOriginDirectory(origin_identifier)))).Append(file_name);
}

bool DatabaseTracker::GetOriginInfo(const string16& origin_identifier,
                                    OriginInfo* info) {
  DCHECK(info);
  CachedOriginInfo* cached_info = GetCachedOriginInfo(origin_identifier);
  if (!cached_info)
    return false;
  *info = OriginInfo(*cached_info);
  return true;
}

bool DatabaseTracker::GetAllOriginIdentifiers(
    std::vector<string16>* origin_identifiers) {
  DCHECK(origin_identifiers);
  DCHECK(origin_identifiers->empty());
  if (!LazyInit())
    return false;
  return databases_table_->GetAllOrigins(origin_identifiers);
}

bool DatabaseTracker::GetAllOriginsInfo(std::vector<OriginInfo>* origins_info) {
  DCHECK(origins_info);
  DCHECK(origins_info->empty());

  std::vector<string16> origins;
  if (!GetAllOriginIdentifiers(&origins))
    return false;

  for (std::vector<string16>::const_iterator it = origins.begin();
       it != origins.end(); it++) {
    CachedOriginInfo* origin_info = GetCachedOriginInfo(*it);
    if (!origin_info) {
      // Restore 'origins_info' to its initial state.
      origins_info->clear();
      return false;
    }
    origins_info->push_back(OriginInfo(*origin_info));
  }

  return true;
}

bool DatabaseTracker::DeleteClosedDatabase(const string16& origin_identifier,
                                           const string16& database_name) {
  if (!LazyInit())
    return false;

  // Check if the database is opened by any renderer.
  if (database_connections_.IsDatabaseOpened(origin_identifier, database_name))
    return false;

  int64 db_file_size = quota_manager_proxy_ ?
      GetDBFileSize(origin_identifier, database_name) : 0;

  // Try to delete the file on the hard drive.
  base::FilePath db_file = GetFullDBFilePath(origin_identifier, database_name);
  if (file_util::PathExists(db_file) && !file_util::Delete(db_file, false))
    return false;

  // Also delete any orphaned journal file.
  DCHECK(db_file.Extension().empty());
  file_util::Delete(db_file.InsertBeforeExtensionASCII(
      DatabaseUtil::kJournalFileSuffix), false);

  if (quota_manager_proxy_ && db_file_size)
    quota_manager_proxy_->NotifyStorageModified(
        quota::QuotaClient::kDatabase,
        DatabaseUtil::GetOriginFromIdentifier(origin_identifier),
        quota::kStorageTypeTemporary,
        -db_file_size);

  // Clean up the main database and invalidate the cached record.
  databases_table_->DeleteDatabaseDetails(origin_identifier, database_name);
  origins_info_map_.erase(origin_identifier);

  std::vector<DatabaseDetails> details;
  if (databases_table_->GetAllDatabaseDetailsForOrigin(
          origin_identifier, &details) && details.empty()) {
    // Try to delete the origin in case this was the last database.
    DeleteOrigin(origin_identifier, false);
  }
  return true;
}

bool DatabaseTracker::DeleteOrigin(const string16& origin_identifier,
                                   bool force) {
  if (!LazyInit())
    return false;

  // Check if any database in this origin is opened by any renderer.
  if (database_connections_.IsOriginUsed(origin_identifier) && !force)
    return false;

  int64 deleted_size = 0;
  if (quota_manager_proxy_) {
    CachedOriginInfo* origin_info = GetCachedOriginInfo(origin_identifier);
    if (origin_info)
      deleted_size = origin_info->TotalSize();
  }

  origins_info_map_.erase(origin_identifier);
  base::FilePath origin_dir = db_dir_.Append(base::FilePath::FromWStringHack(
      UTF16ToWide(origin_identifier)));

  // Create a temporary directory to move possibly still existing databases to,
  // as we can't delete the origin directory on windows if it contains opened
  // files.
  base::FilePath new_origin_dir;
  file_util::CreateTemporaryDirInDir(db_dir_,
                                     kTemporaryDirectoryPrefix,
                                     &new_origin_dir);
  file_util::FileEnumerator databases(
      origin_dir,
      false,
      file_util::FileEnumerator::FILES);
  for (base::FilePath database = databases.Next(); !database.empty();
       database = databases.Next()) {
    base::FilePath new_file = new_origin_dir.Append(database.BaseName());
    file_util::Move(database, new_file);
  }
  file_util::Delete(origin_dir, true);
  file_util::Delete(new_origin_dir, true); // might fail on windows.

  databases_table_->DeleteOrigin(origin_identifier);

  if (quota_manager_proxy_ && deleted_size) {
    quota_manager_proxy_->NotifyStorageModified(
        quota::QuotaClient::kDatabase,
        DatabaseUtil::GetOriginFromIdentifier(origin_identifier),
        quota::kStorageTypeTemporary,
        -deleted_size);
  }

  return true;
}

bool DatabaseTracker::IsDatabaseScheduledForDeletion(
    const string16& origin_identifier,
    const string16& database_name) {
  DatabaseSet::iterator it = dbs_to_be_deleted_.find(origin_identifier);
  if (it == dbs_to_be_deleted_.end())
    return false;

  std::set<string16>& databases = it->second;
  return (databases.find(database_name) != databases.end());
}

bool DatabaseTracker::LazyInit() {
  if (!is_initialized_ && !shutting_down_) {
    DCHECK(!db_->is_open());
    DCHECK(!databases_table_.get());
    DCHECK(!meta_table_.get());

    // If there are left-over directories from failed deletion attempts, clean
    // them up.
    if (file_util::DirectoryExists(db_dir_)) {
      file_util::FileEnumerator directories(
          db_dir_,
          false,
          file_util::FileEnumerator::DIRECTORIES,
          kTemporaryDirectoryPattern);
      for (base::FilePath directory = directories.Next(); !directory.empty();
           directory = directories.Next()) {
        file_util::Delete(directory, true);
      }
    }

    // If the tracker database exists, but it's corrupt or doesn't
    // have a meta table, delete the database directory.
    const base::FilePath kTrackerDatabaseFullPath =
        db_dir_.Append(base::FilePath(kTrackerDatabaseFileName));
    if (file_util::DirectoryExists(db_dir_) &&
        file_util::PathExists(kTrackerDatabaseFullPath) &&
        (!db_->Open(kTrackerDatabaseFullPath) ||
         !sql::MetaTable::DoesTableExist(db_.get()))) {
      db_->Close();
      if (!file_util::Delete(db_dir_, true))
        return false;
    }

    db_->set_error_histogram_name("Sqlite.DatabaseTracker.Error");

    databases_table_.reset(new DatabasesTable(db_.get()));
    meta_table_.reset(new sql::MetaTable());

    is_initialized_ =
        file_util::CreateDirectory(db_dir_) &&
        (db_->is_open() ||
         (is_incognito_ ? db_->OpenInMemory() :
          db_->Open(kTrackerDatabaseFullPath))) &&
        UpgradeToCurrentVersion();
    if (!is_initialized_) {
      databases_table_.reset(NULL);
      meta_table_.reset(NULL);
      db_->Close();
    }
  }
  return is_initialized_;
}

bool DatabaseTracker::UpgradeToCurrentVersion() {
  sql::Transaction transaction(db_.get());
  if (!transaction.Begin() ||
      !meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion) ||
      (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) ||
      !databases_table_->Init())
    return false;

  if (meta_table_->GetVersionNumber() < kCurrentVersion)
    meta_table_->SetVersionNumber(kCurrentVersion);

  return transaction.Commit();
}

void DatabaseTracker::InsertOrUpdateDatabaseDetails(
    const string16& origin_identifier,
    const string16& database_name,
    const string16& database_description,
    int64 estimated_size) {
  DatabaseDetails details;
  if (!databases_table_->GetDatabaseDetails(
          origin_identifier, database_name, &details)) {
    details.origin_identifier = origin_identifier;
    details.database_name = database_name;
    details.description = database_description;
    details.estimated_size = estimated_size;
    databases_table_->InsertDatabaseDetails(details);
  } else if ((details.description != database_description) ||
             (details.estimated_size != estimated_size)) {
    details.description = database_description;
    details.estimated_size = estimated_size;
    databases_table_->UpdateDatabaseDetails(details);
  }
}

void DatabaseTracker::ClearAllCachedOriginInfo() {
  origins_info_map_.clear();
}

DatabaseTracker::CachedOriginInfo* DatabaseTracker::MaybeGetCachedOriginInfo(
    const string16& origin_identifier, bool create_if_needed) {
  if (!LazyInit())
    return NULL;

  // Populate the cache with data for this origin if needed.
  if (origins_info_map_.find(origin_identifier) == origins_info_map_.end()) {
    if (!create_if_needed)
      return NULL;

    std::vector<DatabaseDetails> details;
    if (!databases_table_->GetAllDatabaseDetailsForOrigin(
            origin_identifier, &details)) {
      return NULL;
    }

    CachedOriginInfo& origin_info = origins_info_map_[origin_identifier];
    origin_info.SetOrigin(origin_identifier);
    for (std::vector<DatabaseDetails>::const_iterator it = details.begin();
         it != details.end(); it++) {
      int64 db_file_size;
      if (database_connections_.IsDatabaseOpened(
              origin_identifier, it->database_name)) {
        db_file_size = database_connections_.GetOpenDatabaseSize(
            origin_identifier, it->database_name);
      } else {
        db_file_size = GetDBFileSize(origin_identifier, it->database_name);
      }
      origin_info.SetDatabaseSize(it->database_name, db_file_size);
      origin_info.SetDatabaseDescription(it->database_name, it->description);
    }
  }

  return &origins_info_map_[origin_identifier];
}

int64 DatabaseTracker::GetDBFileSize(const string16& origin_identifier,
                                     const string16& database_name) {
  base::FilePath db_file_name = GetFullDBFilePath(origin_identifier,
                                                  database_name);
  int64 db_file_size = 0;
  if (!file_util::GetFileSize(db_file_name, &db_file_size))
    db_file_size = 0;
  return db_file_size;
}

int64 DatabaseTracker::SeedOpenDatabaseInfo(
    const string16& origin_id, const string16& name,
    const string16& description) {
  DCHECK(database_connections_.IsDatabaseOpened(origin_id, name));
  int64 size = GetDBFileSize(origin_id, name);
  database_connections_.SetOpenDatabaseSize(origin_id, name,  size);
  CachedOriginInfo* info = MaybeGetCachedOriginInfo(origin_id, false);
  if (info) {
    info->SetDatabaseSize(name, size);
    info->SetDatabaseDescription(name, description);
  }
  return size;
}

int64 DatabaseTracker::UpdateOpenDatabaseInfoAndNotify(
    const string16& origin_id, const string16& name,
    const string16* opt_description) {
  DCHECK(database_connections_.IsDatabaseOpened(origin_id, name));
  int64 new_size = GetDBFileSize(origin_id, name);
  int64 old_size = database_connections_.GetOpenDatabaseSize(origin_id, name);
  CachedOriginInfo* info = MaybeGetCachedOriginInfo(origin_id, false);
  if (info && opt_description)
    info->SetDatabaseDescription(name, *opt_description);
  if (old_size != new_size) {
    database_connections_.SetOpenDatabaseSize(origin_id, name, new_size);
    if (info)
      info->SetDatabaseSize(name, new_size);
    if (quota_manager_proxy_)
      quota_manager_proxy_->NotifyStorageModified(
          quota::QuotaClient::kDatabase,
          DatabaseUtil::GetOriginFromIdentifier(origin_id),
          quota::kStorageTypeTemporary,
          new_size - old_size);
    FOR_EACH_OBSERVER(Observer, observers_, OnDatabaseSizeChanged(
        origin_id, name, new_size));
  }
  return new_size;
}

void DatabaseTracker::ScheduleDatabaseForDeletion(
    const string16& origin_identifier,
    const string16& database_name) {
  DCHECK(database_connections_.IsDatabaseOpened(origin_identifier,
                                                database_name));
  dbs_to_be_deleted_[origin_identifier].insert(database_name);
  FOR_EACH_OBSERVER(Observer, observers_, OnDatabaseScheduledForDeletion(
      origin_identifier, database_name));
}

void DatabaseTracker::ScheduleDatabasesForDeletion(
    const DatabaseSet& databases,
    const net::CompletionCallback& callback) {
  DCHECK(!databases.empty());

  if (!callback.is_null())
    deletion_callbacks_.push_back(std::make_pair(callback, databases));
  for (DatabaseSet::const_iterator ori = databases.begin();
       ori != databases.end(); ++ori) {
    for (std::set<string16>::const_iterator db = ori->second.begin();
         db != ori->second.end(); ++db)
      ScheduleDatabaseForDeletion(ori->first, *db);
  }
}

int DatabaseTracker::DeleteDatabase(const string16& origin_identifier,
                                    const string16& database_name,
                                    const net::CompletionCallback& callback) {
  if (!LazyInit())
    return net::ERR_FAILED;

  if (database_connections_.IsDatabaseOpened(origin_identifier,
                                             database_name)) {
    if (!callback.is_null()) {
      DatabaseSet set;
      set[origin_identifier].insert(database_name);
      deletion_callbacks_.push_back(std::make_pair(callback, set));
    }
    ScheduleDatabaseForDeletion(origin_identifier, database_name);
    return net::ERR_IO_PENDING;
  }
  DeleteClosedDatabase(origin_identifier, database_name);
  return net::OK;
}

int DatabaseTracker::DeleteDataModifiedSince(
    const base::Time& cutoff,
    const net::CompletionCallback& callback) {
  if (!LazyInit())
    return net::ERR_FAILED;

  DatabaseSet to_be_deleted;

  std::vector<string16> origins_identifiers;
  if (!databases_table_->GetAllOrigins(&origins_identifiers))
    return net::ERR_FAILED;
  int rv = net::OK;
  for (std::vector<string16>::const_iterator ori = origins_identifiers.begin();
       ori != origins_identifiers.end(); ++ori) {
    if (special_storage_policy_.get() &&
        special_storage_policy_->IsStorageProtected(
            DatabaseUtil::GetOriginFromIdentifier(*ori))) {
      continue;
    }

    std::vector<DatabaseDetails> details;
    if (!databases_table_->GetAllDatabaseDetailsForOrigin(*ori, &details))
      rv = net::ERR_FAILED;
    for (std::vector<DatabaseDetails>::const_iterator db = details.begin();
         db != details.end(); ++db) {
      base::FilePath db_file = GetFullDBFilePath(*ori, db->database_name);
      base::PlatformFileInfo file_info;
      file_util::GetFileInfo(db_file, &file_info);
      if (file_info.last_modified < cutoff)
        continue;

      // Check if the database is opened by any renderer.
      if (database_connections_.IsDatabaseOpened(*ori, db->database_name))
        to_be_deleted[*ori].insert(db->database_name);
      else
        DeleteClosedDatabase(*ori, db->database_name);
    }
  }

  if (rv != net::OK)
    return rv;

  if (!to_be_deleted.empty()) {
    ScheduleDatabasesForDeletion(to_be_deleted, callback);
    return net::ERR_IO_PENDING;
  }
  return net::OK;
}

int DatabaseTracker::DeleteDataForOrigin(
    const string16& origin, const net::CompletionCallback& callback) {
  if (!LazyInit())
    return net::ERR_FAILED;

  DatabaseSet to_be_deleted;

  std::vector<DatabaseDetails> details;
  if (!databases_table_->GetAllDatabaseDetailsForOrigin(origin, &details))
    return net::ERR_FAILED;
  for (std::vector<DatabaseDetails>::const_iterator db = details.begin();
       db != details.end(); ++db) {
    // Check if the database is opened by any renderer.
    if (database_connections_.IsDatabaseOpened(origin, db->database_name))
      to_be_deleted[origin].insert(db->database_name);
    else
      DeleteClosedDatabase(origin, db->database_name);
  }

  if (!to_be_deleted.empty()) {
    ScheduleDatabasesForDeletion(to_be_deleted, callback);
    return net::ERR_IO_PENDING;
  }
  return net::OK;
}

void DatabaseTracker::GetIncognitoFileHandle(
    const string16& vfs_file_name, base::PlatformFile* file_handle) const {
  DCHECK(is_incognito_);
  FileHandlesMap::const_iterator it =
      incognito_file_handles_.find(vfs_file_name);
  if (it != incognito_file_handles_.end())
    *file_handle = it->second;
  else
    *file_handle = base::kInvalidPlatformFileValue;
}

void DatabaseTracker::SaveIncognitoFileHandle(
    const string16& vfs_file_name, const base::PlatformFile& file_handle) {
  DCHECK(is_incognito_);
  DCHECK(incognito_file_handles_.find(vfs_file_name) ==
         incognito_file_handles_.end());
  if (file_handle != base::kInvalidPlatformFileValue)
    incognito_file_handles_[vfs_file_name] = file_handle;
}

bool DatabaseTracker::CloseIncognitoFileHandle(const string16& vfs_file_name) {
  DCHECK(is_incognito_);
  DCHECK(incognito_file_handles_.find(vfs_file_name) !=
         incognito_file_handles_.end());

  bool handle_closed = false;
  FileHandlesMap::iterator it = incognito_file_handles_.find(vfs_file_name);
  if (it != incognito_file_handles_.end()) {
    handle_closed = base::ClosePlatformFile(it->second);
    if (handle_closed)
      incognito_file_handles_.erase(it);
  }
  return handle_closed;
}

bool DatabaseTracker::HasSavedIncognitoFileHandle(
    const string16& vfs_file_name) const {
  return (incognito_file_handles_.find(vfs_file_name) !=
          incognito_file_handles_.end());
}

void DatabaseTracker::DeleteIncognitoDBDirectory() {
  shutting_down_ = true;
  is_initialized_ = false;

  for (FileHandlesMap::iterator it = incognito_file_handles_.begin();
       it != incognito_file_handles_.end(); it++)
    base::ClosePlatformFile(it->second);

  base::FilePath incognito_db_dir =
      profile_path_.Append(kIncognitoDatabaseDirectoryName);
  if (file_util::DirectoryExists(incognito_db_dir))
    file_util::Delete(incognito_db_dir, true);
}

void DatabaseTracker::ClearSessionOnlyOrigins() {
  shutting_down_ = true;

  bool has_session_only_databases =
      special_storage_policy_.get() &&
      special_storage_policy_->HasSessionOnlyOrigins();

  // Clearing only session-only databases, and there are none.
  if (!has_session_only_databases)
    return;

  if (!LazyInit())
    return;

  std::vector<string16> origin_identifiers;
  GetAllOriginIdentifiers(&origin_identifiers);

  for (std::vector<string16>::iterator origin = origin_identifiers.begin();
       origin != origin_identifiers.end(); ++origin) {
    GURL origin_url =
        webkit_database::DatabaseUtil::GetOriginFromIdentifier(*origin);
    if (!special_storage_policy_->IsStorageSessionOnly(origin_url))
      continue;
    if (special_storage_policy_->IsStorageProtected(origin_url))
      continue;
    webkit_database::OriginInfo origin_info;
    std::vector<string16> databases;
    GetOriginInfo(*origin, &origin_info);
    origin_info.GetAllDatabaseNames(&databases);

    for (std::vector<string16>::iterator database = databases.begin();
         database != databases.end(); ++database) {
      base::PlatformFile file_handle = base::CreatePlatformFile(
          GetFullDBFilePath(*origin, *database),
          base::PLATFORM_FILE_OPEN_ALWAYS |
          base::PLATFORM_FILE_SHARE_DELETE |
          base::PLATFORM_FILE_DELETE_ON_CLOSE |
          base::PLATFORM_FILE_READ,
          NULL, NULL);
      base::ClosePlatformFile(file_handle);
    }
    DeleteOrigin(*origin, true);
  }
}

void DatabaseTracker::Shutdown() {
  DCHECK(db_tracker_thread_.get());
  DCHECK(db_tracker_thread_->BelongsToCurrentThread());
  if (shutting_down_) {
    NOTREACHED();
    return;
  }
  if (is_incognito_)
    DeleteIncognitoDBDirectory();
  else if (!force_keep_session_state_)
    ClearSessionOnlyOrigins();
}

void DatabaseTracker::SetForceKeepSessionState() {
  DCHECK(db_tracker_thread_.get());
  if (!db_tracker_thread_->BelongsToCurrentThread()) {
    db_tracker_thread_->PostTask(
        FROM_HERE,
        base::Bind(&DatabaseTracker::SetForceKeepSessionState, this));
    return;
  }
  force_keep_session_state_ = true;
}

}  // namespace webkit_database


text:
class PreviewGLWidget;

class CostFunctionWidget : public QWidget {
  Q_OBJECT

  PreviewGLWidget *m_imagePreview;
  PreviewGLWidget *m_leftImagePreview;

  QSpinBox *m_xDisparitySpin;
  QSpinBox *m_yDisparitySpin;

  QSlider *m_xDisparitySlider;
  QSlider *m_yDisparitySlider;

  QGroupBox *genSettingsBox(QString const& name);
  QHBoxLayout *genXDisparityKnobs();
  QHBoxLayout *genYDisparityKnobs();

public:
  CostFunctionWidget(QWidget *parent = 0);

private slots:
  void imageClicked(int x, int y);
  void recalculateCost();
  void updatePreview();

public slots:
  void updateWidgets();
};
#endif


text:
title:  "Oakridge Primary School"
date:   2018-04-09 14:36:16 +0100
categories: jekyll update
tags: ['JS','PHP','TwitterAPI']
link: "http://www.oakridge.staffs.sch.uk/"
thumb: "/assets/img/oakridge.jpg"
copywright: "© Phenix Digital Ltd"
---


text:
"""@package src.wi.urls.user.network
@author Piotr Wójcik
@date 19.11.2010
"""

from django.conf.urls import patterns, url, include
from django.utils.translation import ugettext_lazy as _

from wi.forms.network import CreateNetworkForm
from wi.utils.decorators import user_permission
from wi.utils.views import direct_to_template, get_list_generic, simple_generic_id, form_generic

resources_patterns = patterns('wi.views.user.network',

    url(r'^networks/$', user_permission(direct_to_template), {'template_name': 'resources/networks.html'}, name='res_networks'),
    url(r'^ajax/network_table/$', user_permission(get_list_generic),
        {'request_url': 'user/network/list_user_networks/'}, name='res_ajax_get_network_table'),
    url(r'^ajax/add_network/$', user_permission(form_generic),
         {'template_name':       'generic/form.html',
         'success_msg':          (lambda desc, data: _('You have successfully added a network') % {'desc': desc}),
         'confirmation':         _('Create'),
         'form_class':           CreateNetworkForm,
         'request_url_post':     'user/network/request/', },
        name='res_ajax_add_network'),
    url(r'^ajax/release_network/(?P<id1>\d+)/$', user_permission(simple_generic_id),
        {'template_name':   'generic/simple.html',
         'success_msg':     (lambda desc: _('You have successfully released network %(desc)s.') % {'desc': desc}),
         'ask_msg':         (lambda desc: _('Do you want to release network %(desc)s?') % {'desc': desc}),
         'request_url':     'user/network/release/',
         'id_key':          'network_id', },
        name='res_ajax_release_network'),
)

urlpatterns = patterns('',
    url(r'^resources/', include(resources_patterns)),
)


text:
<!DOCTYPE html>
<html>
<head>
<script>
function performTest(api)
{
    api.Cursor.makeContainerInsertionPoint();
    api.tests.TestLib.showSelection();
}
</script>
</head>
<body>
Sam[ple te]xt
</body>
</html>


text:
package com.invariantproperties.project.student.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import com.invariantproperties.project.student.domain.Course;

/**
 * Spring Data repository for courses.
 *
 * @author Bear Giles <bgiles@coyotesong.com>
 */
@Repository
public interface CourseRepository extends JpaRepository<Course, Integer>, JpaSpecificationExecutor<Course> {
    Course findCourseByUuid(String uuid);

    Course findCourseByCode(String code);
}


text:
package torpedo_stackoverflow_plugin

import (
	"fmt"
	log "github.com/sirupsen/logrus"

	"github.com/tb0hdan/torpedo_plugins/torpedo_stackoverflow_plugin/stackoverflow"

	"github.com/tb0hdan/torpedo_registry"
	common "github.com/tb0hdan/torpedo_common"
)

func StackOverflowProcessMessage(api *torpedo_registry.BotAPI, channel interface{}, incoming_message string) {
	var message string
	_, command, message := common.GetRequestedFeature(incoming_message)

	if command != "" {
		log.Printf("Got command %s\n", command)
		client := stackoverflow.NewClient("")
		result, err := client.Search(incoming_message)
		if err != nil {
			message = fmt.Sprintf("An error occured during StackOverflow search: %+v\n", err)
		} else {
			message = result
		}
		if message == "" {
			message = "No results for your query"
		}
	}
	api.Bot.PostMessage(channel, message, api)
}

func init() {
	helpmsg := "Search for solution on StackOverflow.com"
	torpedo_registry.Config.RegisterHelpAndHandler("so", helpmsg, StackOverflowProcessMessage)
	torpedo_registry.Config.RegisterHelpAndHandler("stackoverflow", helpmsg, StackOverflowProcessMessage)
}


text:
module Lit
  class LocalizationKey < ActiveRecord::Base
    attr_accessor :interpolated_key

    ## SCOPES
    scope :completed, proc { where(is_completed: true) }
    scope :not_completed, proc { where(is_completed: false) }
    scope :starred, proc { where(is_starred: true) }
    scope :ordered, proc { order('localization_key asc') }
    scope :after, proc { |dt|
      joins(:localizations)
        .where('lit_localization_keys.updated_at >= ?', dt)
        .where('lit_localizations.is_changed = true')
    }

    ## ASSOCIATIONS
    has_many :localizations, dependent: :destroy

    ## VALIDATIONS
    validates :localization_key,
              presence: true,
              uniqueness: { if: :localization_key_changed? }

    unless defined?(::ActionController::StrongParameters)
      ## ACCESSIBLE
      attr_accessible :localization_key
    end

    def to_s
      localization_key
    end

    def clone_localizations
      new_created = false
      Lit::Locale.find_each do |locale|
        localizations.where(locale_id: locale.id).first_or_create do |l|
          l.default_value = interpolated_key
          new_created = true
        end
      end
      if new_created
        Lit::LocalizationKey.update_all ['is_completed=?', false], ['id=? and is_completed=?', id, false]
      end
    end

    def mark_completed
      self.is_completed = localizations.changed.count(:id) == localizations.count
    end

    def mark_completed!
      save if mark_completed
    end

    def mark_all_completed!
      localizations.update_all(['is_changed=?', true])
      mark_completed!
    end

    def self.order_options
      ['localization_key asc', 'localization_key desc', 'created_at asc', 'created_at desc', 'updated_at asc', 'updated_at desc']
    end

    # it can be overridden in parent application, for example: {:order => "created_at desc"}
    def self.default_search_options
      {}
    end

    def self.search(options = {})
      options = options.to_h.reverse_merge(default_search_options).with_indifferent_access
      s = self
      if options[:order] && order_options.include?(options[:order])
        column, order = options[:order].split(' ')
        s = s.order("#{Lit::LocalizationKey.quoted_table_name}.#{connection.quote_column_name(column)} #{order}")
      else
        s = s.ordered
      end
      localization_key_col = Lit::LocalizationKey.arel_table[:localization_key]
      default_value_col = Lit::Localization.arel_table[:default_value]
      translated_value_col = Lit::Localization.arel_table[:translated_value]
      if options[:key_prefix].present?
        q = "#{options[:key_prefix]}%"
        s = s.where(localization_key_col.matches(q))
      end
      if options[:key].present?
        q = "%#{options[:key]}%"
        q_underscore = "%#{options[:key].parameterize.underscore}%"
        cond = localization_key_col.matches(q).or(
            default_value_col.matches(q).or(
                translated_value_col.matches(q)
            )
        ).or(localization_key_col.matches(q_underscore))
        s = s.joins([:localizations]).where(cond)
      end
      unless options[:include_completed].to_i == 1
        s = s.not_completed
      end
      s
    end
  end
end


text:
package fusefrontend_reverse

import (
	"github.com/hanwen/go-fuse/v2/fs"
)

// Check that we have implemented the fs.File* interfaces
var _ = (fs.FileReader)((*File)(nil))
var _ = (fs.FileReleaser)((*File)(nil))
var _ = (fs.FileLseeker)((*File)(nil))

/* Not needed
var _ = (fs.FileGetattrer)((*File)(nil))
var _ = (fs.FileGetlker)((*File)(nil))
var _ = (fs.FileSetlker)((*File)(nil))
var _ = (fs.FileSetlkwer)((*File)(nil))
*/

/* Will not implement these - reverse mode is read-only!
var _ = (fs.FileSetattrer)((*File)(nil))
var _ = (fs.FileWriter)((*File)(nil))
var _ = (fs.FileFsyncer)((*File)(nil))
var _ = (fs.FileFlusher)((*File)(nil))
var _ = (fs.FileAllocater)((*File)(nil))
*/


text:
<?php

class Login_test extends TestCase
{
	public function setUp()
        {
            $this->resetInstance();
            $this->CI->load->model('M_login');
            $this->objek = $this->CI->M_login;
            $this->form_validation = new CI_Form_validation();
        }
         public function test_login(){
            $this->request('POST', 'Login/aksi_login',['username' => 'titis', 'password' => '123admin']);
            $this->assertRedirect('Bayi');
        }

        public function test_login_error(){
            $output = $this->request('POST', 'Login/aksi_login',['username' => 'titis', 'password' => 'salah']);
            $this->assertContains("Username dan password salah !", $output);
        }

        public function test_index() {
            $output = $this->request('GET', 'login');
            $this->assertContains('<title>SIP - Login</title>', $output);
        }

}

?>


text:
var goalslist;
var startTime = 0;
var firstVisit = false;

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {

	$('#submit-btn').click(loginFunction);
	$('#btn-back').click(cancelFunction);
	$('.btn-register').click(goToSignUp);
	$('#makeact-btn').click(signupFunction);
	$('#btn-cancel').click(cancelFunction);
	$('#btn-add').click(addMilestoneFunction);
	$('#btn-menu').click(menuFunction);
	$('#btn-back-homescreen').click(cancelFunction);
	$('.logout').click(logOutFunction);
	$('#add-goal').click(addGoalFunction);
	$('#submit-milestone-btn').click(addMilestonePost);
	//$('#submit-btn').click(cancelFunction);
	console.log('blah');
	addEvents($('.timeline-wrapper'));
	addMilestones($('.milestone-list'));
	addGoals($('#goal-list'));

	if($('.datepicker').length != 0)
		$('.datepicker').datepicker();

	setUpAdders();
	//getMilestones();
})

function addMilestones(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotMilestones);
}

function gotMilestones(result){

	var milestoneList = $('.milestone-list');
	console.log(result);
	var goalname = $('#goal-name-hack').html();
	console.log($('#goal-name-hack').html());
	var goals = result[0]['goals'];
	var realgoal ;
	for(var i = 0 ; i < goals.length; ++i){
		if(goals[i].name == goalname)
			realgoal = goals[i];
	}
	console.log(realgoal);
	for(var i = 0; i < realgoal.milestones.length; ++i){
		milestoneList.append('<button type="button" class="btn btn-default">' + realgoal.milestones[i].name+'</button>')
	}

}

function addGoals(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotGoals);
}

function gotGoals(result){
	console.log(result);

	if($('#mainmenu').length==0){
		var goalList = $('#goal-list');
		console.log(result);
		var goals = result[0]['goals'];
		console.log(goals);
		for(var i = 0; i< goals.length; ++i){
			var string = '
' + goals[i].name +  '
';
			goalList.append(string);
		}
	}
	else{
		var goalList = $('#goal-list');
		console.log(result);
		var goals = result[0]['goals'];
		console.log(goals);
		for(var i = 0; i< goals.length; ++i){
			var string = '
' + goals[i].name +  '
';
			goalList.append(string);
			// $('#'+ goals[i]._id+' a[class = delete]').bind("click", function(e){
			// 	e.preventDefault();
			// 	console.log("clicked");
			// 	console.log( $(this).parent().parent().attr('id'));
			// 	$.post('/delgoal', {id: $(this).parent().attr('id')});
			// 	//window.location.href = '/menu';
			// });
		}
	}
}

function addEvents(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotEvents);
}

function gotEvents(result){
	var today = new Date();

	if(result[0].lastVisited == null || new String(window.location.href).indexOf("homescreen") != -1 &&
		(result[0].lastVisited.getDate() != today.getDate() || result[0].lastVisited.getMonth() == today.getMonth())){
			///$.post('/updatedate', {"newdate:" : today} ,  null);

	}

	goalslist = result[0].goals;
	console.log('goallist');
	console.log(goalslist);

	var pathname = window.location.pathname;

	$('#btn-add').remove();
	if(result[0] == undefined || result[0].goals.length ==0){
		$('.goal-header').remove();
		$('.status1').remove();
		console.log('nothing to show');
		return;
	}
	else{
		$('.help-wrapper').hide();
	}
	console.log(result);
	var goals = result[0]['goals'];

	console.log(goals);

	var colors = getColors(goals.length);
	console.log(colors);
	for(var i = 0; i < goals.length; ++ i){
		goals[i].color = colors[i];
		console.log(goals[i].color);
	}

	var milestones = new Array();

	var goalname = $('#goal-name-hack').html();
	console.log(goalname);
	var realgolnum;
	if(goalname != ''){
		var realgoal ;
		for(var i = 0 ; i < goals.length; ++i){
			if(goals[i].name == goalname){
				realgoal = goals[i];
				realgolnum = i;

				break;
			}
		}
		makeGoalHeader(result, realgolnum);
		var milestonelist = realgoal.milestones;
		for(var j = 0; j <milestonelist.length; ++j){
			milestonelist[j].actualDate = new Date(milestonelist[j]['date']);
			milestonelist[j].goalNum=  realgolnum;
			milestonelist[j].milestoneNum = j;
			milestones.push(milestonelist[j]);
		}
	}
	else{
		makeGoalHeader(result, -1);
		for(var i = 0; i < goals.length; ++i){
			var milestonelist = goals[i]['milestones'];
			for(var j = 0; j <milestonelist.length; ++j){
				milestonelist[j].actualDate = new Date(milestonelist[j]['date']);
				milestonelist[j].goalNum = i;
				milestonelist[j].milestoneNum = j;
				milestones.push(milestonelist[j]);
			}
		}
	}

	milestones.sort(dateComp);

	console.log(milestones);

	var timeline = $('.timeline-wrapper');

	for(var tl = 0; tl < timeline.length; ++tl){
		for(var i = 0; i < milestones.length ; ){
			var date = milestones[i].actualDate;
			if(isNaN(date.getTime())){
				i++;
				continue;
			}

			var dayMilestones = new Array();
			console.log(date);

			var allcomplete = true;
			while(i < milestones.length && milestones[i].actualDate.getTime() == date.getTime()){
				dayMilestones.push(milestones[i]);
				if(!milestones[i].completed)
					allcomplete = false;
				i++;
			}

			//if past and not all complete
			if((date <= Date.now() && !allcomplete) || !($(timeline[tl]).hasClass("modal-timeline"))){
				var string = '
'+ date.toDateString() + '
';
				for(var j = 0; j < dayMilestones.length; ++j){
					if(dayMilestones[j].actualDate > Date.now()){//future
						if(dayMilestones[j].completed){
							string+= '
';
							string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
						}
						else{
							string+= '
';
							string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
						}
					}
					else{//past
						if(dayMilestones[j].completed && !($(timeline[tl]).hasClass("modal-timeline"))){
							string+= '
';
							string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
						}
						else{
							string+= '
';
							string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
						}
					}
					if(!($(timeline[tl]).hasClass("modal-timeline")) || !dayMilestones[j].completed){
					string+=
		                '
Delete' +
		                '    '+
		                //Edit+
		                '

' +
		    			'
  ';
					else
						string +='">  ';
		    		string += dayMilestones[j].name + '
' +
		    			'
';
		    		}
				}
				string = '
' + string  + '
';
				$(timeline[tl]).append(string);
			}

		}
	}
	console.log('styling goaldivs');
	var goalDivs = $('p.event-complete-time');
	for(var i = 0; i < goalDivs.length; ++i){
		var goal;
		for(var j = 0; j < goals.length; ++j){
			console.log($(goalDivs[i]).text());
			if(goals[j].name == $(goalDivs[i]).text()){
				goal = goals[j];
				break;
			}
		}
		console.log(goal.color);
		$(goalDivs[i]).parent().css({"border-left": "4px solid " + goal.color});
	}

	function clickedCheck(e){
		var removing;
		if($(this).hasClass("glyphicon-check")){
			removing = true;
		}
		else
			removing = false;

		var string = $('.num-milestones').text();
		var strarray = string.split(' ');
		var first = parseInt(strarray[0]);
		if(removing)
			first--;
		else
			first++;

		var newstring = "";
		newstring += first;
		for(var i = 1; i < strarray.length; ++i){
			newstring += " " ;
			newstring += strarray[i];
		}

		$('.num-milestones').text(newstring);

		$(this).toggleClass("glyphicon-check");
		$(this).toggleClass("glyphicon-unchecked");
		var id = $(this).parent().attr('id');
		var goalname = $(this).parent().parent().find('p.event-complete-time').text();

		var goalnum= 0;
		for(; goalnum < result[0].goals.length; goalnum++){
			if(result[0].goals[goalnum].name == goalname)
				break;
		}

		var milestonestatus;
		var milestonename;
		var ms;
		for(var i = 0; i < result[0].goals[goalnum].milestones.length; ++i){
			if(result[0].goals[goalnum].milestones[i]._id == id){
				ms = result[0].goals[goalnum].milestones[i];
				milestonestatus = ms.completed;
				milestonename = ms.name;
				break;
			}
		}

		var parentDiv = $(this).parent().parent();
		if(removing){
			if(parentDiv.hasClass('event-past'))
				parentDiv.toggleClass('event-overdue');
			if(parentDiv.hasClass('event-future'))
				parentDiv.toggleClass('event-incomplete');
		}
		else{//checking off
			if(parentDiv.hasClass('event-overdue'))
				parentDiv.toggleClass('event-overdue');
			if(parentDiv.hasClass('event-incomplete'))
				parentDiv.toggleClass('event-incomplete');
		}

		console.log("switching from " + milestonestatus + " to " + !milestonestatus);

		var callback = function(data, status){
			if(status =='success'){
				console.log(data);
				$.get('/data', function(res){
					console.log(res);
					countGoals(res, realgolnum);
				});
			}
		};

		$.post('/milestoneupdate', {'milestonestatus' : !milestonestatus, 'milestonename': milestonename, 'milestoneid':id, 'goalname': goalname}
			, callback);
	};

	$('.glyphicon-check').click(clickedCheck);
	$('.glyphicon-unchecked').click(clickedCheck);

	console.log(milestones);
	setUpDeletersAndEditors();
	if(!$.trim($('.modal-timeline').html()).length){
		$('.modal-title').text("You're on track!");
		$('.modal-body').empty();
	}
}

function dateComp(a,b){
	return new Date(a.actualDate)-new Date(b.actualDate);
}

function getColors(size){
	var colors = new Array();
	for(var i = 0; i < size; ++i){
		colors.push('#'+Math.floor(Math.random()*16777215).toString(16));
	}
	return colors;
}

function countGoals(results, goalnum){
	var smallnum =0;
	var bignum =0;
	var goalname;
	var object = results[0];
	console.log('number is' + goalnum);
	if(goalnum != undefined){
		var goal = object['goals'][goalnum];
		goalname = goal.name;
		for(var i = 0 ; i < goal.milestones.length; ++i)
			if(goal.milestones[i].completed)
				smallnum++;
		bignum = goal.milestones.length;
	}
	else{
		goalname = "All Goals";
		for(var i = 0; i < object['goals'].length; ++i){
			var goal = object['goals'][i];
			for(var j = 0 ; j< goal.milestones.length; ++j)
				if(goal.milestones[j].completed)
					smallnum++;
			bignum += goal.milestones.length
		}
	}

	var percent = smallnum/bignum*100  + "%";
	$("#meter-span").width(percent)
}

function makeGoalHeader(results, goalnum){
	var smallnum =0;
	var bignum =0;
	var goalname, goaldate;
	if(goalnum != -1){
		var goal = results[0]['goals'][goalnum];
		goalname = goal.name;
		goaldate = new Date(goal.completionDate);
		goaldate = ((goaldate.getMonth() + 1) + '/' + goaldate.getDate() + '/' +  goaldate.getFullYear());

		var smallnum = 0;
		for(var i = 0 ; i < goal.milestones.length; ++i)
			if(goal.milestones[i].completed)
				smallnum++;
		bignum = goal.milestones.length;
	}
	else{
		goalname = "All Goals";
		for(var i = 0; i < results[0]['goals'].length; ++i){
			var goal = results[0]['goals'][i];
			goaldate = goal.completionDate;
			for(var j = 0 ; j< goal.milestones.length; ++j)
				if(goal.milestones[j].completed)
					smallnum++;
			bignum += goal.milestones.length
		}
	}

	var string = '

'+goalname+'

';
        if(goalnum!=-1)
            string += 'Finish by ' +  goaldate + '
';

        string += ''+  smallnum + ' of '+ bignum + ' milestones completed'+
           '
'+
                ''+
             '
' +
         '

';

        $(".goal-header").append(string);
}

function loginFunction(e){
	e.preventDefault();
	console.log('loggingin');
	$.post('/', {
		"user": $('#name').val(),
		"pass": $('#password').val(),
		"remember-me": 'true'
	}, function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
}

function signupFunction(e){
	e.preventDefault();
	console.log('signingup');
	$.post('/signup', {
		"name": $('#name').val(),
		"user": $('#username').val(),
		"email" : $('#email').val(),
		"pass": $('#password').val()
	}, function(data, status){
		if(status == 'success'){
			$.post('/', {
				"user": $('#name').val(),
				"pass": $('#password').val(),
				"remember-me": 'true'
			}, function(a, b){
				console.log(a);
				console.log(b);
				window.location.href = "/";
			});
		}
		else{
			alert(status);
			console.log(data);
		}
		window.location.href = "/";
	});
	//window.location.href = "/";
	// $.get('/');
};

function logOutFunction(e){
	e.preventDefault();

	$.post('/logout', {},
		function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
};

function addGoalFunction(e){
	e.preventDefault();

	console.log('clicked');
	console.log( $('#name').val() );
	$.post('/addgoal', {
		"name" : $('#name').val() ,
		"date": $('#date').val()
	},
	function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
	//window.location.href = "/";
};

function addMilestonePost(e){
	e.preventDefault;
	console.log('trying to add milestone');
	console.log($('#goal-name-hack').html());
	$.post('/addmilestonepost', {
		"name" : $('#goalname').val() ,
		"date": $('#complete').val(),
		"goal": $('#goal-name-hack').html()
	}, function(data, status){
		console.log(data);
		console.log(status);
		ga("send", "event", "ms", "add");
		ga('send', 'timing', 'jQuery', 'Milestone1Add', new Date().getTime(), 'Google CDN');
		$.post('/addEvent', {
				"type": 'addmilestone1',
				"val" : new Date().getTime()
			});
		window.location.href = "/";
	});

}

function goToSignUp(e){
	e.preventDefault();
	window.location.href= '/signup';
}

function cancelFunction(e){
	e.preventDefault();
	window.location.href= '/homescreen';
};

function addFunction(e){
	e.preventDefault();
	window.location.href= '/add-goal';
};

function addMilestoneFunction(e){
	e.preventDefault();

	$.post('/setTime', {"startTime": new Date().getTime()}, function(data,status){
		console.log(data);
		console.log(status);
	});
	ga("send", "event", "ms", "startadd");
	ga('send', 'timing', 'jQuery', 'Milestone1Start', new Date().getTime(), 'Google CDN');
	$.post('/addEvent', {
		"type": 'milestone1start',
		"val" : new Date().getTime()
	});

	if($('#goal-name-hack').html()){
		window.location.href= '/add-milestone/' + $('#goal-name-hack').html();
	}
	else
		window.location.href= '/choose-goal';
}

function menuFunction(e){
	e.preventDefault();
	window.location.href= '/menu';
};

function getMilestones(){
	console.log('stuff');
	$.post('/getms', {},
		function(data, status){
	});

	$.post('/addgoal', {},
		function(data, status){
	});
}

function setUpDeletersAndEditors(){
	console.log("asdlfkjasldfjalsdkfjasd");
	$('.milestone-delete').click(deleteMilestone);
	console.log($('.milestone-delete'));
	$('.milestone-edit-omg').click(editMilestone);

	function deleteMilestone(e){
		var date  = $(this).parent().parent().parent().find('.date').text();
		var name = $(this).parent().parent().find('.event-description').text();
		var goal = $(this).parent().parent().find('.event-complete-time').text();

		console.log('deleting' + name + date);

		$.post('/deletemilestonepost', {
			'milestonename':$.trim(name),
			'milestonedate':new Date(date),
			'goalname':$.trim(goal)
		}, function(data,status){
			console.log(status);
			window.location.href = "/";
		});
	}

	function editMilestone(e){
		e.preventDefault();

		var date = $(this).parent().parent().parent().find('.date').text();
		var name = $(this).parent().parent().find('.event-description').text();
		var goal = $(this).parent().parent().find('.event-complete-time').text();

		console.log('starting to edit' + name  + "  " + data );

	}
}

function setUpAdders(){

	$('.add-event').click(goForward);

	function fillWithEvent1(e){
		var parent = $(e);
		parent.toggleClass("status1");
		parent.toggleClass("status2");
		parent.html('
Add New Milestone
');
		parent.unbind();
		parent.removeClass("status2");
		parent.removeClass("status3");
		parent.addClass("status1");
		parent.click(goForward);
	};

	function fillWithEvent2(e){
		var div = $(e);
		console.log('fwe2');
		if(getGoalName() != ""){
			fillWithEvent3(e);
			return;
		}

		var newdata = '
' +
            ''+
            'Pick a goal to add a milestone to:'+
            ''+
        '
'+
        '
'+
        '<select id = "goalselect">';
        for(var i = 0 ; i < goalslist.length; ++i){
        	newdata += '<option>' + goalslist[i].name + '</option>';
        }
       	// getGoalsOptions();
        newdata+='</select>';
		div.html(newdata);
		div.removeClass("status1");
		div.removeClass("status3");
		div.addClass("status2");
		div.unbind();
		div.children('.add-event-header').children('.btn-left-mini').click(goBack);
		div.children('.add-event-header').children('.btn-right-mini').click(goForward);
		console.log('event2');
	};

	function fillWithEvent3(e){
		var div = $(e);

		var goalname = getGoalName();
		if(goalname == ""){
			goalname = div.children('.select').children('#goalselect').children('option:selected').text();
		}
		console.log(goalname);

		var newdata =  '
' +
            ''+
            'Add Milestone for '+ goalname +
            ''+
        	'
'+
        '
'+
            '<input type="text" class="form-control" id="name" placeholder="Milestone description" name="name">'+
            '<input type="text" class="form-control datepicker" readonly="true" id="date" placeholder="Due date" name="password">'+
        '
';

        console.log(div.html());
        div.html(newdata);
        $('.datepicker').datepicker();
        div.removeClass('status1 status2');
        div.addClass('status3');
        div.unbind();
        div.children('.add-event-header').children('.btn-left-mini').click(goBack);
		div.children('.add-event-header').children('.btn-right-mini').click(goForward);
	};

	function submitThis(e){
		var div = $(e);
		console.log('trying to add milestone');
		console.log({
			"name" :  $('#name').val(),
			"date": $('#date').val(),
			"goal": $('.add-event-header').attr('id')
		});
		$.post('/addmilestonepost', {
			"name" :  $('#name').val(),
			"date": $('#date').val(),
			"goal": $('.add-event-header').attr('id')
		}, function(data, status){
			console.log(data);
			console.log(status);
			var endTime = new Date().getTime();
			console.log(endTime);
			ga("send", "event", "ms", "add2");
			ga('send', 'timing', 'jQuery', 'addMilestone2', endTime-startTime, 'Google CDN');
			$.post('/addEvent', {
				"type": 'addmilestone2',
				"val" : endTime-startTime
			});
			//alert(endTime-startTime);
			window.location.href = window.location;
		});
	}

	function goForward(e){
		if($(this).hasClass('status1') &&  getGoalName() == ""){
			startTime= new Date().getTime();
			fillWithEvent2($(this));
			return false;
		}
		else if($(this).hasClass('status1') &&  getGoalName() != ""){
			fillWithEvent3($(this));
			return false;
		}

		console.log('forwarding');
		if($(this).parent().parent().hasClass('status2')){
			console.log('front3');
			fillWithEvent3($(this).parent().parent());
			return false;
		}
		else if($(this).parent().parent().hasClass('status3')){
			console.log('front,add,back1');
			submitThis($(this).parent().parent());
			//window.location.href = "/homescreen";
			//fillWithEvent1($(this).parent().parent());
			return false;
		}
	};

	function goBack(e){
		console.log('backing');
		if($(this).parent().parent().hasClass('status2') || getGoalName() != ""){
			console.log('back1');
			fillWithEvent1($(this).parent().parent());
			return false;
		}
		else if($(this).parent().parent().hasClass('status3')){
			console.log('back2');
			fillWithEvent2($(this).parent().parent());
			return false;
		}
	};
}

function getGoalName(){
	return $("#goal-name-hack").text();
}


text:
testpath(f) = joinpath(dirname(@__FILE__), f)

for test_file in [
  "base.jl",
  "events.jl",
  "operators.jl",
  "simulations.jl",
  "processes.jl",
  "resources/containers.jl",
  "resources/stores.jl",
  "utils/time.jl",
  ]
  include(testpath(test_file))
end


text:
$(function(){

	//轮播图
	jQuery(".bigImages").slide({mainCell:".bd ul",autoPlay:true,effect:"left",interTime:4500});

	//中医文化
	jQuery(".wenhua").slide({mainCell:".bd ul",autoPlay:true,effect:"leftMarquee",vis:5,interTime:50});

	//中医名家
	jQuery(".mingjia").slide({titCell:".hd ul",mainCell:".bd ul",autoPage:true,effect:"left",autoPlay:true,vis:2,trigger:"click"});

	//友情链接
	jQuery(".firendlink").slide({titCell:".hd ul",mainCell:".bd ul",autoPage:true,effect:"left",autoPlay:true,vis:6,trigger:"click"});

	//导航栏
	$('.menu li').hover(function(){
		$(this).find('>ul').stop().fadeIn(200)
		$(this).parents('li').find('>a').addClass('current')
	},function(){
		$(this).find('>ul').fadeOut(100);
		$(this).parents('li').find('a').removeClass('current')

	})

	//news tab
	$(".news-tab li").click(function(){
			$(this).addClass("on").siblings().removeClass("on");
			 var index = $(".news-tab li").index($(this));
				$(".news-main>ul:eq("+index+")").fadeIn().siblings().hide();
	});

})

//加入收藏夹
function AddFvtgc() {
 var title = document.title;
 var url = document.location.href;
 try {
  window.external.AddFavorite(url, title);
 }
 catch (e) {
  alert("请按下 Ctrl + D 键将本站加入收藏。");
 }
}

//设为首页
function AddHomegc() {
 var url = document.location.href; if (document.all)
 { document.body.style.behavior = 'url(#default#homepage)'; document.body.setHomePage(url); }
 else if (window.sidebar) {
  if (window.netscape) {
   try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); }
   catch (e)
   { alert("此操作被浏览器拒绝!\n请在浏览器地址栏输入"about:config"并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'"); }
  }
  //var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
  //prefs.setCharPref('browser.startup.homepage', url);
 }
 else {
  alert('您的浏览器不支持自动自动设置首页, 请使用浏览器菜单手动设置!');
 }
}

//获取当前时间
GetCurTime();
function GetCurTime() {
    webtime = document.getElementById('jnkc');
    webtime.innerHTML = new Date().getFullYear() + '年' + eval(new Date().getMonth() + 1) + '月' + new Date().getDate() + '日' + ' 星期' + '日一二三四五六'.charAt(new Date().getDay()) + ' ' ;
}


text:
using System;
using System.Runtime.InteropServices;
using Nohros.Extensions.Time;

namespace Nohros.Aion
{
  internal static class Environment
  {
    [StructLayout(LayoutKind.Sequential)]
    struct LastInputInfo
    {
      public static readonly int SizeOf = Marshal.SizeOf(typeof (LastInputInfo));

      [MarshalAs(UnmanagedType.U4)] public UInt32 cbSize;
      [MarshalAs(UnmanagedType.U4)] public UInt32 dwTime;
    }

    [DllImport("user32.dll")]
    static extern bool GetLastInputInfo(ref LastInputInfo plii);

    /// <summary>
    /// Gets time in seconds since the last user input.
    /// </summary>
    /// <returns>
    /// The time in seconds since the last user input.
    /// </returns>
    public static IdleTimeInfo GetSystemIdleTime() {
      var last_input_info = new LastInputInfo();
      last_input_info.cbSize = (uint) Marshal.SizeOf(last_input_info);
      last_input_info.dwTime = 0;

      uint last_input_tick = 0;
      var env_ticks = (uint) System.Environment.TickCount;
      if (GetLastInputInfo(ref last_input_info)) {
        last_input_tick = last_input_info.dwTime;
      }
      return new IdleTimeInfo {
        Timestamp = DateTime.Now.ToUnixEpoch(),
        LastInputTime = last_input_tick,
        MachineUpTime = env_ticks
      };
    }
  }
}