text:
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/nu7hatch/gouuid"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

//curl -H "Content-Type: application/json" -XPUT -d '{"P"}' -f -v http://localhost:3000/beacon/{id}

const (
	dbName = "artroomServer"
	//DBURI for the mongodb
	DBURI = "127.0.0.1"

	waltersAPIPrefix    = "http://api.thewalters.org/v1/objects?apikey=ShxvahaBFNIcfWR7E78xXdssKIlXtUAJk9rDDrrmlvbOlxQKtASCzV4op5aHv2Il&title="
	waltersImagePrefix  = "http://static.thewalters.org/images/"
	waltersImagePostfix = "?width=500"
	moxtraAPI           = "https://api.moxtra.com/oauth/token?client_id="             //client-id
	moxtraCS            = "&client_secret="                                           //CLIENT-SECRET
	moxtraGrantType     = "&grant_type=http://www.moxtra.com/auth_uniqueid&uniqueid=" //UNIQUE-ID
	moxtraTS            = "&timestamp="                                               //TIMESTAMP
	moxtraSig           = "&signature="                                               //SIGNATURE
	moxtraClientID      = "u-DTusZ0ruc"
)

var (
	s = Server{}
	//CollectionNames is the shiz
	CollectionNames = []string{"beacon", "art"}
	beaconIndex     = mgo.Index{
		Key:        []string{"MinorID"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
		Name:       "beaconIndex",
		//ExpireAf
	}

	artIndex = mgo.Index{
		Key:        []string{"Beacon", "Title"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
		Name:       "ArtIndex",
		//ExpireAf
	}
	indices            = []mgo.Index{beaconIndex, artIndex}
	moxtraTimeStamp    string
	moxtraSignature    []byte
	moxtraClientSecret = []byte("vWLjlkGMZOk")
)

type (
	//Server is the name for the server deal wit it
	Server struct {
		Session     *mgo.Session // The main session we'll we be cloning
		DBURI       string       // Where the DB is on the network
		dbName      string       // Name of the MongoDB
		MoxtraToken MoxtraToken
	}

	//Beacon is the struct that structures what the data for a beacon will look like
	Beacon struct {
		ProxID  string
		MajorID int
		MinorID int
	}
	//FormResponse is what we get back from the form
	FormResponse struct {
		Date        string
		Author      string
		Title       string
		ProxID      string
		MajorID     int
		MinorID     int
		Description string
	}

	//The structure the walter api gives us more or less
	WalterObj struct {
		ObjectID       int
		BinderID       string
		Collection     string
		Title          string
		Author         string
		Medium         string
		Description    string
		Images         string
		CuratorComment string
		Beacon         Beacon
		ImageURL       string
	}
	//Walters objects
	Walters struct {
		Items []WalterObj
	}

	//MoxtraToken balls to the wall
	MoxtraToken struct {
		AccessToken string `json:"access_token"`
		TokenType   string `json:"token_type"`
		ExpiresIn   int    `json:"expires_in"`
		Scope       string
	}

	MoxtraChatRoom struct {
		Name         string
		Conversation bool
	}
	ChatroomResp struct {
		Code string
		Data CRD
	}
	CRD struct {
		ID          string
		Name        string
		Revision    int
		CreatedTime int
		UpdatedTime int
	}
)

func main() {
	log.Println("Server is warming up...")
	initDB()
	initMoxtra()
	defer s.Session.Close()
	http.Handle("/", initHandlers())
	log.Fatalln(http.ListenAndServe(":3000", nil))
}

func initMoxtra() {
	u, err := uuid.NewV4()
	if err != nil {
		log.Fatalf("Unable to Gen UUID for Moxtra.")
	}
	moxtraTimeStamp = strconv.FormatInt(time.Now().Unix()*1000, 10)
	log.Printf("%v", moxtraTimeStamp)
	combString := moxtraClientID + u.String() + moxtraTimeStamp

	mac := hmac.New(sha256.New, moxtraClientSecret)
	mac.Write([]byte(combString))
	moxtraSignature = mac.Sum(nil)
	str := base64.StdEncoding.EncodeToString(moxtraSignature)
	fmt.Println(str)
	str = strings.Replace(str, "\\", "-", -1)
	str = strings.Replace(str, "/", "_", -1)
	str = str[:len(str)-1]
	client := &http.Client{}
	url := moxtraAPI + moxtraClientID + moxtraCS + string(moxtraClientSecret) + moxtraGrantType + u.String() + moxtraTS + moxtraTimeStamp + moxtraSig + str //string(moxtraSignature)
	log.Println(url)
	request, _ := http.NewRequest("POST", url, nil)
	//	request.Header.Add("Accept", "application/json")
	res, err := client.Do(request)
	if err != nil {
		//		http.Error(w, "Req didn't go through", 500)
		//		return
		log.Fatalf("Req didn't go through, %v", err)
	}
	moxie := MoxtraToken{}
	//err = ReadJSON(request, &moxie)
	defer res.Body.Close()
	//	var data json.RawMessage
	log.Printf("%v", res.Body)
	err = json.NewDecoder(res.Body).Decode(&moxie)
	log.Printf("\n\n%v\n", moxie)
	if err != nil {
		//		http.Error(w, "Couldn't decode data...", 500)
		//		return
		log.Fatalf("Can't resolve the datum?\n %v", err)
		//	panic(err)
	}
	log.Println("PASSED")
	//err = json.Unmarshal(data, &moxie)
	if err != nil {
		//http.Error(w, "Couldn't marshall into individual waltOBJ.", 500)
		//return
		log.Fatalf("Can't unmarshall into individ waltOBJ, %v", err)
	}
	s.MoxtraToken = moxie
	log.Printf("%v", moxie)
}

func initHandlers() *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/beacon", handlePOSTBeacon).Methods("POST", "OPTIONS")
	r.HandleFunc("/beacon/{minorID:[0-9]+}", handleBeacon).Methods("GET")
	return r
}

func handlePOSTBeacon(w http.ResponseWriter, req *http.Request) {
	log.Println("I got here?")
	switch req.Method {
	case "OPTIONS":
		w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		fallthrough
	case "POST":
		//		w.Header().Set("Access-Control-Allow-Origin", "*")
		var formResponse FormResponse
		err := ReadJSON(req, &formResponse)
		log.Printf("We have begun the ritual, %v", formResponse)
		client := &http.Client{}
		request, _ := http.NewRequest("GET", waltersAPIPrefix+strings.Replace(formResponse.Title, " ", "%20", -1), nil)
		request.Header.Add("Accept", "application/json")
		res, err := client.Do(request)
		if err != nil {
			http.Error(w, "Req didn't go through", 500)
			return
			//		log.Fatalf("Req didn't go through, %v", err)
		}
		defer res.Body.Close()
		var data json.RawMessage
		err = json.NewDecoder(res.Body).Decode(&data)
		if err != nil {
			http.Error(w, "Couldn't decode data...", 500)
			return
			//		log.Fatalf("Can't resolve the datum?%v", err)
		}
		wal := Walters{}
		err = json.Unmarshal(data, &wal)
		if err != nil {
			http.Error(w, "Couldn't marshall into individual waltOBJ.", 500)
			return
			//		log.Fatalf("Can't unmarshall into individ waltOBJ, %v", err)
		}
		if len(wal.Items) < 1 {
			http.Error(w, "Couldn't marshall correctly", 500)
			return
		}
		waltersObject := wal.Items[0]
		waltersObject.Beacon = Beacon{formResponse.ProxID, formResponse.MajorID, formResponse.MinorID}
		waltersObject.ImageURL = waltersImagePrefix + strings.Split(waltersObject.Images, ",")[0] + waltersImagePostfix
		waltersObject.CuratorComment = formResponse.Description

		name := strconv.Itoa(waltersObject.Beacon.MinorID)
		d, errorsA := json.Marshal(MoxtraChatRoom{Name: name, Conversation: true})
		if errorsA != nil {
			panic(errorsA)
		}
		req2, _ := http.NewRequest("POST", "https://api.moxtra.com/me/binders", bytes.NewBuffer(d))
		log.Println(s.MoxtraToken.AccessToken)
		req2.Header.Add("Authorization", "bearer "+s.MoxtraToken.AccessToken)
		req.Header.Set("Content-Type", "application/json")
		res2, err2 := client.Do(req2)
		if err2 != nil {
			http.Error(w, "Req didn't go through", 500)
			return
			//		log.Fatalf("Req didn't go through, %v", err)
		}
		defer res2.Body.Close()
		chr := ChatroomResp{}
		err2 = json.NewDecoder(res2.Body).Decode(&chr)
		if err != nil {
			http.Error(w, "Couldn't decode data...", 500)
			return
			//		log.Fatalf("Can't resolve the datum?%v", err)
		}
		waltersObject.BinderID = chr.Data.ID

		//	err2 = json.Unmarshal(data, &chr)

		err2 = Insert("beacon", waltersObject.Beacon)
		if err2 != nil {
			//Return a 500
			http.Error(w, "Couldn't insert corresponding beacon.", 500)
			return
		}

		err = Insert("art", waltersObject)
		if err != nil {
			//Return a 500
			http.Error(w, "Couldn't insert corresponding art piece.", 500)
			return
		}
		//https//api.moxtra.com/me/binders
		http.Error(w, http.StatusText(http.StatusCreated), http.StatusCreated)
		break
	}
}

func handleBeacon(w http.ResponseWriter, req *http.Request) {
	params := mux.Vars(req)
	minorID, err := strconv.Atoi(params["minorID"])
	if err != nil {
		http.Error(w, "Beacon can't be found with invalid id", 404)
	}
	log.Println(minorID)
	beacon, err := SearchBeaconByID(minorID, 0, -1)
	log.Printf("%v", beacon)
	if err != nil {
		//Beacon not found return 404
		http.Error(w, "Beacon not found in db", 404)
	}
	for _, i := range beacon {
		arts, error := SearchArtByBeacon(i, 0, -1)
		if error != nil {
			http.Error(w, "Beacon assigned to art piece", 404)
		}
		ServeJSON(w, arts)

	}
	//	responseHeaders.Add("Accept","application/json")
	http.Error(w, "Beacon not found", 404)
	//Send a get request to api with keyword param
}

func initDB() {
	s.DBURI = DBURI
	s.dbName = dbName
	s.getSession()
	s.Session.SetSafe(&mgo.Safe{})
	s.Session.SetMode(mgo.Monotonic, true)
	cNames, errors := EnsureIndex(CollectionNames, indices...)
	for k, err := range errors {
		if err != nil {
			log.Fatalf("Indices not taking for %v;%v\n", cNames[k], err)
		}
	}
}

//EnsureIndex ensures that when we store things, we get the expected results
func EnsureIndex(collectionNames []string, indices ...mgo.Index) (s []string, e []error) {
	for j, k := range indices {
		function := func(c *mgo.Collection) error {
			return c.EnsureIndex(k)
		}
		err := withCollection(collectionNames[j], function)
		if err != nil {
			s = append(s, collectionNames[j])
			e = append(e, err)
		}
	}
	return
}

func (s *Server) getSession() *mgo.Session {
	if s.Session == nil {
		var err error
		dialInfo := &mgo.DialInfo{
			Addrs:    []string{s.DBURI},
			Direct:   true,
			FailFast: false,
		}
		s.Session, err = mgo.DialWithInfo(dialInfo)
		if err != nil {
			log.Fatalf("Can't find MongoDB. Is it started? %v\n", err)
		}
	}
	// Returns a copy of the session so we don't waste le resources? Doesn't reuse socket however
	return s.Session.Copy()
}

func withCollection(collection string, fn func(*mgo.Collection) error) error {
	session := s.getSession()
	defer session.Close()
	c := session.DB(s.dbName).C(collection)
	return fn(c)
}

//Insert datum into a specific collection
func Insert(collectionName string, values ...interface{}) error {
	function := func(c *mgo.Collection) error {
		err := c.Insert(values...)
		if err != nil {
			log.Printf("Can't insert document, %v\n", err)
		}
		return err
	}
	return withCollection(collectionName, function)
}

//SearchBeacon searches for a beacon using a passed in struct
func SearchBeacon(q interface{}, skip int, limit int) (searchResults []Beacon, err error) {
	searchResults = []Beacon{}
	query := func(c *mgo.Collection) error {
		function := c.Find(q).Skip(skip).Limit(limit).All(&searchResults)
		if limit < 0 {
			function = c.Find(q).Skip(skip).All(&searchResults)
		}
		return function
	}
	search := func() error {
		return withCollection("beacon", query)
	}
	err = search()
	return
}

//Estimote id
//

//SearchBeaconByID is a
func SearchBeaconByID(minorID int, skip int, limit int) (searchResults []Beacon, err error) {
	//	if len(beacon) == 20 {
	return SearchBeacon(bson.M{"minorid": minorID}, skip, limit)
	//	}
	//	return nil, errors.New("Not long enough to be a beacon")
}

//SearchArt is a
func SearchArt(q interface{}, skip int, limit int) (searchResults []WalterObj, err error) {
	searchResults = []WalterObj{}
	query := func(c *mgo.Collection) error {
		function := c.Find(q).Skip(skip).Limit(limit).All(&searchResults)
		if limit < 0 {
			function = c.Find(q).Skip(skip).All(&searchResults)
		}
		return function
	}
	search := func() error {
		return withCollection("art", query)
	}
	err = search()
	return
}

//SearchArtByBeacon is a specific version of searchArt
func SearchArtByBeacon(beacon Beacon, skip int, limit int) (searchResults []WalterObj, err error) {
	return SearchArt(bson.M{"beacon": beacon}, skip, limit)
}

// ServeJSON replies to the request with a JSON
// representation of resource v.
func ServeJSON(w http.ResponseWriter, v interface{}) {
	// avoid json vulnerabilities, always wrap v in an object literal
	//	doc := map[string]interface{}{"d": v}
	if data, err := json.Marshal(v); err != nil {
		log.Printf("Error marshalling json: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		w.Header().Set("Content-Length", strconv.Itoa(len(data)))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Write(data)
	}
}

// ReadJSON decodes JSON data into a provided struct which must be passed in as a pointer.
//If it's not a pointer you are basically putting your data into a bottomless gorge and willing it to
//show up right next to you. Just no.
func ReadJSON(req *http.Request, v interface{}) error {
	defer req.Body.Close()
	decoder := json.NewDecoder(req.Body)
	err := decoder.Decode(v)
	return err
}

//Use this method to debug things
func logRequest(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		var s = time.Now()
		handler(w, r)
		log.Printf("%s %s %6.3fms", r.Method, r.RequestURI, (time.Since(s).Seconds() * 1000))
	}
}


text:
@page migrate-3 Migrating to DoneJS 3
@parent Guides
@hide sidebar
@outline 2 ol
@description This guide walks you through the step-by-step process of upgrading a DoneJS 2 app to DoneJS 3.

@body

This guide explains how to upgrade DoneJS 2 app to DoneJS 3.

## Pre-migration preparation

Before upgrading to DoneJS 3, it's a good idea to make sure all of your tests are passing, your project builds successfully, and you can deploy your app. This will give you more assurance as you upgrade individual parts of your project.

To make sure tests are passing, run:

```shell
donejs test
```

To confirm that your build is working correctly, run:

```shell
donejs build
NODE_ENV=production donejs start
```

This will create your production build and then start a local server in production mode. If you open [localhost:8080](http://localhost:8080/) in your browser, you should see the production bundles being loaded in the Network tab of your developer tools.

Once you are confident that you are ready to upgrade, create a new branch from which to work. Assuming you are using git run this command:

```js
git checkout -b upgrade-donejs
```

If you are using a different version control system, substitute above for the relevant commands. The idea is the same; create a new branch from which to make the DoneJS upgrade changes.

## Install donejs@3

Once you have completed the preprepation, upgrade to the latest version of the __donejs__ global package.

```shell
npm install --global donejs@3
```

Now any time you create new applications using `donejs add app`, it will scaffold out a DoneJS 3 project.

## Run donejs upgrade

Running `donejs upgrade` will upgrade all of your dependencies to their latest version and run any codemods that are available. Running the following command:

```shell
donejs upgrade
```

This will:

* Update your package.json with the latest versions of each DoneJS packages.
* Run `npm install`, to give you the latest versions.
* Run `can-migrate` to apply codemods for the changes that happened in CanJS 5.0.

Once this is complete you will see several changed files. It's a good idea to look at these files using your favorite diff tool to see if the changes look correct. can-migrate is conservative about the changes it makes but is not perfect.

If you would prefer *not* to run the CanJS codemods as part of the upgrade, you can skip this part by running the command as `donejs upgrade --no-canmigrate`.

## Go through the StealJS 2 Migration Guide

StealJS 2 only has a few, small, breaking changes, so it's easiest to upgrade it first. The [StealJS 2.0 migration guide](https://stealjs.com/docs/StealJS.topics.migrating-two.html) goes over the few things you might need to change in your code.

## Go through the CanJS 5 Migration Guide

Although `donejs upgrade` covers a lot of the important parts of the upgrade, especially getting the correct versions of each dependency, it cannot do everything for you.

The [CanJS 5.0 migration guide](https://canjs.com/doc/migrate-5.html) goes over the parts that you might need to change manually. Reviewing this guide will also help familiarize yourself with CanJS 5, so it's a good thing to read even if you are developing a new project.

## Getting help

We've taken care to make upgrading DoneJS apps as easy as possible. However, as always, we're available on [Slack](https://www.bitovi.com/community/slack) ([#donejs channel](https://bitovi-community.slack.com/messages/CFC80DU5B)) and [the forums](https://forums.bitovi.com/) to try and help!

redpajama_set_name: RedPajamaGithub


text:
var caml = new CamlBuilder().Where()
	.Any(
	CamlBuilder.Expression().TextField("Email").EqualTo("support@google.com"),
	CamlBuilder.Expression().TextField("Email").EqualTo("plus@google.com"),
	CamlBuilder.Expression().TextField("Title").BeginsWith("[Google]"),
	CamlBuilder.Expression().TextField("Content").Contains("Google")
	)
	.ToString();

caml = new CamlBuilder().Where()
	.UserField("AssignedTo").EqualToCurrentUser()
	.Or()
	.UserField("AssignedTo").Membership.CurrentUserGroups()
	.GroupBy("Category")
	.OrderBy("Priority").ThenBy("Title")
	.ToString();

caml = new CamlBuilder().Where()
	.All(
	CamlBuilder.Expression().All(
		CamlBuilder.Expression().BooleanField("Enabled").IsTrue(),
		CamlBuilder.Expression().UserMultiField("TargetAudience").EqualTo("55").Or().UserMultiField("TargetAudience").EqualTo("66")
		),
	CamlBuilder.Expression().Any(
		CamlBuilder.Expression().TextField("NotificationScope").EqualTo("77"),
		CamlBuilder.Expression().TextField("NotificationScope").EqualTo("88").And().TextField("ScopeWebRelativeUrl").EqualTo("99")
		)
	)
	.ToString();

var caml = new CamlBuilder().Where()
	.LookupField("Category").Id().In([2, 3, 10])
	.And()
	.DateField("ExpirationDate").GreaterThan(CamlBuilder.CamlValues.Now)
	.OrderBy("ExpirationDate")
	.ToString()

caml = new CamlBuilder().Where().CounterField("ID").In([1, 2, 3]).ToString();

caml = CamlBuilder.Expression()
	.All(
		CamlBuilder.Expression().DateField("BroadcastExpires").GreaterThanOrEqualTo(CamlBuilder.CamlValues.Today),
		CamlBuilder.Expression().Any(
			CamlBuilder.Expression().UserField("BroadcastTo").IsInCurrentUserGroups(),
			CamlBuilder.Expression().UserField("BroadcastTo").EqualToCurrentUser()
		),
		CamlBuilder.Expression().DateRangesOverlap(CamlBuilder.DateRangesOverlapType.Year, new Date().toISOString())
	)
	.ToString();

caml = new CamlBuilder().Where().DateTimeField("Created").GreaterThan(new Date(Date.UTC(2013,0,1))).ToString();


text:
namespace prnn { class RecurrentOpsHandle; }

namespace prnn { namespace matrix { class DynamicView;      } }
namespace prnn { namespace matrix { class ConstDynamicView; } }
namespace prnn { namespace matrix { class Precision;        } }
namespace prnn { namespace matrix { class Dimension;        } }
namespace prnn { namespace matrix { class Matrix;           } }

namespace prnn
{
namespace rnn
{

size_t getMaximumSizeRNNForThisGPU(const matrix::Precision&);

void forwardPropRecurrent(
    const matrix::DynamicView& activations,
    const matrix::ConstDynamicView& inputActivations,
    const matrix::ConstDynamicView& weights,
    const matrix::DynamicView& scratch,
    const matrix::DynamicView& reserve,
    const RecurrentOpsHandle& handle);

void backPropDeltasRecurrent(const matrix::DynamicView& inputDeltas,
    const matrix::ConstDynamicView& weights,
    const matrix::ConstDynamicView& outputActivations,
    const matrix::ConstDynamicView& outputDeltas,
    const matrix::DynamicView& scratch,
    const matrix::DynamicView& reserve,
    const RecurrentOpsHandle& handle);

void backPropGradientsRecurrent(const matrix::DynamicView& dWeights,
    const matrix::ConstDynamicView& inputActivations,
    const matrix::ConstDynamicView& outputActivations,
    const matrix::ConstDynamicView& scratch,
    const matrix::ConstDynamicView& reserve,
    const RecurrentOpsHandle& handle);

size_t getForwardPropScratchSize(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);
size_t getBackPropDeltasScratchSize(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);
size_t getBackPropGradientsScratchSize(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);

matrix::Dimension getReserveDimensions(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);
matrix::Dimension getWeightDimensions(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);

void getWeightsRange(matrix::Dimension& begin, matrix::Dimension& end,
    const RecurrentOpsHandle& handle,
    const matrix::Precision& precision, int index);

matrix::Matrix getForwardPropScratch(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);
matrix::Matrix getBackPropDeltasScratch(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);
matrix::Matrix getBackPropGradientsScratch(const RecurrentOpsHandle& handle,
    const matrix::Precision& precision);

}
}


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

namespace NPoco.Expressions
{
    public static class S
    {
        public static bool In<T>(this T value, IEnumerable<T> list)
        {
            return list.Contains(value);
        }

        public static string Desc<T>(T value)
        {
            return value == null ? "" : value.ToString() + " DESC";
        }

        public static string As<T>(T value, object asValue)
        {
            return value == null ? "" : string.Format("{0} AS {1}", value.ToString(), asValue);
        }

        public static T Sum<T>(T value)
        {
            return value;
        }

        public static T Count<T>(T value)
        {
            return value;
        }

        public static T Min<T>(T value)
        {
            return value;
        }

        public static T Max<T>(T value)
        {
            return value;
        }

        public static T Avg<T>(T value)
        {
            return value;
        }
    }
}


text:
class HashTable(object):

    # constructor
    # provides the basic structure of the Hash Table
    def __init__(self, size):
        self.size = size
        self.slots = [None] * self.size
        self.value = [None] * self.size

    # Method to insert an element in the table
    def insert(self, key, value):

        # first find a hash Value
        hashValue = self.hash(key, len(self.slots))

        # if the slot at the above hash Value is empty
        if self.slots[hashValue] == None:
            self.slots[hashValue] = key
            self.value[hashValue] = value

        else:

            # if the key of the value which is being inserted
            # already exists then just update the value
            if self.slots[hashValue] == key:
                self.value[hashValue] = value

            # else find a new slot
            else:

                # take the next slot
                nextSlot = self.rehash(hashValue, len(self.slots))

                # loop through the slots
                while self.slots[nextSlot] is not None and self.slots[nextSlot] is not key:
                    nextSlot = self.rehash(nextSlot, len(self.slots))

                # if we found an empty slot then insert in it
                if self.slots[nextSlot] == None:
                    self.slots[nextSlot] = key
                    self.value[nextSlot] = value

                # if the key of the value which is being inserted
                # already exists then just update the value
                else:
                    self.value[nextSlot] = value

    # method to find the hash value
    def hash(self, key, size):
        return key%size

    # method to find the next hash value
    def rehash(self, oldHash, size):
        return (oldHash + 1) % size

    # method to get the value associated to a key
    def get(self, key):

        # initially we look for the key's corresponding original slot
        startSlot = self.hash(key, len(self.slots))
        value = None
        stop = False
        found = False
        pos = startSlot

        # loop through the slots
        while self.slots[pos] is not None and not found and not stop:

            # if the slot is found
            if self.slots[pos] == key:
                found = True
                value = self.value[pos]

            # try the next hash
            else:
                pos = self.rehash(pos, len(self.slots))

                # if we reached the first slot where we started from then stop
                if pos == startSlot:
                    stop = True

        return value


text:
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;

namespace Nest.Litterateur
{
	public static class SyntaxNodeExtensions
	{
		public static bool ShouldBeHidden(this SyntaxNode node)
		{
			return node.HasLeadingTrivia && Regex.IsMatch(node.GetLeadingTrivia().ToFullString(), @"\/\/\s*hide");
		}
	}
}


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

MAILING_LISTS = { :customer => '1', :merchandiser => '2' }

describe NewsieQ::Job do
  let(:job) { NewsieQ::Job }
  let(:email) { Faker::Internet.email }
  let(:mailing_list_id) { 'f80ai25uox' }
  let(:mailing_list) { :mailing_list }
  let(:mailing_lists) { MAILING_LISTS }
  before { NewsieQ::Mailchimp.mailing_lists = MAILING_LISTS }

  describe "subscribe" do
    after { job.subscribe(mailing_list, email) }

    it "should enqueue" do
      Resque.should_receive(:enqueue).with(NewsieQ::Job, mailing_list, email)
    end
  end

  describe "perform" do
    after { job.perform(:customer, email) }

    it "should call subscribe_to_mailing_list" do
      job.should_receive(:subscribe_to_mailing_list).with('1', email)
    end
  end

  describe "mailing_list_id" do
    let(:mailing_list) { 'customer' }
    after { NewsieQ::Job.mailing_list_id(mailing_list) }

    it "should convert string to symbol" do
      mailing_list.should_receive(:to_sym)
    end

  end

  describe "subscribe_to_mailing_list" do
    let(:client) { mock }
    before do
      client.stub(:list_subscribe => true)
      NewsieQ::Mailchimp.stub(:api_client => client)
    end
    after { job.subscribe_to_mailing_list(mailing_list_id, email) }

    it "should subscribe to mailchimp" do
      client.should_receive(:list_subscribe).with(mailing_list_id, email, {}, 'html', false)
    end
  end

end


text:
import { FETCH_BOOKS, FETCH_A_BOOK, REVISE_BOOK } from '../actions/books';
import _ from 'lodash';

export function books(state = {}, action) {
  switch (action.type) {
    case FETCH_BOOKS:
    return _.mapKeys(action.payload, 'id');

    case REVISE_BOOK:
    return { ...state, [action.book.id]: action.book};

    default:
    return state;
  };
}

export function current_book(state = {}, action) {
  switch (action.type) {

    case FETCH_A_BOOK:
    return null;

    default:
    return state;
  }
}


text:
package vn.com.hiringviet.service;

import java.util.List;

import org.springframework.stereotype.Service;

import vn.com.hiringviet.dto.CommentDTO;

// TODO: Auto-generated Javadoc
/**
 * The Interface CommentService.
 */
@Service("commentService")
public interface CommentService {

	/**
	 * Gets the list comment.
	 *
	 * @param first the first
	 * @param max the max
	 * @param Id the id
	 * @param isPost the is post
	 * @return the list comment
	 */
	public List<CommentDTO> getListComment(Integer first, Integer max, Integer Id, boolean isPost);

	/**
	 * Creates the.
	 *
	 * @param commentDTO the comment dto
	 * @return the integer
	 */
	public Integer create(CommentDTO commentDTO);

	/**
	 * Delete.
	 *
	 * @param commentId the comment id
	 * @return true, if successful
	 */
	public boolean delete(Integer commentId);
}


text:
import { IPromise } from 'angular';
import { API } from 'core';

export interface ISlackChannel {
  id: string;
  name: string;
  is_channel: boolean;
  creator: string;
  is_archived: boolean;
  name_normalized: string;
  num_members: number;
}

export class SlackReader {
  public static getChannels(): IPromise<ISlackChannel[]> {
    return API.one('slack/channels')
      .getList()
      .catch(() => [] as ISlackChannel[]);
  }
}


text:
package org.apache.spark.status

import org.apache.spark.SparkFunSuite
import org.apache.spark.status.api.v1.TaskMetricDistributions
import org.apache.spark.util.Distribution
import org.apache.spark.util.kvstore._

class AppStatusStoreSuite extends SparkFunSuite {

  private val uiQuantiles = Array(0.0, 0.25, 0.5, 0.75, 1.0)
  private val stageId = 1
  private val attemptId = 1

  test("quantile calculation: 1 task") {
    compareQuantiles(1, uiQuantiles)
  }

  test("quantile calculation: few tasks") {
    compareQuantiles(4, uiQuantiles)
  }

  test("quantile calculation: more tasks") {
    compareQuantiles(100, uiQuantiles)
  }

  test("quantile calculation: lots of tasks") {
    compareQuantiles(4096, uiQuantiles)
  }

  test("quantile calculation: custom quantiles") {
    compareQuantiles(4096, Array(0.01, 0.33, 0.5, 0.42, 0.69, 0.99))
  }

  test("quantile cache") {
    val store = new InMemoryStore()
    (0 until 4096).foreach { i => store.write(newTaskData(i)) }

    val appStore = new AppStatusStore(store)

    appStore.taskSummary(stageId, attemptId, Array(0.13d))
    intercept[NoSuchElementException] {
      store.read(classOf[CachedQuantile], Array(stageId, attemptId, "13"))
    }

    appStore.taskSummary(stageId, attemptId, Array(0.25d))
    val d1 = store.read(classOf[CachedQuantile], Array(stageId, attemptId, "25"))

    // Add a new task to force the cached quantile to be evicted, and make sure it's updated.
    store.write(newTaskData(4096))
    appStore.taskSummary(stageId, attemptId, Array(0.25d, 0.50d, 0.73d))

    val d2 = store.read(classOf[CachedQuantile], Array(stageId, attemptId, "25"))
    assert(d1.taskCount != d2.taskCount)

    store.read(classOf[CachedQuantile], Array(stageId, attemptId, "50"))
    intercept[NoSuchElementException] {
      store.read(classOf[CachedQuantile], Array(stageId, attemptId, "73"))
    }

    assert(store.count(classOf[CachedQuantile]) === 2)
  }

  test("only successfull task have taskSummary") {
    val store = new InMemoryStore()
    (0 until 5).foreach { i => store.write(newTaskData(i, status = "FAILED")) }
    val appStore = new AppStatusStore(store).taskSummary(stageId, attemptId, uiQuantiles)
    assert(appStore.size === 0)
  }

  test("summary should contain task metrics of only successfull tasks") {
    val store = new InMemoryStore()

    for (i <- 0 to 5) {
      if (i % 2 == 1) {
        store.write(newTaskData(i, status = "FAILED"))
      } else {
        store.write(newTaskData(i))
      }
    }

    val summary = new AppStatusStore(store).taskSummary(stageId, attemptId, uiQuantiles).get

    val values = Array(0.0, 2.0, 4.0)

    val dist = new Distribution(values, 0, values.length).getQuantiles(uiQuantiles.sorted)
    dist.zip(summary.executorRunTime).foreach { case (expected, actual) =>
      assert(expected === actual)
    }
  }

  private def compareQuantiles(count: Int, quantiles: Array[Double]): Unit = {
    val store = new InMemoryStore()
    val values = (0 until count).map { i =>
      val task = newTaskData(i)
      store.write(task)
      i.toDouble
    }.toArray

    val summary = new AppStatusStore(store).taskSummary(stageId, attemptId, quantiles).get
    val dist = new Distribution(values, 0, values.length).getQuantiles(quantiles.sorted)

    dist.zip(summary.executorRunTime).foreach { case (expected, actual) =>
      assert(expected === actual)
    }
  }

  private def newTaskData(i: Int, status: String = "SUCCESS"): TaskDataWrapper = {
    new TaskDataWrapper(
      i, i, i, i, i, i, i.toString, i.toString, status, i.toString, false, Nil, None,
      i, i, i, i, i, i, i, i, i, i,
      i, i, i, i, i, i, i, i, i, i,
      i, i, i, i, stageId, attemptId)
  }
}


text:
#ifndef itkImageAndPathToImageFilter_h
#define itkImageAndPathToImageFilter_h

#include "itkImageToImageFilter.h"

namespace itk
{
/** \class ImageAndPathToImageFilter
 * \brief Base class for filters that take both a path and an image as input and produce a path as output.
 *
 * This class is the base class for filters that take both an image and a path
 * as input and produce an image as output.  Specifically, this class defines
 * the methods SetPathInput() and SetImageInput().  (It also establishes the
 * precedent of having image inputs precede path inputs for functions producing
 * images as outputs, according to the underlying DataObject implementation.)
 *
 * \ingroup ImageFilters
 * \ingroup PathFilters
 * \ingroup ITKPath
 */
template< typename TInputImage, typename TInputPath, typename TOutputImage >
class ImageAndPathToImageFilter:
  public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
  /** Standard class typedefs. */
  typedef ImageAndPathToImageFilter                       Self;
  typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass;
  typedef SmartPointer< Self >                            Pointer;
  typedef SmartPointer< const Self >                      ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(ImageAndPathToImageFilter, ImageToImageFilter);

  /** Some convenient typedefs. */
  typedef          TInputImage                  InputImageType;
  typedef typename InputImageType::ConstPointer InputImagePointer;
  typedef typename InputImageType::RegionType   InputImageRegionType;
  typedef typename InputImageType::PixelType    InputImagePixelType;
  typedef          TInputPath                   InputPathType;
  typedef typename InputPathType::Pointer       InputPathPointer;
  typedef typename InputPathType::ConstPointer  InputPathConstPointer;
  typedef typename InputPathType::InputType     InputPathInputType;
  typedef typename InputPathType::OutputType    InputPathOutputType;
  typedef typename InputPathType::IndexType     InputPathIndexType;
  typedef typename InputPathType::OffsetType    InputPathOffsetType;
  typedef          TOutputImage                 OutputImageType;
  typedef typename OutputImageType::Pointer     OutputImagePointer;
  typedef typename OutputImageType::RegionType  OutputImageRegionType;
  typedef typename OutputImageType::PixelType   OutputImagePixelType;

  /** ImageDimension constants */
  itkStaticConstMacro(InputImageDimension, unsigned int,
                      TInputImage::ImageDimension);
  itkStaticConstMacro(OutputImageDimension, unsigned int,
                      TOutputImage::ImageDimension);

  /** Set/Get the image input of this process object. */
  virtual void SetImageInput(const TInputImage *image);

  /** Set/Get the path input of this process object. */
  virtual void SetPathInput(const TInputPath *path);

  const InputImageType * GetImageInput();
  const InputPathType * GetPathInput();

protected:
  InputImageType * GetNonConstImageInput();
  InputPathType * GetNonConstPathInput();
  ImageAndPathToImageFilter();
  virtual ~ImageAndPathToImageFilter() {}

  virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

private:
  ITK_DISALLOW_COPY_AND_ASSIGN(ImageAndPathToImageFilter);
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkImageAndPathToImageFilter.hxx"
#endif

#endif


text:
package com.vicmns.library;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.TextView;

/**
 * Created by vicmns on 2/4/2015.
 */
public class FullScreenShowcaseView extends ShowcaseView {

    public FullScreenShowcaseView(Context context) {
        this(context, null);
    }

    public FullScreenShowcaseView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FullScreenShowcaseView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public FullScreenShowcaseView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initShowcaseView() {
        initViews();
    }

    private void initViews() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        mMainLayout = (ViewGroup) inflater.inflate(R.layout.showcase_fullscreen_layout, this, false);
        mTitleTextView = (TextView) mMainLayout.findViewById(R.id.showcase_title);
        mDescriptionTextView = (TextView) mMainLayout.findViewById(R.id.showcase_description);
        mShowcaseButton =  mMainLayout.findViewById(R.id.showcase_button);

        addView(mMainLayout);
    }

    public static class Builder {
        final FullScreenShowcaseView mShowcaseView;
        private boolean isAttached;
        private final Activity mActivity;

        public Builder(Activity activity) {
            mActivity = activity;
            mShowcaseView = new FullScreenShowcaseView(activity);
        }

        public Builder attachToView(ViewGroup parentView) {
            parentView.addView(mShowcaseView);
            mShowcaseView.setVisibility(View.INVISIBLE);
            isAttached = true;
            return this;
        }

        public Builder setOnClickListener(OnClickListener onClickListener) {
            mShowcaseView.overrideButtonClick(onClickListener);
            return this;
        }

        public Builder setShowCaseEventListener(OnShowcaseEventListener onShowcaseEventListener) {
            mShowcaseView.setonShowcaseEventListener(onShowcaseEventListener);
            return this;
        }

        public Builder setShowcaseTitle(String showcaseTitle) {
            mShowcaseView.setTitleText(showcaseTitle);
            return this;
        }

        public Builder setShowcaseDescription(String showcaseDescription) {
            mShowcaseView.setDescriptionText(showcaseDescription);
            return this;
        }

        public Builder doNotAttach() {
            isAttached = true;
            return this;
        }

        public Builder hideButton() {
            mShowcaseView.setShowcaseButtonVisibility(View.GONE);
            return this;
        }

        public FullScreenShowcaseView build() {
            if(!isAttached) {
                attachShowCaseToDecorView(mActivity, mShowcaseView);
            }

            return mShowcaseView;
        }
    }

    private static void attachShowCaseToDecorView(Activity activity, View showcaseView) {
        ((ViewGroup) activity.getWindow().getDecorView()).addView(showcaseView);
        showcaseView.setVisibility(View.INVISIBLE);
    }

    public void clear() {
        ((ViewManager) this.getParent()).removeView(this);
    }

    public void setStatusBarColor(int color){
        Activity parent = (Activity)getContext();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if(parent.getWindow() != null)
                parent.getWindow().setStatusBarColor(color);
        }
    }

    public int getStatusBarColor() {
        Activity parent = (Activity)getContext();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if(parent.getWindow() != null)
                return parent.getWindow().getStatusBarColor();
        }

        return getResources().getColor(android.R.color.black);
    }

    public void setNavigationBarColor(int color) {
        Activity parent = (Activity)getContext();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if(parent.getWindow() != null)
                parent.getWindow().setNavigationBarColor(color);
        }
    }

    public int getNavigationBarColor() {
        Activity parent = (Activity)getContext();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if(parent.getWindow() != null)
                return parent.getWindow().getNavigationBarColor();
        }

        return getResources().getColor(android.R.color.black);
    }
}


text:
package ro.tla.doubt.feedback.commons;

import ro.tla.doubt.feedback.commons.operations.Operation;

public interface OperationExecutorRpcHandler {

    public abstract Object execute(Operation operation) throws Exception;

}


text:
require_relative '../../puppet_x/puppetlabs/property/tag.rb'
require 'puppet/property/boolean'

Puppet::Type.newtype(:ec2_volume) do
  @doc = 'type representing an EC2 Block Device'

  ensurable

  newparam(:name, namevar: true) do
    desc 'the name of the security group'
    validate do |value|
      fail 'Volume must have a name' if value == ''
      fail 'name should be a String' unless value.is_a?(String)
    end
  end

  newproperty(:region) do
    desc 'the region in which to launch the volume'
    validate do |value|
      fail 'region should not contain spaces' if value =~ /\s/
      fail 'region should be a String' unless value.is_a?(String)
    end
  end

  newproperty(:tags, :parent => PuppetX::Property::AwsTag) do
    desc 'the tags for the volume'
  end

  newproperty(:description) do
    desc 'a short description of the volume'
    validate do |value|
      fail 'description cannot be blank' if value == ''
      fail 'description should be a String' unless value.is_a?(String)
    end
  end

  newproperty(:availability_zone) do
    desc 'The availability zone in which to place the instance.'
    validate do |value|
      fail 'availability_zone should not contain spaces' if value =~ /\s/
      fail 'availability_zone should not be blank' if value == ''
      fail 'availability_zone should be a String' unless value.is_a?(String)
    end
  end

  newproperty(:size) do
    desc 'The size in GB of the volume.'
    validate do |value|
      fail 'Size should be a integer' unless value =~ /^\d+$/
    end
  end

  newproperty(:volume_id) do
    desc 'aws id of volume'
    validate do |value|
      fail "Volume Type should be a String: #{value}" unless value.is_a?(String)
    end
  end

  newproperty(:volume_type) do
    desc 'standard, io1, gp2'
    validate do |value|
      fail "Volume Type should be a String: #{value}" unless value.is_a?(String)
    end
  end

  newproperty(:snapshot_id) do
    desc 'The snapshot that this volume should be created from'
    validate do |value|
      fail 'snapshot_id should be an string' unless value.is_a?(String)
    end
  end

  newproperty(:attach) do
    desc 'The ec2 instance that this volume should attach to'
    validate do |value|
      attachments = value.is_a?(Array) ? value : [value]
      attachments.each do |params|
        fail "must supply instance id" unless value.keys.include?('instance_id')
        fail "must supply device name" unless value.keys.include?('device')
      end
    end
  end

  newproperty(:iops) do
    desc 'Provisioned iops for volume'
    validate do |value|
      fail 'iops should be an integer' unless value =~ /^\d+$/
    end
  end

  newproperty(:kms_key_id) do
    desc 'The full ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use when creating the encrypted volume.'
    validate do |value|
      fail 'kms_key_id should be an string' unless value.is_a?(String)
    end
  end

  newproperty(:encrypted, parent: Puppet::Property::Boolean) do
    desc 'Indicates whether newly created volume should be encrypted.'
  end
end


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const shady = require("shady-css-parser");
const document_1 = require("../parser/document");
const cssbeautify = require("cssbeautify");
class ParsedCssDocument extends document_1.ParsedDocument {
    constructor() {
        super(...arguments);
        this.type = 'css';
    }
    visit(visitors) {
        for (const node of this) {
            for (const visitor of visitors) {
                visitor.visit(node);
            }
        }
    }
    sourceRangeForNode(node) {
        return this.sourceRangeForShadyRange(node.range);
    }
    /**
     * Takes a range from a shadycss node directly, rather than a shadycss node.
     * Useful when there are multiple ranges for a given node.
     */
    sourceRangeForShadyRange(range) {
        return this.offsetsToSourceRange(range.start, range.end);
    }
    _sourceRangeForNode(node) {
        return this.sourceRangeForShadyRange(node.range);
    }
    stringify(options = {}) {
        const { prettyPrint = true } = options;
        const beautifulResults = cssbeautify(shadyStringifier.stringify(this.ast), {
            indent: prettyPrint ? '  ' : '',
            autosemicolon: true,
            openbrace: 'end-of-line'
        });
        const indent = '  '.repeat(options.indent || 0);
        return beautifulResults.split('\n')
            .map((line) => line === '' ? '' : indent + line)
            .join('\n') +
            '\n';
    }
    *[Symbol.iterator]() {
        yield* shady.iterateOverAst(this.ast);
    }
}
exports.ParsedCssDocument = ParsedCssDocument;
const shadyStringifier = new shady.Stringifier();
//# sourceMappingURL=css-document.js.map


text:
__author__ = 'gjp'
import datetime
import json
import uuid

import yaml
from fiware_cloto.orion_wrapper import orion_client as orion_client
from fiware_cloto.cloto.utils.log import logger
from django.utils import timezone
from django.core.validators import URLValidator, validate_email
from keystoneclient.exceptions import Conflict
from fiware_cloto.cloto.constants import OPERATIONS, OPERANDS
from fiware_cloto.cloto.models import Rule, RuleModel, ListRuleModel, Entity, SpecificRule, \
    Subscription, SubscriptionModel

class RuleManager():
    """This class provides methods to manage rules.
    """
    #ContextBrokerClient
    orionClient = orion_client.orion_client()

    def get_rule_model(self):
        """Returns model of Rule."""
        return RuleModel

    def get_rule(self, ruleId):
        """Returns information about a general rule."""
        r_query = Rule.objects.get(ruleId__exact=ruleId)
        rule = RuleModel()
        rule.ruleId = r_query.__getattribute__("ruleId")
        rule.name = r_query.__getattribute__("name")
        rule.condition = r_query.__getattribute__("condition")
        rule.action = r_query.__getattribute__("action")
        return rule

    def delete_rule(self, ruleId):
        """Deletes a general rule."""
        r_query = Rule.objects.get(ruleId__exact=ruleId)
        r_query.delete()
        return True

    def get_all_rules(self, tenantId):
        """Returns all general rules of a tenant."""
        dict = list(Rule.objects.filter(tenantId=tenantId).values('ruleId', 'name', 'condition', 'action'))

        mylist = ListRuleModel()
        mylist.tenantId = tenantId
        mylist.rules = dict

        return mylist

    def create_general_rule(self, tenantId, rule):
        """Creates new general rule """
        try:
            condition = self.getContition(rule)
            action = self.getAction(rule)
            name = self.getName(rule)
        except Exception as err:
            raise ValueError(str(err) + " is missing")

        self.checkRule(name, condition, action)

        createdAt = datetime.datetime.now(tz=timezone.get_default_timezone())
        ruleId = uuid.uuid1()
        rule = Rule(ruleId=ruleId, tenantId=tenantId,
                    name=name, condition=condition, action=action, createdAt=createdAt)
        rule.save()
        ruleResult = RuleModel()
        ruleResult.ruleId = str(ruleId)
        return ruleResult

    def update_rule(self, tenantId, ruleId, rule):
        """Updates a general rule """
        rule_db = Rule.objects.get(ruleId__exact=ruleId, tenantId__exact=tenantId)

        try:
            condition = self.getContition(rule)
            action = self.getAction(rule)
            name = self.getName(rule)
        except Exception as err:
            raise ValueError(str(err) + " is missing")

        self.checkRule(name, condition, action)

        rule_db.action = action
        rule_db.name = name
        rule_db.condition = condition
        rule_db.save()
        ruleResult = RuleModel()
        ruleResult.ruleId = str(ruleId)
        ruleResult.name = name
        ruleResult.condition = condition
        ruleResult.action = action
        return ruleResult

    def getContition(self, rule):
        """Splits condition from a rule.

        :param str rule:        The rule description in json format
        """
        condition = yaml.load(rule)['condition']
        return condition

    def getAction(self, rule):
        """Splits action from a rule.

        :param str rule:        The rule description in json format
        """
        action = yaml.load(rule)['action']
        return action

    def getName(self, rule):
        """Splits the name from a rule.

        :param str rule:        The rule description in json format
        """
        name = yaml.load(rule)['name']
        return name

    def create_specific_rule(self, tenantId, serverId, rule):
        """Creates a new specific rule for a server

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str rule:        The rule description in json format
        """
        try:
            entity = Entity.objects.get(serverId__exact=serverId)
        except Entity.DoesNotExist as err:
            entity = Entity(serverId=serverId, tenantId=tenantId)
            entity.save()
        try:
            condition = self.getContition(rule)
            action = self.getAction(rule)
            name = self.getName(rule)
        except Exception as err:
            raise ValueError(str(err) + " is missing")

        self.checkRule(name, condition, action)

        #Its necesary modify action to get subscriptionId
        modifiedAction = self.pimp_rule_action(action, name, serverId)
        modifiedCondition = self.pimp_rule_condition(condition, name, serverId)

        createdAt = datetime.datetime.now(tz=timezone.get_default_timezone())
        ruleId = uuid.uuid1()
        rule = SpecificRule(specificRule_Id=ruleId,
                tenantId=tenantId, name=name, condition=condition, action=action,
                clips_condition=modifiedCondition, clips_action=modifiedAction, createdAt=createdAt)
        """try:
            rule = SpecificRule.objects.get(serverId__exact=serverId, )
            raise ValueError("rule name already exists")
        except Entity.DoesNotExist as err:
            entity = Entity(serverId=serverId, tenantId=tenantId)"""
        rule.save()
        entity.specificrules.add(rule)
        rule.save()
        ruleResult = RuleModel()
        ruleResult.ruleId = str(ruleId)
        logger.info("RuleId %s was created for server %s" % (str(ruleId), serverId))
        return ruleResult

    def update_specific_rule(self, tenantId, serverId, ruleId, rule):
        """Updates a specific rule

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        :param str rule:        The rule description in json format
        """

        rule_db = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId, entity__exact=serverId)
        try:
            condition = self.getContition(rule)
            action = self.getAction(rule)
            name = self.getName(rule)
        except Exception as err:
            raise ValueError(str(err) + " is missing")

        self.checkRule(name, condition, action)

        rule_db.action = action
        rule_db.name = name
        rule_db.condition = condition
        modifiedAction = self.pimp_rule_action(action, name, serverId)
        modifiedCondition = self.pimp_rule_condition(condition, name, serverId)
        rule_db.clips_action = modifiedAction
        rule_db.clips_condition = modifiedCondition
        rule_db.save()
        ruleResult = RuleModel()
        ruleResult.ruleId = str(ruleId)
        ruleResult.name = name
        ruleResult.condition = condition
        ruleResult.action = action
        logger.info("RuleId %s was updated" % str(ruleId))
        return ruleResult

    def get_specific_rule(self, tenantId, serverId, ruleId):
        """Returns information about a specific rule.

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        """
        r_query = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId, entity__exact=serverId)
        rule = RuleModel()
        rule.ruleId = r_query.__getattribute__("specificRule_Id")
        rule.name = r_query.__getattribute__("name")
        rule.condition = r_query.__getattribute__("condition")
        rule.action = r_query.__getattribute__("action")
        return rule

    def get_all_specific_rules(self, tenantId, serverId):
        """Returns all specific rules of a server.

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        """
        entity = Entity.objects.get(serverId=serverId)

        mylist = entity.specificrules.values('specificRule_Id', 'name', 'condition', 'action').iterator()

        dictRules = list()
        for rule in mylist:
            dictRules.append(rule)
        subscr = entity.subscription.values('subscription_Id', 'ruleId').iterator()
        dictSubsc = list()
        for subs in subscr:
            dictSubsc.append(subs)

        mylist = ListRuleModel()
        mylist.tenantId = tenantId
        mylist.rules = dictRules
        mylist.serverId = serverId
        mylist.subscription = dictSubsc

        return mylist

    def delete_specific_rule(self, tenantId, serverId, ruleId):
        """Deletes a specific rule.

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        """
        r_query = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId, entity__exact=serverId)
        r_query.delete()

        #Deleting subscriptions to that rule
        subscriptions = Subscription.objects.filter(ruleId__exact=ruleId)
        subscriptions.delete()
        logger.info("RuleId %s from server %s was deleted" % (ruleId, serverId))
        return True

    def get_all_entities(self, tenantId):
        """Returns all servers with their information.

        :param str tenantId:      The id of the tenant
        """

        servers = Entity.objects.filter(tenantId__exact=tenantId).values('serverId').iterator()
        dictEntities = list()
        for entity in servers:
            s = entity['serverId']
            rules = self.get_all_specific_rules(tenantId, s)
            for rule in rules.rules:
                del rule['action']
                del rule['condition']

            final = ListRuleModel()
            final.rules = rules.rules
            final.serverId = rules.serverId
            dictEntities.append(vars(final))

        mylist = ListRuleModel()
        mylist.servers = dictEntities

        return mylist

    def subscribe_to_rule(self, tenantId, serverId, subscription):
        """Creates a server subscription to a rule.

        :param str tenantId:        The id of the tenant
        :param str serverId:        The id of the server
        :param str subscription:    The subscription description in json format
        """
        context_broker_subscription = False
        try:
            entity = Entity.objects.get(serverId__exact=serverId)
        except Entity.DoesNotExist as err:
            entity = Entity(serverId=serverId, tenantId=tenantId)
            entity.save()
        ruleId = json.loads(subscription)['ruleId']
        SpecificRule.objects.get(specificRule_Id__exact=ruleId, entity__exact=serverId)
        url = json.loads(subscription)['url']
        #Verify that there is no more subscriptions to the rule for that server
        it = entity.subscription.iterator()
        for sub in it:
            if sub.serverId == serverId:
                context_broker_subscription = sub.cbSubscriptionId
            if sub.ruleId == ruleId:
                raise Conflict("Subscription already exists")

        self.verify_url(url)
        if not context_broker_subscription:
            cbSubscriptionId = self.orionClient.contextBrokerSubscription(tenantId, serverId)
        else:
            cbSubscriptionId = context_broker_subscription
        subscription_Id = uuid.uuid1()
        subscr = Subscription(subscription_Id=subscription_Id, ruleId=ruleId, url=url, serverId=serverId,
                              cbSubscriptionId=cbSubscriptionId)
        subscr.save()
        entity.subscription.add(subscr)
        entity.save()
        logger.info("Server %s was subscribed to rule %s: cbSubscriptionId is %s and internal subscription %s"
                        % (serverId, ruleId, cbSubscriptionId, str(subscription_Id)))

        return subscription_Id

    def unsubscribe_to_rule(self, serverId, subscriptionId):
        """Unsuscribe a server from a rule.

        :param str tenantId:        The id of the tenant
        :param str serverId:        The id of the server
        :param str subscriptionId:  The id of the subscription
        """

        r_query = Subscription.objects.get(subscription_Id__exact=subscriptionId, serverId__exact=serverId)
        if Subscription.objects.filter(serverId__exact=serverId).count() == 1:
            self.orionClient.contextBrokerUnSubscription(r_query.cbSubscriptionId, r_query.serverId)
            r_query.delete()
        else:
            r_query.delete()
        logger.info("Server %s was unsubscribed to this subscription: %s"
                        % (serverId, subscriptionId))
        return True

    def get_subscription(self, tenantId, serverId, subscriptionId):
        """Returns information about a subscription.

        :param str tenantId:        The id of the tenant
        :param str serverId:        The id of the server
        :param str subscriptionId:  The id of the subscription
        """

        r_query = Subscription.objects.get(subscription_Id__exact=subscriptionId, serverId__exact=serverId)
        subscription = SubscriptionModel()
        subscription.ruleId = r_query.__getattribute__("ruleId")
        subscription.serverId = r_query.__getattribute__("serverId")
        subscription.url = r_query.__getattribute__("url")
        subscription.subscriptionId = r_query.__getattribute__("subscription_Id")
        return subscription

    def checkRule(self, name, condition, action):
        """Checks if the parts of the rule fulfill the expected character limit

        :param str name:        The name of the rule
        :param str condition:   The description of the condition
        :param str action:      The description of the actions
        """

        try:
            if name.__len__() > 30 or name.__len__() < 3:
                raise ValueError("You must provide a name with length between 3 and 30 characters")
            if condition.__len__() > 1024 or condition.__len__() < 1:
                raise ValueError("You must provide conditions with length between 1 and 1024 characters")
            if action.__len__() > 1024 or action.__len__() < 1:
                raise ValueError("You must provide actions with length between 1 and 1024 characters")
        except ValueError as ex:
            raise ex

    def verify_url(self, url):
        """Checks if the string is valid URL

        :param str url:      The expected url
        """
        validator = URLValidator()
        validator(url)

    def verify_email(self, email):
        """Checks if the string is valid email

        :param str email:      The expected email
        """
        validate_email(email)

    def verify_values(self, name, value, type):
        """Checks if rule operands are expected strings and values are valid floats

        :param str name:        The name
        :param str value:       The value
        :param object type:     The type of the value
        """
        try:
            if value == None or value == "":
                raise ValueError()
            if type == str:
                if name == "operation" and value not in OPERATIONS:
                    raise ValueError
                if "operand" in name and (value not in OPERANDS):
                    raise ValueError
            else:
                if type == float:
                    myfloat = float(value)
                if myfloat < 0.0 or myfloat > 100.0:
                    raise ValueError
        except ValueError:
            raise ValueError("You must provide a valid value and operand for %s" % name)

    def pimp_rule_action(self, action, ruleName, serverId):
        """This method builds a CLIPS rule from data received as json.
        It is necesary to Rule Engine add this String to be able to get the notification url of each Rule subscribed

        :param str action:          The description of the action
        :param str ruleName:        The name of the rule
        :param object serverId:     The id of the server
        """
        try:
            actionName = action['actionName']
            self.verify_values('actionName', actionName, str)
            action_string = "(python-call " + actionName + " \"" + serverId + "\" ?url"

            if actionName == "notify-email":
                email = action['email']
                body = action['body']
                self.verify_email(email)
                self.verify_values("body", body, str)
                action_string += " \"" + body + "\"" " " + email
            if actionName == "notify-scale":
                operation = action['operation']
                self.verify_values("operation", operation, str)
                action_string += " \"" + operation + "\""
            action_string += ")"
            string_to_get_url_subscription = "(bind ?url (python-call get-notification-url \"" + ruleName\
                                             + "\" \"" + serverId + "\"))"
            return string_to_get_url_subscription + action_string
        except ValueError as error:
            raise error
        except KeyError as error:
            raise error

    def pimp_rule_condition(self, condition, ruleName, serverId):
        """This method builds a CLIPS condition from data received as json.

        :param str condition:       The description of the condition
        :param str ruleName:        The name of the rule
        :param object serverId:     The id of the server
        """

        try:
            operands = {"less": "<", "greater": ">", "less equal": "<=", "greater equal": ">="}
            condition_string = "(ServerFact \"" + serverId + "\""

            ##Adding CPU condition
            parameters = ["cpu", "mem", "hdd", "net"]
            for k in parameters:
                self.verify_values(k + " operand", condition[k]["operand"], str)
                self.verify_values(k, condition[k]["value"], float)
                operand = operands[condition[k]["operand"]]
                condition_string += " ?" + k + "&:(" + operand + " ?" + k + " " \
                                    + str(condition[k]["value"]) + ")"
            condition_string += ")"
            return condition_string
        except ValueError as error:
            raise error
        except KeyError as error:
            raise error


text:
//
//  DZBatchRequest.h
//  DZNetworking
//
//  Created by Wenbing Zuo on 5/6/16.
//  Copyright © 2016 DaZuo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DZBaseRequest.h"
@class DZBatchRequest;

typedef void(^DZBatchRequestSuccessCallback)(DZBatchRequest *batchRequest);
typedef void(^DZBatchRequestFailureCallback)(DZBatchRequest *batchRequest, __kindof DZBaseRequest *request, NSError *error);
typedef void(^DZBatchRequestCancelCallback)(DZBatchRequest *batchRequest);

@interface DZBatchRequest : NSObject

@property (nonatomic, strong, readonly) NSArray *requests;

/**
 A flag to indicate whether cancel the rest request or not when error occurs.
 Default is YES.
 */
@property (nonatomic, assign) BOOL cancelWhenErrorOccur;

@property (nonatomic, strong) dispatch_queue_t completionQueue;

- (void)addAccessory:(id<DZRequestAccessory>)accessory;

@property (nonatomic, copy) DZBatchRequestSuccessCallback successCallback;
@property (nonatomic, copy) DZBatchRequestFailureCallback failureCallback;
- (void)setSuccesssCallback:(DZBatchRequestSuccessCallback)success failureCallback:(DZBatchRequestFailureCallback)failure;

- (void)start;
- (void)startBatchReqeustSuccessCallback:(DZBatchRequestSuccessCallback)success failureCallback:(DZBatchRequestFailureCallback)failure;

@property (nonatomic, copy) DZBatchRequestCancelCallback cancelCallback;
- (void)cancel;
- (void)cancelWithCallback:(DZBatchRequestCancelCallback)cancel;

///---------------------
/// @name Initialization
///---------------------

- (instancetype)initWithRequests:(NSArray<DZBaseRequest *>*) requests;

@end

@interface DZBatchRequestManager : NSObject

+ (instancetype)sharedManager;

- (void)addBatchRequest:(DZBatchRequest *)batchRequest;

- (void)removeBatchRequest:(DZBatchRequest *)batchRequest;

@end


text: PRAGMA locking_mode = exclusive


text:
package com.sequenceiq.cloudbreak.cloud.gcp.client;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.sequenceiq.cloudbreak.cloud.event.credential.CredentialVerificationException;
import com.sequenceiq.cloudbreak.cloud.model.CloudCredential;

@Service
public class GcpIamFactory extends GcpServiceFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(GcpIamFactory.class);

    @Inject
    private JsonFactory jsonFactory;

    @Inject
    private GcpCredentialFactory gcpCredentialFactory;

    @Inject
    private HttpTransport httpTransport;

    public Iam buildIam(CloudCredential gcpCredential) {
        try {
            GoogleCredential credential = gcpCredentialFactory.buildCredential(gcpCredential, httpTransport);
            return new Iam.Builder(httpTransport, jsonFactory, requestInitializer(credential))
                    .setApplicationName(gcpCredential.getName())
                    .build();
        } catch (Exception e) {
            LOGGER.warn("Error occurred while building Google Compute access.", e);
            throw new CredentialVerificationException("Error occurred while building Google Compute access.", e);
        }
    }
}


text:
/*
 * \brief
 * \author Sylvain Jaume, Francois Huguet
 */

#include "SoVtkExtractCTHPart.h"
#include "SoVtkUtils.h"

#include "vtkMultiProcessController.h"
#include "vtkPlane.h"
#include "vtkAlgorithmOutput.h"
#include "vtkPolyData.h"
#include "vtkMultiBlockDataSet.h"

SO_ENGINE_SOURCE( SoVtkExtractCTHPart )

SoVtkExtractCTHPart::SoVtkExtractCTHPart()
{
	SO_ENGINE_CONSTRUCTOR(SoVtkExtractCTHPart);

	mObject = vtkExtractCTHPart::New();
	mObject->Register(0);
	mObject->SetGlobalWarningDisplay(0);

	vtkExtractCTHPart *aExtractCTHPart = vtkExtractCTHPart::New();
	double *x = 0;
	int *y = 0;
	float *z = 0;

	SO_ENGINE_ADD_INPUT(Controller, (0));

	SO_ENGINE_ADD_INPUT(VolumeArrayName, (""));

	SO_ENGINE_ADD_INPUT(ClipPlane, (0));

	SO_ENGINE_ADD_INPUT(InputConnection, (0));

	aExtractCTHPart->Delete();

	SO_ENGINE_ADD_OUTPUT( oController, SoSFVtkObject );
	mController = 0;
	SO_ENGINE_ADD_OUTPUT( Output, SoSFVtkObject );
	mOutput = 0;
	SO_ENGINE_ADD_OUTPUT( OutputPort, SoSFVtkAlgorithmOutput );
	mOutputPort = 0;

	addCalled = 0;
}

SoVtkExtractCTHPart::~SoVtkExtractCTHPart()
{
	// Deletion of the objects if they exist
	if ( mController )
	{

		mController->unref();
		mController = 0;
	}

	if ( mOutput )
	{

		mOutput->unref();
		mOutput = 0;
	}

	if ( mOutputPort )
	{

		mOutputPort->unref();
		mOutputPort = 0;
	}

	if ( mObject )
	{
		mObject->UnRegister(0);
		mObject->Delete();
		mObject = 0;
	}

}

void SoVtkExtractCTHPart::initClass()
{
	SO_ENGINE_INIT_CLASS( SoVtkExtractCTHPart, SoEngine, "Engine" );
}

void SoVtkExtractCTHPart::evaluate()
{
	try
	{
		// Get the input type(s)
		SoVtkAlgorithmOutput *inputPortPtr = InputConnection.getValue();

		if (inputPortPtr)
			mObject->SetInputConnection(inputPortPtr->getPointer());

		// Deletion of the objects if they exist
		if ( mController )
		{

			mController->unref();
			mController = 0;
		}

		if ( mOutput )
		{

			mOutput->unref();
			mOutput = 0;
		}

		if ( mOutputPort )
		{

			mOutputPort->unref();
			mOutputPort = 0;
		}

		if ( addCalled )
		{
			reset();
			addCalled = 0;
		}

		mObject->GetController();
		mController = new SoVtkObject();
		mController->ref();
		mController->setPointer( mObject->GetController() );

		mObject->GetOutput()->Register(0);
		mOutput = new SoVtkObject();
		mOutput->ref();
		mOutput->setPointer( mObject->GetOutput() );

		if ( mObject->GetNumberOfOutputPorts() > 0 )
		{
			mObject->GetOutputPort()->Register(0);
			mOutputPort = new SoVtkAlgorithmOutput();
			mOutputPort->ref();
			mOutputPort->setPointer( mObject->GetOutputPort() );
		}

	}
	catch(...)
	{
		SoDebugError::post( __FILE__, "Unknown Exception" );
		return;
	}
	SO_ENGINE_OUTPUT( oController, SoSFVtkObject, setValue( mController ) );
	SO_ENGINE_OUTPUT( Output, SoSFVtkObject, setValue( mOutput ) );
	SO_ENGINE_OUTPUT( OutputPort, SoSFVtkAlgorithmOutput, setValue( mOutputPort ) );
}

void SoVtkExtractCTHPart::inputChanged(SoField * f)
{
	// Get the Controller value
	if ( f == &Controller )
		SO_VTK_SET_FIELD_DATA( mObject, Controller, vtkMultiProcessController);

	// Get the VolumeArrayName value
	if ( f == &VolumeArrayName )
		addCalled = 1;
	// Get the ClipPlane value
	if ( f == &ClipPlane )
		SO_VTK_SET_FIELD_DATA( mObject, ClipPlane, vtkPlane);

	mObject->Update();
}

void SoVtkExtractCTHPart::reset()
{
	mObject->UnRegister(0);
	mObject->Delete();
	mObject = 0;
	mObject = vtkExtractCTHPart::New();
	mObject->Register(0);
	mObject->SetGlobalWarningDisplay(0);
	// Get the input type(s)
	SoVtkAlgorithmOutput *inputPortPtr = InputConnection.getValue();

	if (inputPortPtr)
		mObject->SetInputConnection(inputPortPtr->getPointer());

	// Get the Controller value

		SO_VTK_SET_FIELD_DATA( mObject, Controller, vtkMultiProcessController);

	// Get the VolumeArrayName value

		SO_VTK_ADD_FIELD_MFSTRING( mObject, VolumeArrayName);

	// Get the ClipPlane value

		SO_VTK_SET_FIELD_DATA( mObject, ClipPlane, vtkPlane);

	mObject->Update();
}


text:
devices = new (function() {

this.backends_ = [];  // ['Android', 'Linux']
this.devices_ = {};  // 'Android/a1b2' -> {.backend, .name, .id}
this.selDeviceUri_ = null;

this.onDomReady_ = function() {
  $('#refresh-devices').on('click', this.refresh.bind(this));
  $('#devices').on('change', this.onDeviceSelectionChange_.bind(this));
  this.refresh();
};

this.getSelectedURI = function() {
  return this.selDeviceUri_;
};

this.getSelectedDevice = function() {
  if (!this.selDeviceUri_)
    return null;
  return this.devices_[this.selDeviceUri_];
};

this.getAllBackends = function() {
  // Returns a list of the registered backends, e.g., ['Android', 'Linux'].
  return this.backends_;
};

this.getAllDevices = function() {
  // Returns a list of devices [{backend:'Android', name:'N7', id:'1234'}].
  return Object.keys(this.devices_).map(function(k) {
    return this.devices_[k];
  }, this);
};

this.refresh = function() {
  webservice.ajaxRequest('/devices', this.onDevicesAjaxResponse_.bind(this));
  webservice.ajaxRequest('/backends', this.onBackendsAjaxResponse_.bind(this));
};

this.onBackendsAjaxResponse_ = function(data) {
  if (!data || !data.length)
  {
    rootUi.showDialog('No backends detected! Memory Inspector looks terribly' +
                       ' broken. Please file a bug');
  }
  this.backends_ = data;
};

this.onDevicesAjaxResponse_ = function(data) {
  var devList = $('#devices');
  devList.empty();
  this.devices_ = {};
  data.forEach(function(device) {
    var deviceUri = device.backend + '/' + device.id;
    var deviceFullTime = device.backend + ' : ' +
                         device.name + ' [' + device.id + ']';
    devList.append($('<option/>').val(deviceUri).text(deviceFullTime));
    this.devices_[deviceUri] = device;
  }, this);

  if (data.length > 0) {
    this.onDeviceSelectionChange_();  // Start monitoring the first device.
  } else {
    rootUi.showDialog('No devices could be detected. Check the settings tab ' +
                      'to ensure that the adb path is properly configured.');
  }
};

this.onDeviceSelectionChange_ = function() {
  this.selDeviceUri_ = $('#devices').val();
  if (!this.selDeviceUri_)
    return;

  this.initializeSelectedDevice(false);
};

this.initializeSelectedDevice = function(enableNativeTracing) {
  webservice.ajaxRequest(
      '/initialize/' + this.selDeviceUri_,
      this.onDeviceInitializationComplete_.bind(this),
      null,  // default error handler.
      {enableNativeTracing: (enableNativeTracing ? '1' : '')});
};

this.onDeviceInitializationComplete_ = function(data) {
  this.devices_[this.selDeviceUri_].isNativeTracingEnabled =
     data.isNativeTracingEnabled;
  processes.startPsTable();
  processes.startDeviceStats();
};

$(document).ready(this.onDomReady_.bind(this));

})();


text:
package fr.bmartel.protocol.http;

/**
 * Http version builder and parser
 *
 * @author Bertrand Martel
 *
 */
public class HttpVersion {

	/** version first digit (before ".") */
	public int versionDigit1;

	/** version second digit */
	public int versionDigit2;

	/**
	 * Http version builder according to two digit parameters (RFC)
	 *
	 * @param versionDigit1
	 * @param versionDigit2
	 */
	public HttpVersion(int versionDigit1, int versionDigit2) {
		this.versionDigit1 = versionDigit1;
		this.versionDigit2 = versionDigit2;
	}

	/**
	 * Parser for http version
	 *
	 * @param stringToParse
	 *            http request to parse
	 */
	public HttpVersion(String stringToParse) {
		if (stringToParse.startsWith("HTTP/")
				&& stringToParse.length() > "HTTP/".length() + 2) {
			int version1 = Integer.parseInt(stringToParse.substring(
					stringToParse.indexOf('/') + 1,
					stringToParse.indexOf('/') + 2));
			int version2 = Integer.parseInt(stringToParse.substring(
					stringToParse.indexOf('/') + 3,
					stringToParse.indexOf('/') + 4));
			this.versionDigit1 = version1;
			this.versionDigit2 = version2;
		}
	}

	/**
	 * format http version according to RFC
	 */
	public String toString() {
		return "HTTP/" + this.versionDigit1 + "." + this.versionDigit2;
	}
}


text:
'use strict';
var D = require('dual');

function createSingleClassHandler(cssClass, classAsset) {
    return function(value) {
        var asset = classAsset ? this.assets[classAsset] : this.$;
        if (value) {
            asset.addClass(cssClass);
        } else {
            asset.removeClass(cssClass);
        }
    };
}

function createHtmlAttributeHandler(htmlAttribute, htmlAttributeAsset) {
    return function(value) {
        var asset = htmlAttributeAsset ? this.assets[htmlAttributeAsset] : this.$;
        asset.setAttribute(htmlAttribute, value);
    };
}

function createTextHandler(textAsset) {
    return function(value) {
        var asset = textAsset ? this.assets[textAsset] : this.$;
        asset.setText(value);
    };
}

function createClassMapHandler(classMap, classAsset) {

    var valuesToClasses = [];
    for (var cssClass in classMap) {
        if (!classMap.hasOwnProperty(cssClass)) {
            continue;
        }

        valuesToClasses.push([cssClass, classMap[cssClass]]);
    }

    return function(value) {
        var asset = classAsset ? this.assets[classAsset] : this.$;

        for (var i = 0; i < valuesToClasses.length; i++) {
            var valueToClass = valuesToClasses[i];
            var matchValue = valueToClass[0];
            var className = valueToClass[1];
            if ('' + matchValue === '' + value) {
                asset.addClass(className);
            } else {
                asset.removeClass(className);
            }
        }
    };
}

function createHandlersRunner(handlers) {
    return function(value) {
        for (var i = 0; i < handlers.length; i++) {
            handlers[i].call(this, value);
        }
    };
}

function isString(val) {
    return Object.prototype.toString.call(val) === '[object String]';
}

//--------------------------------------------------------------------

module.exports = D.Widget.extend({

}, {
    extend: function(protoProps, staticProps) {
        var newConstructor = D.Widget.extend.call(this, protoProps, staticProps);
        var proto = newConstructor.prototype;
        var attrs = proto.ATTRS || {};
        for (var attr in attrs) {
            var desc = attrs[attr];

            var applierName = desc.applierName || 'applyAttribute_' + attr;
            if ('function' === typeof(proto[applierName])) {
                continue; //already exists
            }

            var handlers = [];

            if (desc) {

                if (desc.cssClass) {
                    if (isString(desc.cssClass)) {
                        handlers.push(
                            createSingleClassHandler(desc.cssClass, desc.cssClassAsset));
                    } else {
                        handlers.push(
                            createClassMapHandler(desc.cssClass, desc.cssClassAsset));
                    }
                }

                if (desc.htmlAttribute) {
                    handlers.push(
                        createHtmlAttributeHandler(desc.htmlAttribute, desc.htmlAttributeAsset));
                }

                if (desc.textAsset !== undefined) {
                    handlers.push(
                        createTextHandler(desc.textAsset));
                }
            }

            proto[applierName] = createHandlersRunner(handlers);
        }
        return newConstructor;
    }
});


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>owl.js</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700" type="text/css">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/cayman.css">
    <link rel="stylesheet" href="css/prism.css">

owl.js

Backbone-like frontend library
View on GitHubView on npm

Main

owl.Collection.js

owl.Controller.js

owl.Model.js

owl.Promise.js

owl.Router.js

owl.View.js

owl.ajax.js

owl.history.js

owl.js

owl.util.js

owl.js

Backbone-like frontend library

Ask a question in gitter.

Install

Bower

bower install owl.js

npm

npm install owl.js

Features

Languages: ES5, ES6, TypeScript.

Modules: CommonJS, amd.

Libraries: React.

Examples

To start examples server

cd examples
npm start

Concept

owl.js is simple library similar to backbone.js, without dependency on underscore.js and jQuery.
If you know backbone.js you mostly know owl.js.

The library uses MVC as main pattern.
owl.Model is responsible for representing data from server based on REST architecture.
owl.View is responsible for rendering view it can use any template engine to do it or generate DOM manually.
owl.Controller is responsible for business logic.

Also there is few classes out of the main pattern.

owl.Router is created to manage pages based on URL.
It contains records named routes.
Each route contains path and a controller that will be called for specified path.

owl.Collection is an array of owl.Models it is created to represent model sets.

In is not necessary to use all of those classes, for example you can use React components instead of owl.View.

Development

Run unit tests

karma start

or

npm test

Cayman is maintained by iwatakeshi.

This page was generated by Mr. Doc using the Cayman theme by Jason Long.


text:
import os
from io import open
from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname), encoding='utf-8').read()

setup(
    name="zerodark",
    version='0.0.1',
    description="Monitoring and analysis",
    long_description=read('readme.md'),
    classifiers=[
        "Topic :: System :: Systems Administration",
        "Topic :: System :: Distributed Computing"
    ],
    url="https://github.com/cloud-custodian/cloud-custodian",
    author="Kapil Thangavelu",
    license="Apache-2.0",
    packages=find_packages(),
    entry_points={
        'console_scripts': [
            'zero-metrics = zerodark.metrics:cli',
            'zero-ipdb = zerodark.ipdb:cli',
            'zero-flow = zerodark.floweni:cli']},
    install_requires=[
        "boto3>=1.4.7",
        "botocore>=1.7.37",
        "pyyaml",
        "sqlalchemy",
        "humanize",
        "c7n_org",
        "c7n",
        "jsonschema",
        "click",
        "tabulate",
        "influxdb",
        "ipaddress"
    ],
)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Plans extends CI_Controller {

	public function index() {
		redirect('/');
	}

	public function create() {
		$plan = $this->input->post(array('title', 'total'), TRUE);
		$this->plan->new_plan($plan);
		redirect('/');
	}

	public function get($plan_id) {
		$this->plan->id($plan_id);
		$this->load->view('header');
		$this->load->view('plan');
		$this->load->view('footer');
	}

	public function deposit($payment_id) {
		$this->db->set('complete', true);
		$this->db->set('payment_date', date('Y-m-d'));
		$this->db->where('id', $payment_id);
		$this->db->update('payments');
		$plan_id = $this->db->get_where('payments', array('id' => $payment_id))->row('plan_id');
		redirect('/plans/'.$plan_id);
	}
}


text:
package com.google.android.libraries.remixer.ui.widget;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import android.view.LayoutInflater;
import android.widget.Switch;
import android.widget.TextView;
import com.google.android.libraries.remixer.BooleanVariableBuilder;
import com.google.android.libraries.remixer.Callback;
import com.google.android.libraries.remixer.Variable;
import com.google.android.libraries.remixer.ui.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

@RunWith(RobolectricTestRunner.class)
@Config(
    sdk = 21,
    manifest = "src/main/AndroidManifest.xml",
    packageName = "com.google.android.libraries.remixer.ui")
public class BooleanVariableWidgetTest {
  private static final String TITLE = "Some boolean";
  private static final String KEY = "theboolean";
  private static final boolean DEFAULT_VALUE = false;

  @Mock
  Callback<Boolean> mockCallback;

  private Variable<Boolean> variable;
  private BooleanVariableWidget view;
  private TextView name;
  private Switch variableSwitch;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    variable = new BooleanVariableBuilder()
        .setInitialValue(DEFAULT_VALUE)
        .setTitle(TITLE)
        .setKey(KEY)
        .setContext(this)
        .setCallback(mockCallback)
        .build();
    view = (BooleanVariableWidget) LayoutInflater.from(RuntimeEnvironment.application)
        .inflate(R.layout.boolean_variable_widget, null);
    view.bindVariable(variable);
    variableSwitch = (Switch) view.findViewById(R.id.variableSwitch);
    name = (TextView) view.findViewById(R.id.variableName);
  }

  @Test
  public void defaultIsShown() {
    assertEquals(TITLE, name.getText());
    assertEquals(DEFAULT_VALUE, variableSwitch.isChecked());
  }

  @Test
  public void callbackIsCalled() {
    // Check that the callback  was called. This should've happened during setUp()
    verify(mockCallback, times(1)).onValueSet(variable);
    variableSwitch.toggle();
    // After changing the text, check that the callback was called once again
    verify(mockCallback, times(2)).onValueSet(variable);
  }

  @Test
  public void callbackIsCalledOnNameClick() {
    // Check that the callback  was called. This should've happened during setUp()
    verify(mockCallback, times(1)).onValueSet(variable);
    name.performClick();
    // After changing the text, check that the callback was called once again
    verify(mockCallback, times(2)).onValueSet(variable);
  }
}


text:
require 'request_handler/concerns/config_helper'

module RequestHandler
  class BaseParser
    include RequestHandler::Concerns::ConfigHelper
  end
end


text:
#include <aws/waf/model/DeleteLoggingConfigurationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::WAF::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteLoggingConfigurationRequest::DeleteLoggingConfigurationRequest() :
    m_resourceArnHasBeenSet(false)
{
}

Aws::String DeleteLoggingConfigurationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_resourceArnHasBeenSet)
  {
   payload.WithString("ResourceArn", m_resourceArn);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DeleteLoggingConfigurationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSWAF_20150824.DeleteLoggingConfiguration"));
  return headers;

}


text:
LobbySystem::LobbySystem() : EntitySystem (SystemType::LobbySystem),
	DataSource("connectedPlayers")
{
	m_tableName = "lobbyPanel";

	for(int i = 0; i < MAXPLAYERS; i++)
	{
		resetPlayer(i);
	}
	m_connectPlayers = 0;
	NotifyRowAdd(m_tableName,0,MAXPLAYERS);
}

void LobbySystem::resetPlayer( int p_playerId )
{
	m_players[p_playerId].playerName	= "open";
	m_players[p_playerId].ping			= -1;
	m_players[p_playerId].ready			= false;
}

void LobbySystem::GetRow( Rocket::Core::StringList& row, const Rocket::Core::String& table,
						 int row_index, const Rocket::Core::StringList& columns )
{
	if(table == m_tableName){
		for (int col_index = 0; col_index < columns.size(); col_index++)
		{
			if (columns[col_index] == "playerName")
			{
				row.push_back(m_players[row_index].playerName.c_str());
			}
			else if (columns[col_index] == "ping")
			{
				row.push_back(toString(m_players[row_index].ping).c_str());
			}
			else if (columns[col_index] == "ready")
			{
				if(m_players[row_index].ready){
					row.push_back("Yes");
				}
				else{
					row.push_back("No");
				}
			}
		}
	}
}

int LobbySystem::GetNumRows( const Rocket::Core::String& table )
{
	return MAXPLAYERS;
}

void LobbySystem::process()
{

}

void LobbySystem::initialize()
{

}

void LobbySystem::updateRow( int p_row, const LobbyStats& p_stats )
{
	m_players[p_row].playerName = p_stats.playerName;
	m_players[p_row].ping		= p_stats.ping;
	m_players[p_row].ready		= p_stats.ready;
	NotifyRowChange(m_tableName, p_row, 1);
}

void LobbySystem::setPlayerReady( int p_playerId, bool p_ready )
{
	m_players[p_playerId].ready	= p_ready;
	NotifyRowChange(m_tableName, p_playerId, 1);
}

void LobbySystem::addNewPlayer( const NewlyConnectedPlayerPacket& p_packet )
{
	m_players[p_packet.playerID].playerName = p_packet.playerName;
	m_players[p_packet.playerID].ping		= p_packet.playerID;
	m_players[p_packet.playerID].ready		= false;

	NotifyRowChange(m_tableName,p_packet.playerID, 1);
}

void LobbySystem::removePlayer( const DisconnectPacket& p_packet )
{
	resetPlayer(p_packet.playerID);
	NotifyRowChange(m_tableName, p_packet.playerID, 1);
}

void LobbySystem::resetAllPlayers()
{
	for(int i = 0; i < MAXPLAYERS; i++)
	{
		resetPlayer(i);
	}
	NotifyRowChange(m_tableName,0,MAXPLAYERS);
}

bool LobbySystem::isPlayerReady( int p_playerId ) const
{
	return m_players[p_playerId].ready;
}

void LobbySystem::setAllPlayersReady( bool p_ready )
{
	for(int i = 0; i < MAXPLAYERS; i++)
	{
		m_players[i].ready = p_ready;
	}
	NotifyRowChange(m_tableName,0,MAXPLAYERS);
}

void LobbySystem::updatePing( int p_playerId, int p_ping )
{
	m_players[p_playerId].ping = p_ping;
	NotifyRowChange(m_tableName, p_playerId, 1);
}


text:
<!DOCTYPE html>
<meta charset="utf-8" />

  <title>Reflections - Reflections</title>

  <meta name="description" content="Default Page Description" />

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="http://blog.shiv.me/css/latex.css" />
<link rel="stylesheet" href="http://blog.shiv.me/css/main.css" />

<meta name="generator" content="Hugo 0.75.1" />

Reflections

Shiva Velmurugan

Abstract

                  I'm a product manager by day, and programmer by night. I am intrigued by abstraction, programming languages and organizing data.

GReader just saved me a lot of time

  Aug 14, 2009

Google reader is one of Google’s products, that didn’t you didn’t realize you needed until you started using it. Heck, pretty much every product they do is in that category. It is one app where I spend a lot of time every day. That is how I still manage to read blogs. Even after twitter and facebook and friendfeed, GReader is still the place, where you can truly control the signal vs noise ratio of content that you read.

        Read More

\[Jason\] The Case Against Apple--in Five Parts

  Aug 8, 2009

Hi Jason,
I was writing a post very much on the same lines, when I read your mail. I’m on my 3rd ipod, 1st iphone and 2nd MBP (one which I ordered just last week). I don’t think I can in the right mind buy another iphone or ipod for the amount of control that apple gets.
1. Absolutely. This is a no-brainer, that I’m frankly surprised that Steve Jobs does not see?

        Read More

Map of the internet circa 2006

  Aug 6, 2009

Some fun things, and some cute ones too

  Aug 5, 2009

I’m pretty sure that I am violating some copyright by posting these here but they really are good. (I found these on a facebook album shared by someone I know - thank you if you know who you are). I did several searches on google and bing and couldn’t trace any restrictions. If you have problems with it, let me know.
  See and download the full gallery on posterous

        Read More

Some fun things, and some cute ones too

  Aug 5, 2009

I’m pretty sure that I am violating some copyright by posting these here but they really are good. (I found these on a facebook album shared by someone I know - thank you if you know who you are). I did several searches on google and bing and couldn’t trace any restrictions. If you have problems with it, let me know.
  See and download the full gallery on posterous

        Read More

          ← Newer

          Older →

        Powered By Hugo / Theme HugoTeX

        Shiva Velmurugan
        ©
        2016


text:
module AuthN
  module Activation
    module ActionMailer

      private

      def activation_mail

      end
    end
  end
end


text:
// SAX DTD handler.
// No warranty; no copyright -- use this as you will.
// $Id: DTDHandler.java 233605 2001-11-06 18:33:40Z hannes $

package org.xml.sax;

/**
  * Receive notification of basic DTD-related events.
  *
  *
If a SAX application needs information about notations and
  * unparsed entities, then the application implements this
  * interface and registers an instance with the SAX parser using
  * the parser's setDTDHandler method.  The parser uses the
  * instance to report notation and unparsed entity declarations to
  * the application.

  *
  *
The SAX parser may report these events in any order, regardless
  * of the order in which the notations and unparsed entities were
  * declared; however, all DTD events must be reported after the
  * document handler's startDocument event, and before the first
  * startElement event.

  *
  *
It is up to the application to store the information for
  * future use (perhaps in a hash table or object tree).
  * If the application encounters attributes of type "NOTATION",
  * "ENTITY", or "ENTITIES", it can use the information that it
  * obtained through this interface to find the entity and/or
  * notation corresponding with the attribute value.

  *
  *
The HandlerBase class provides a default implementation
  * of this interface, which simply ignores the events.

  *
  * @author David Megginson (ak117@freenet.carleton.ca)
  * @version 1.0
  * @see org.xml.sax.Parser#setDTDHandler
  * @see org.xml.sax.HandlerBase
  */
public interface DTDHandler {

  /**
    * Receive notification of a notation declaration event.
    *
    *
It is up to the application to record the notation for later
    * reference, if necessary.

    *
    *
If a system identifier is present, and it is a URL, the SAX
    * parser must resolve it fully before passing it to the
    * application.

    *
    * @param name The notation name.
    * @param publicId The notation's public identifier, or null if
    *        none was given.
    * @param systemId The notation's system identifier, or null if
    *        none was given.
    * @exception org.xml.sax.SAXException Any SAX exception, possibly
    *            wrapping another exception.
    * @see #unparsedEntityDecl
    * @see org.xml.sax.AttributeList
    */
  public abstract void notationDecl (String name,
				     String publicId,
				     String systemId)
    throws SAXException;

  /**
    * Receive notification of an unparsed entity declaration event.
    *
    *
Note that the notation name corresponds to a notation
    * reported by the notationDecl() event.  It is up to the
    * application to record the entity for later reference, if
    * necessary.

    *
    *
If the system identifier is a URL, the parser must resolve it
    * fully before passing it to the application.

    *
    * @exception org.xml.sax.SAXException Any SAX exception, possibly
    *            wrapping another exception.
    * @param name The unparsed entity's name.
    * @param publicId The entity's public identifier, or null if none
    *        was given.
    * @param systemId The entity's system identifier (it must always
    *        have one).
    * @param notation name The name of the associated notation.
    * @see #notationDecl
    * @see org.xml.sax.AttributeList
    */
  public abstract void unparsedEntityDecl (String name,
					   String publicId,
					   String systemId,
					   String notationName)
    throws SAXException;

}


text:
Starter code for transpiling ES2015 (including modules) with Babel, Gulp and Browserify.

# Installing

1. Clone the repo
2. `npm install -g gulp` to install Gulp globally.
3. `npm install` to resolve project dependencies.

# Using

Run `npm start` from the command line and you are good to go!

The project is currently setup to transpile code under the _/src_ folder using the _/src/app.js_ file as an entry point.

Our resulting code ends up in the `public` directory.

# Watch the videos
- [Add a Build System to a React Application](https://www.codeschool.com/screencasts/add-a-build-system-to-a-react-application)
- [ES2015 and the Virtual DOM in a React Application](https://www.codeschool.com/screencasts/es2015-and-the-virtual-dom-in-a-react-application)
- [Add a Router to a React Application](https://www.codeschool.com/screencasts/add-a-router-to-a-react-application)

_A Code School subscription is required before watching the videos. Don't have one yet? [Sign up today!](https://www.codeschool.com/pricing)_