text:
package main

import (
	"bytes"
	"flag"
	"fmt"
	"github.com/BjornTwitchBot/gainesvillemls-scraper/Godeps/_workspace/src/github.com/garyburd/redigo/redis"
	"github.com/BjornTwitchBot/gainesvillemls-scraper/Godeps/_workspace/src/golang.org/x/net/html"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"sync"
)

func main() {
	if os.Getenv("REDIS_HOST_PORT") == "" {
		log.Fatal("REDIS_HOST_PORT not set")
	}
	if os.Getenv("REDIS_PASSWORD") == "" {
		log.Fatal("REDIS_PASSWORD not set")
	}
	if os.Getenv("SENDGRID_API_TOKEN") == "" {
		log.Fatal("SENDGRID_API_TOKEN not set")
	}
	if os.Getenv("EMAIL_FROM_ADDRESS") == "" {
		log.Fatal("EMAIL_FROM_ADDRESS not set")
	}
	if os.Getenv("EMAIL_TO_ADDRESS") == "" {
		log.Fatal("EMAIL_TO_ADDRESS not set")
	}

	flag.Parse()
	// Instantiate redis connection pool
	pool = newPool(*redisServer, *redisPassword)
	poolErr := pool.Get().Err()
	// Check redis connection
	if poolErr != nil {
		log.Fatalf("Something went wrong connecting to Redis! Error is '%s'", poolErr)
	}

	MLSPrices := getMLSPrices()
	populateListings(MLSPrices)
	MLSNumbers := returnMLSNumbers(MLSPrices)
	MLSURLs := getMLSDetails(MLSNumbers)
	fmt.Println(MLSURLs)
	if len(MLSURLs) > 0 {
		sendEmail(os.Getenv("EMAIL_TO_ADDRESS"), MLSURLs)
	} else {
		fmt.Println("No New Listings")
	}
}

func returnMLSNumbers(MLSNumberPrices []string) []string {
	MLSNumbers := []string{}
	for _, MLSPrice := range MLSNumberPrices {
		MLSNumbers = append(MLSNumbers, strings.Split(MLSPrice, "_")[0])
	}
	return MLSNumbers
}

func filterOldListings(listings []string) []string {
	redisConn := pool.Get()
	defer redisConn.Close()

	filteredListings := []string{}

	for _, listing := range listings {
		redisReply, redisError := redis.Bool(redisConn.Do("EXISTS", listing))
		if redisError != nil {
			log.Fatalf("Error reading redis data '%s'", redisError)
		}
		if redisReply == false {
			filteredListings = append(filteredListings, listing)
		}
	}
	return filteredListings
}

func populateListings(listings []string) {
	redisConn := pool.Get()
	defer redisConn.Close()

	for _, listing := range listings {
		_, redisError := redisConn.Do("SET", listing, "true")
		if redisError != nil {
			log.Fatalf("Error inserting data into redis '%s'", redisError)
		}
	}
}

func getMLSPrices() []string {
	MLSNums := []string{}

	searchURL := "https://www.gainesvillemls.com"
	searchPath := "/gan/idx/search.php"

	data := url.Values{}
	data.Set("LM_MST_prop_fmtYNNT", "1")
	data.Add("LM_MST_prop_cdYYNT", "1,9,10,11,12,13,14")
	data.Add("LM_MST_mls_noYYNT", "")
	// Minimum Price
	data.Add("LM_MST_list_prcYNNB", "60000")
	// Maximum Price
	data.Add("LM_MST_list_prcYNNE", "160000")
	data.Add("LM_MST_prop_cdYNNL[]", "9")
	// Minimum Square Footage
	data.Add("LM_MST_sqft_nYNNB", "")
	// Maximum Square Footage
	data.Add("LM_MST_sqft_nYNNE", "")
	// Minimum Year Built
	data.Add("LM_MST_yr_bltYNNB", "")
	// Maximum Year Built
	data.Add("LM_MST_yr_bltYNNE", "")
	// Minimum Bedrooms
	data.Add("LM_MST_bdrmsYNNB", "3")
	// Maximum Bedrooms
	data.Add("LM_MST_bdrmsYNNE", "")
	// Minimum Bathrooms
	data.Add("LM_MST_bathsYNNB", "2")
	// Maximum Bathrooms
	data.Add("LM_MST_bathsYNNE", "")
	data.Add("LM_MST_hbathYNNB", "")
	data.Add("LM_MST_hbathYNNE", "")
	// County
	data.Add("LM_MST_countyYNCL[]", "ALA")
	data.Add("LM_MST_str_noY1CS", "")
	data.Add("LM_MST_str_namY1VZ", "")
	data.Add("LM_MST_remarksY1VZ", "")
	data.Add("openHouseStartDt_B", "")
	data.Add("openHouseStartDt_E", "")
	data.Add("ve_info", "")
	data.Add("ve_rgns", "1")
	data.Add("LM_MST_LATXX6I", "")
	data.Add("poi", "")
	data.Add("count", "1")
	data.Add("key", "52633f4973cf845e55b18c8e22ab08d5")
	data.Add("isLink", "0")
	data.Add("custom", "")

	u, _ := url.ParseRequestURI(searchURL)
	u.Path = searchPath
	urlStr := fmt.Sprintf("%v", u)

	client := &http.Client{}
	request, requestErr := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
	if requestErr != nil {
		log.Fatalf("Problem creating new httpRequest", "%s", requestErr)
	}
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	request.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36")
	request.Header.Add("Accept", "*/*")
	request.Header.Add("Accept-Language", "en-US,en;q=0.8")
	request.Header.Add("Accept-Encoding", "gzip, deflate")
	request.Header.Add("Referer", "https://www.gainesvillemls.com/gan/idx/index.php?key=52633f4973cf845e55b18c8e22ab08d5")
	request.Header.Add("X-Requested-With", "XMLHttpRequest")

	resp, responseError := client.Do(request)
	if responseError != nil {
		log.Fatalf("Problem getting http response", "%s", responseError)
	}

	responseBody := resp.Body
	if resp.StatusCode != 200 {
		log.Fatalf("Response status not 200: %v, %v", resp.StatusCode, resp.Status)
	}
	defer responseBody.Close()

	parsedHTML := html.NewTokenizer(responseBody)

	MLSNumber := ""
	MLSFlag := false
	Price := ""
	PriceFlag := false
	cityFlag := false

	for {
		tt := parsedHTML.Next()
		switch {
		case tt == html.ErrorToken:
			return filterOldListings(MLSNums)
		case tt == html.StartTagToken:
			t := parsedHTML.Token()
			if t.String() == `<span class="mls">` {
				MLSFlag = true
			}
			if t.String() == `<span class="price">` {
				PriceFlag = true
			}
		case tt == html.TextToken:
			t := parsedHTML.Token().String()
			tLower := strings.ToLower(t)
			if strings.Contains(tLower, ", fl") {
				// We don't want homes not in Gainesville
				if strings.Contains(tLower, "gainesville") {
					cityFlag = true
				}
			}
			if MLSFlag == true {
				MLSNumber = t
				MLSFlag = false
			}
			if PriceFlag == true {
				Price = strings.TrimSpace(t)
				MLS_Price := MLSNumber + "_" + Price
				if cityFlag == true {
					MLSNums = append(MLSNums, MLS_Price)
					cityFlag = false
				}
				PriceFlag = false
			}
		}
	}
}

func getMLSDetails(mlsArray []string) []string {
	MLSURLs := []string{}
	// chans := make([]chan string, len(mlsArray))
	responses := make(chan string)
	var wg sync.WaitGroup

	for _, mlsNumber := range mlsArray {
		wg.Add(2)
		go func(mlsNumber string) {
			defer wg.Done()
			responses <- getMLSDetail(mlsNumber)
		}(mlsNumber)
	}

	go func() {
		for response := range responses {
			// We only want responses that are not empty strings
			if response != "" {
				MLSURLs = append(MLSURLs, response)
			}
			wg.Done()
		}
	}()
	wg.Wait()
	return MLSURLs
}

func getMLSDetail(MLSNumber string) string {
	MLSURL := ""

	searchURL := "https://www.gainesvillemls.com"
	searchPath := "/gan/idx/detail.php"
	data := url.Values{}
	data.Set("key", "52633f4973cf845e55b18c8e22ab08d5")
	data.Add("gallery", "false")
	data.Add("custom", "")
	data.Add("mls", MLSNumber)
	u, _ := url.ParseRequestURI(searchURL)
	u.Path = searchPath
	urlStr := fmt.Sprintf("%v", u)

	client := &http.Client{}
	request, requestErr := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
	if requestErr != nil {
		log.Fatalf("Problem creating new httpRequest", "%s", requestErr)
	}
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	request.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36")
	request.Header.Add("Accept", "*/*")
	request.Header.Add("Accept-Language", "en-US,en;q=0.8")
	request.Header.Add("Accept-Encoding", "gzip, deflate")
	request.Header.Add("Referer", "https://www.gainesvillemls.com/gan/idx/index.php?key=52633f4973cf845e55b18c8e22ab08d5")
	request.Header.Add("X-Requested-With", "XMLHttpRequest")

	resp, responseError := client.Do(request)
	if responseError != nil {
		log.Fatalf("Problem creating new httpRequest", "%s", responseError)
	}

	responseBody := resp.Body
	defer responseBody.Close()

	parsedHTML := html.NewTokenizer(responseBody)

	constructionFlag := false
	constructionCounter := 2
	parkingFlag := false
	parkingCounter := 2

	for {
		tt := parsedHTML.Next()
		switch {
		case tt == html.ErrorToken:
			return MLSURL
		case tt == html.TextToken:
			t := parsedHTML.Token()
			if constructionFlag == true {
				constructionCounter--
				if constructionCounter == 0 {
					if strings.Contains(strings.ToLower(t.String()), "block") || strings.Contains(strings.ToLower(t.String()), "blk") || strings.Contains(strings.ToLower(t.String()), "brick") {
						MLSURL = fmt.Sprintf("https://www.gainesvillemls.com/gan/idx/index.php?key=52633f4973cf845e55b18c8e22ab08d5&mls=%s\n", MLSNumber)
					}
					constructionFlag = false
				}
			}
			if parkingFlag == true {
				parkingCounter--
				if parkingCounter == 0 {
					if strings.Contains(strings.ToLower(t.String()), "no garage") {
						return ""
					}
					parkingFlag = false
				}
			}
			if t.String() == "Construction-exterior:" {
				constructionFlag = true
			}
			if t.String() == "Parking:" {
				parkingFlag = true
			}

		}
	}
}


text:
layout: default
---

{{ page.title }}

投稿日: <time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">{{ page.date | date: "%-Y/%-m/%-d" }}</time>

    {{ content }}

redpajama_set_name: RedPajamaGithub


text:
chrome-ext-refresh-og
=====================


text:
package hu.bme.mit.inf.lookaheadmatcher.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.eclipse.incquery.runtime.matchers.psystem.PVariable;
import org.eclipse.incquery.runtime.matchers.psystem.basicdeferred.Equality;
import org.eclipse.incquery.runtime.matchers.psystem.basicdeferred.Inequality;

public class InEqualConstraint extends CheckableConstraint implements IConstraint
{
	private Inequality innerInequalityConstraint;

	private List<PVariable> affectedVariables;

	public InEqualConstraint(Inequality innerEq)
	{
		this.innerInequalityConstraint = innerEq;
		this.affectedVariables = new ArrayList<PVariable>();
		for (PVariable inner : this.innerInequalityConstraint.getAffectedVariables())
		{
			this.affectedVariables.add(inner);
		}
	}

	@Override
	public boolean Evaluate(HashMap<PVariable, Object> matchingVariables)
	{
		if (!this.CanBeEvaluated(matchingVariables))
			return false; // ejjnye!

		// bubble :(
		for (int i = 0; i < this.affectedVariables.size(); i++)
		{
			for (int j = i + 1; j < this.affectedVariables.size(); j++)
			{
				if (matchingVariables.get(this.affectedVariables.get(i)).equals(matchingVariables.get(this.affectedVariables.get(j))))
					return false; // if some of them equal, escape!
			}
		}
		return true;
	}

	@Override
	public boolean CanBeEvaluated(HashMap<PVariable, Object> matchingVariables)
	{
		for (PVariable affected : this.affectedVariables)
		{
			if (matchingVariables.get(affected) == null)
				return false;
		}
		return true;
	}
}


text:
Error

{{message}}

  <button type="button" class="btn btn-default" ng-click="close()">Close</button>


text:
__all__ = (
    "StateInline",
    "text",
    "text_collapse",
    "link_pairs",
    "escape",
    "newline",
    "backtick",
    "emphasis",
    "image",
    "link",
    "autolink",
    "entity",
    "html_inline",
    "strikethrough",
)
from . import emphasis, strikethrough
from .autolink import autolink
from .backticks import backtick
from .balance_pairs import link_pairs
from .entity import entity
from .escape import escape
from .html_inline import html_inline
from .image import image
from .link import link
from .newline import newline
from .state_inline import StateInline
from .text import text
from .text_collapse import text_collapse


text:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class ProgressService {
  public color$ = new Subject<string>();
  public mode$ = new Subject<string>();
  public value$ = new Subject<number>();

  color: string;
  mode: string;
  value: number;
  total: number;

  constructor() {
    this.color = 'primary';
    this.mode = 'determinate';
    this.value = 0;
    this.total = 100;
  }

  public start(mode?: string, color?: string, total?: number) {
    this.value = 20;
    if (mode == null) {
      this.mode = 'indeterminate';
    } else {
      this.mode = mode;
    }
    if (color == null) {
      this.color = 'primary';
    } else {
      this.color = color;
    }
    if (total) {
      this.total = total;
    } else {
      this.total = 100;
    }

    this.color$.next(this.color);
    this.mode$.next(this.mode);
    this.value$.next(this.value);
  }

  public progress(current: number): number {
    if (this.total !== 0 && this.total > current) {
      const value = (100 * Math.round(Number(current))) / this.total;
      console.log('Setting progress to ' + value);
      this.value = value;
    } else if (this.total <= current) {
      this.end();
    }
    this.value$.next(this.value);
    return this.value;
  }

  public end() {
    this.color = 'primary';
    this.mode = 'determinate';
    this.value = 0;
    this.color$.next(this.color);
    this.mode$.next(this.mode);
    this.value$.next(this.value);
  }

  public increaseSteadily() {
    let remaining = this.total - this.value;
    const increment = this.value + Math.round(Number(remaining / 10));
    remaining = this.progress(increment);
  }
}


text:
package org.apache.uima.cas.test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASRuntimeException;
import org.apache.uima.cas.IntArrayFS;
import org.apache.uima.cas.TypeSystem;
import org.apache.uima.cas.admin.CASFactory;
import org.apache.uima.cas.admin.TypeSystemMgr;
import org.apache.uima.cas.text.AnnotationIndex;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * Class comment for CASTest.java goes here.
 *
 */
public class CASTest {

  private CAS cas;

  private TypeSystem ts;

  @BeforeEach
  public void setUp() {
    try {
      this.cas = CASInitializer.initCas(new CASTestSetup(), null);
      this.ts = this.cas.getTypeSystem();
    } catch (Exception e) {
      assertTrue(false);
    }
  }

  @AfterEach
  public void tearDown() {
    this.cas = null;
    this.ts = null;
  }

  @Test
  public void testGetTypeSystem() {
    assertTrue(this.cas.getTypeSystem() != null);
  }

  @Test
  public void testGetAnnotationIndex() {
    AnnotationIndex index = this.cas.getAnnotationIndex();
    assertNotNull(index);
    assertTrue(index.iterator() != null);
    boolean caughtException = false;
    try {
      this.cas.getAnnotationIndex(this.cas.getTypeSystem().getType(CAS.TYPE_NAME_TOP));
    } catch (CASRuntimeException e) {
      caughtException = true;
    }
    assertTrue(caughtException);
  }

  @Test
  public void testCreateFS() {
    // Can create FS of type "Top"
    assertTrue(this.cas.createFS(this.ts.getType(CAS.TYPE_NAME_TOP)) != null);
    boolean caughtExc = false;
    // Can't create int FS.
    try {
      this.cas.createFS(this.ts.getType(CAS.TYPE_NAME_INTEGER));
    } catch (CASRuntimeException e) {
      caughtExc = true;
      assertTrue(e.getMessageKey().equals(CASRuntimeException.NON_CREATABLE_TYPE));
    }
    assertTrue(caughtExc);
    caughtExc = false;
    // Can't create array with CAS.createFS().
    try {
      this.cas.createFS(this.ts.getType(CAS.TYPE_NAME_FS_ARRAY));
    } catch (CASRuntimeException e) {
      caughtExc = true;
      assertTrue(e.getMessageKey().equals(CASRuntimeException.NON_CREATABLE_TYPE));
    }
    assertTrue(caughtExc);
    caughtExc = false;

    // Check that we can create structures that are larger than the internal
    // heap page size.
    final int arraySize = 1000000;
    // Make sure that the structure we're trying to create is actually larger
    // than the page size we're testing with.
    // assertTrue(arraySize > Heap.DEFAULT_SIZE);
    IntArrayFS array = null;
    try {
      array = this.cas.createIntArrayFS(arraySize);
    } catch (CASRuntimeException e) {
      assertTrue(false);
    }
    try {
      array.set(arraySize - 1, 1);
    } catch (ArrayIndexOutOfBoundsException e) {
      assertTrue(false);
    }

    // Can't create array subtype with CAS.createFS().
    // try {
    // this.cas.createFS(this.ts.getType(CASTestSetup.INT_ARRAY_SUB));
    // } catch (CASRuntimeException e) {
    // caughtExc = true;
    // assertTrue(e.getError() == CASRuntimeException.NON_CREATABLE_TYPE);
    // }
    // assertTrue(caughtExc);
  }

  @Test
  public void testCreateCAS() {
    TypeSystemMgr tsm = CASFactory.createTypeSystem();
    tsm.commit();
  }
}


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package ebay.apis.eblbasecomponents;

import java.io.Serializable;
import com.leansoft.nano.annotation.*;

/**
 *
 * Retrieves details for VeRO reason codes and their descriptions. You can specify a
 * reason code ID to get details for a specific reason on the site specified in the
 * request header. If ReasonCodeID is not passed in the request, all reason codes are
 * returned. Set ReturnAllSites to true to retrieve reason codes for all sites.
 * You must be a member of the Verified Rights Owner (VeRO) Program to use this call.
 *
 */
@RootElement(name = "GetVeROReasonCodeDetailsRequest", namespace = "urn:ebay:apis:eBLBaseComponents")
public class GetVeROReasonCodeDetailsRequestType extends AbstractRequestType implements Serializable {

    private static final long serialVersionUID = -1L;

	@Element(name = "ReasonCodeID")
	private Long reasonCodeID;

	@Element(name = "ReturnAllSites")
	private Boolean returnAllSites;

	/**
     * public getter
     *
     *
     *  Unique identifier for a reason code. If this ReasonCodeID is passed then
     *  only details of this ReasonCodeID will be returned. If no reason code is
     *  specified, all reason codes are returned.
     *
     *
     * @returns java.lang.Long
	 */
	public Long getReasonCodeID() {
	    return this.reasonCodeID;
	}

	/**
	 * public setter
	 *
     *
     *  Unique identifier for a reason code. If this ReasonCodeID is passed then
     *  only details of this ReasonCodeID will be returned. If no reason code is
     *  specified, all reason codes are returned.
     *
     *
     * @param java.lang.Long
	 */
	public void setReasonCodeID(Long reasonCodeID) {
	    this.reasonCodeID = reasonCodeID;
	}
	/**
     * public getter
     *
     *
     *  Set to true to retrieve reason codes for all sites. If not specified,
     *  reason codes are returned for the site specified in the request header
     *  only.
     *  If ReasonCodeID is specified, this parameter is ignored.
     *
     *
     * @returns java.lang.Boolean
	 */
	public Boolean getReturnAllSites() {
	    return this.returnAllSites;
	}

	/**
	 * public setter
	 *
     *
     *  Set to true to retrieve reason codes for all sites. If not specified,
     *  reason codes are returned for the site specified in the request header
     *  only.
     *  If ReasonCodeID is specified, this parameter is ignored.
     *
     *
     * @param java.lang.Boolean
	 */
	public void setReturnAllSites(Boolean returnAllSites) {
	    this.returnAllSites = returnAllSites;
	}

}


text:
package com.pholser.junit.quickcheck.internal.generator;

import com.pholser.junit.quickcheck.generator.GenerationStatus;
import com.pholser.junit.quickcheck.generator.Generator;
import com.pholser.junit.quickcheck.random.SourceOfRandomness;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

public class GuaranteeValuesGenerator extends Generator<Object> {
    private final ExhaustiveDomainGenerator guaranteed;
    private final Generator<?> rest;

    @SuppressFBWarnings("EI_EXPOSE_REP2")
    public GuaranteeValuesGenerator(
        ExhaustiveDomainGenerator guaranteed,
        Generator<?> rest) {

        super(Object.class);

        this.guaranteed = guaranteed;
        this.rest = rest;
    }

    @Override public Object generate(
        SourceOfRandomness random,
        GenerationStatus status) {

        return guaranteed.hasNext()
            ? guaranteed.generate(random, status)
            : rest.generate(random, status);
    }
}


text:
package org.ubjson.model;

import static org.ubjson.io.IUBJTypeMarker.FLOAT;

import java.io.IOException;

import org.ubjson.io.UBJFormatException;
import org.ubjson.io.UBJInputStreamParser;
import org.ubjson.io.UBJOutputStream;

public class FloatValue extends AbstractValue<Float> {
	public FloatValue(Float value) throws IllegalArgumentException {
		super(value);
	}

	public FloatValue(UBJInputStreamParser in) throws IllegalArgumentException,
			IOException, UBJFormatException {
		super(in);
	}

	@Override
	public byte getType() {
		return FLOAT;
	}

	@Override
	public void serialize(UBJOutputStream out) throws IllegalArgumentException,
			IOException {
		if (out == null)
			throw new IllegalArgumentException("out cannot be null");

		out.writeFloat(value);
	}

	@Override
	public void deserialize(UBJInputStreamParser in)
			throws IllegalArgumentException, IOException, UBJFormatException {
		if (in == null)
			throw new IllegalArgumentException("in cannot be null");

		value = in.readFloat();
	}
}


text:
<!DOCTYPE HTML>

		<title>Phantom by HTML5 UP</title>

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

		<link rel="stylesheet" href="../assets/css/main.css" />

									Phantom

Menu

Menu

Home

Ipsum veroeros

Tempus etiam

Consequat dolor

Elements

This is Phantom, a free, fully responsive site

								template designed by HTML5 UP.

Etiam quis viverra lorem, in semper lorem. Sed nisl arcu euismod sit amet nisi euismod sed cursus arcu elementum ipsum arcu vivamus quis venenatis orci lorem ipsum et magna feugiat veroeros aliquam. Lorem ipsum dolor sit amet nullam dolore.

Magna

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Lorem

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Feugiat

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Tempus

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Aliquam

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Veroeros

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Ipsum

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Dolor

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Nullam

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Ultricies

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Dictum

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Pretium

Sed nisl arcu euismod sit amet nisi lorem etiam dolor veroeros et feugiat.

Get in touch

								<form method="post" action="#">

										<input type="text" name="name" id="name" placeholder="Name" />

										<input type="email" name="email" id="email" placeholder="Email" />

										<textarea name="message" id="message" placeholder="Message"></textarea>

<input type="submit" value="Send" class="special" />

								</form>

Follow

Twitter

Facebook

Instagram

Dribbble

GitHub

500px

Phone

Email

© Untitled. All rights reserved

Design: HTML5 UP


text:
'''
Created on May 21, 2015

@author: hsorby
'''
import os
import re

from opencmiss.zinc.field import Field
from opencmiss.zinc.status import OK
from opencmiss.utils.zinc.field import createFieldFiniteElement
from opencmiss.utils.zinc.finiteelement import createSquareElement
from opencmiss.utils.image import extractImageCorners

from mapclientplugins.heartsurfacesegmenterstep.maths.algorithms import calculatePlaneNormal

LONG_AXIS = 1
SHORT_AXIS = 2

class ImageModel(object):

    def __init__(self, context):
        '''
        Constructor
        '''
        self._context = context
        self.clear()

    def getContext(self):
        return self._context

    def clear(self):
        self._image_data = {}
        self._images = []

    def initialise(self, region):
        self._createImageRegion(region)
        self._computeImages(LONG_AXIS)
        self._computeImages(SHORT_AXIS)

    def setImageData(self, axis, image_data):
        self._image_data[axis] = image_data

    def getImages(self):
        return self._images

    def getPlane(self, region):
        regions = [image.getRegion() for image in self._images]
        plane_point = None
        plane_normal = None
        if region in regions:
            fieldmodule = region.getFieldmodule()
            fieldcache = fieldmodule.createFieldcache()
            coordinate_field = fieldmodule.findFieldByName('coordinates')
            nodeset = fieldmodule.findNodesetByFieldDomainType(Field.DOMAIN_TYPE_NODES)
            nodesetiterator = nodeset.createNodeiterator()

            node = nodesetiterator.next()
            locations = []
            count = 0
            while node.isValid() and count < 3:
                fieldcache.setNode(node)
                result, location = coordinate_field.evaluateReal(fieldcache, 3)
                if result == OK:
                    locations.append(location)
                node = nodesetiterator.next()
                count += 1

            if len(locations) == 3:
                plane_point = locations[0]
                plane_normal = calculatePlaneNormal(locations[0], locations[1], locations[2])

        return plane_point, plane_normal

    def getRegionNames(self):
        return [image.getRegion().getName() for image in self._images]

    def setRegionVisibility(self, region_name, state):
        region_names = self.getRegionNames()
        if region_name in region_names:
            index = region_names.index(region_name)
            self._images[index].setVisibility(state)

    def _computeImages(self, axis):
        directory = self._image_data[axis].location()
        files = os.listdir(directory)
        files.sort(key=alphanum_key)
        files = [image_file for image_file in files if image_file not in ['.hg', '.git', 'annotation.rdf']]
        # Assuming these images are DICOMs
        LA_count = 0
        SA_count = 0
        for filename in files:
            if axis == LONG_AXIS:
                LA_count += 1
                region = self._region.findChildByName('LA{0}'.format(LA_count))
                if not region.isValid():
                    region = self._region.createChild('LA{0}'.format(LA_count))
            else:
                SA_count += 1
                region = self._region.createChild('SA{0}'.format(SA_count))

            self._images.append(ImageTexture(self, directory, filename, region))

    def _createImageRegion(self, region):
        '''
        Creates a child region of the root region called 'image'.  Stores
        a handle to the region in the class attribute '_region'.
        '''
        self._region = region.createChild('image_region')

def determineAxis(name):
    return LONG_AXIS

class ImageTexture(object):

    def __init__(self, parent, directory, filename, region):
        self._parent = parent
        self._name = region.getName()
        self._region = region

        fieldmodule = region.getFieldmodule()
        self._coordinate_field = createFieldFiniteElement(region)
        corners = extractImageCorners(directory, filename)
        mesh = fieldmodule.findMeshByDimension(2)
        createSquareElement(mesh, self._coordinate_field, corners)
        self._image_field = self._createImageField(fieldmodule, os.path.join(directory, filename))
        self._material = self._createMaterialUsingImageField(self._image_field)

    def _createMaterialUsingImageField(self, image_field):
        '''
        Use an image field in a material to create an OpenGL texture.  Returns the
        created material.
        '''
        # Create a graphics material from the graphics module, assign it a name
        # and set flag to true
        materials_module = self._parent.getContext().getMaterialmodule()
        material = materials_module.createMaterial()

        spectrummodule = self._parent.getContext().getSpectrummodule()
        spectrum = spectrummodule.createSpectrum()
        component = spectrum.createSpectrumcomponent()
        component.setColourMappingType(component.COLOUR_MAPPING_TYPE_MONOCHROME)
        component.setRangeMinimum(0)
        component.setRangeMaximum(1)
        material.setTextureField(1, image_field)

        return material

    def _createImageField(self, fieldmodule, absolute_filename):
        image_field = fieldmodule.createFieldImage()
        image_field.setName('image_field')
        image_field.setFilterMode(image_field.FILTER_MODE_LINEAR)

        # Create a stream information object that we can use to read the
        # image file from disk
        stream_information = image_field.createStreaminformationImage()

        # We are reading in a file from the local disk so our resource is a file.
        if os.path.isfile(absolute_filename):
            # SWIG cannot handle unicode strings or rather the Zinc interface
            # files cannot handle unicode strings so we convert them to ascii
            # here.
            # if isinstance(absolute_filename, unicode):
            #     absolute_filename = absolute_filename.encode('ascii', 'ignore')
            stream_information.createStreamresourceFile(absolute_filename)

        # Actually read in the image file into the image field.
        image_field.read(stream_information)

        return image_field

    def getCoordinateField(self):
        return self._coordinate_field

    def getRegion(self):
        return self._region

    def getName(self):
        return self._name

    def getMaterial(self):
        return self._material

    def setVisibility(self, state):
        self._region.getScene().setVisibilityFlag(state)

    def free(self):
        fieldmodule = self._region.getFieldmodule()
        for dimension in [3, 2, 1]:
            mesh = fieldmodule.findMeshByDimension(dimension)
            mesh.destroyAllElements()
        nodeset = fieldmodule.findNodesetByFieldDomainType(Field.DOMAIN_TYPE_NODES)
        nodeset.destroyAllNodes()
        it = fieldmodule.createFielditerator()
        field = it.next()
        while field.isValid():
            if field.isManaged():
                field.setManaged(False)
                # must reset iterator
                it = fieldmodule.createFielditerator()
            field = it.next()

        self._region = None
        self._coordinate_field = None
        self._image_field = None
        self._material = None

def tryint(s):
    try:
        return int(s)
    except:
        return s

def alphanum_key(s):
    """ Turn a string into a list of string and number chunks.
    "z23a" -> ["z", 23, "a"]
    """
    return [tryint(c) for c in re.split('([0-9]+)', s)]


text: A simple app designed to make the ride from Seattle to Vancouver more comfortable.


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
    	<parameter key="anpe.user_manager.class">Anpe\Bundle\UserBundle\Manager\UserManager</parameter>
    </parameters>

    <services>

        <service id="anpe.user_manager" class="%anpe.user_manager.class%">
        	<argument type="service" id="doctrine.orm.entity_manager" />
        </service>

    </services>

</container>


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_PRIMITIVES_BLOCK_H
#define BITCOIN_PRIMITIVES_BLOCK_H

#include "primitives/transaction.h"
#include "serialize.h"
#include "uint256.h"

/** Nodes collect new transactions into a block, hash them into a hash tree,
 * and scan through nonce values to make the block's hash satisfy proof-of-work
 * requirements.  When they solve the proof-of-work, they broadcast the block
 * to everyone and the block is added to the block chain.  The first transaction
 * in the block is a special one that creates a new coin owned by the creator
 * of the block.
 */
class CBlockHeader
{
public:
    // header
    int32_t nVersion;
    uint256 hashPrevBlock;
    uint256 hashMerkleRoot;
    uint256 hashReserved;
    uint32_t nTime;
    uint32_t nBits;
    uint256 nNonce;
    std::vector<unsigned char> nSolution;

    CBlockHeader()
    {
        SetNull();
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action) {
        READWRITE(this->nVersion);
        READWRITE(hashPrevBlock);
        READWRITE(hashMerkleRoot);
        READWRITE(hashReserved);
        READWRITE(nTime);
        READWRITE(nBits);
        READWRITE(nNonce);
	    READWRITE(nSolution);
    }

    void SetNull()
    {
        nVersion = 0;
        hashPrevBlock.SetNull();
        hashMerkleRoot.SetNull();
	    hashReserved.SetNull();
        nTime = 0;
        nBits = 0;
        nNonce = uint256();
	    nSolution.clear();
    }

    bool IsNull() const
    {
        return (nBits == 0);
    }

    uint256 GetHash() const;

    int64_t GetBlockTime() const
    {
        return (int64_t)nTime;
    }
};

class CBlock : public CBlockHeader
{
public:
    // network and disk
    std::vector<CTransactionRef> vtx;

    // memory only
    mutable bool fChecked;

    CBlock()
    {
        SetNull();
    }

    CBlock(const CBlockHeader &header)
    {
        SetNull();
        *((CBlockHeader*)this) = header;
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action) {
        READWRITE(*(CBlockHeader*)this);
        READWRITE(vtx);
    }

    void SetNull()
    {
        CBlockHeader::SetNull();
        vtx.clear();
        fChecked = false;
    }

    CBlockHeader GetBlockHeader() const
    {
        CBlockHeader block;
        block.nVersion       = nVersion;
        block.hashPrevBlock  = hashPrevBlock;
        block.hashMerkleRoot = hashMerkleRoot;
	block.hashReserved   = hashReserved;
        block.nTime          = nTime;
        block.nBits          = nBits;
        block.nNonce         = nNonce;
	block.nSolution      = nSolution;
        return block;
    }

    std::string ToString() const;
};

/**
 *  * Custom serializer for CBlockHeader that omits the nonce and solution, for use
 *   * as input to Equihash.
 *    */
class CEquihashInput : private CBlockHeader
{
public:
    CEquihashInput(const CBlockHeader &header)
    {
        CBlockHeader::SetNull();
        *((CBlockHeader*)this) = header;
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action) {
        READWRITE(this->nVersion);
        nVersion = this->nVersion;
        READWRITE(hashPrevBlock);
        READWRITE(hashMerkleRoot);
        READWRITE(hashReserved);
        READWRITE(nTime);
        READWRITE(nBits);
    }
};

/** Describes a place in the block chain to another node such that if the
 * other node doesn't have the same branch, it can find a recent common trunk.
 * The further back it is, the further before the fork it may be.
 */
struct CBlockLocator
{
    std::vector<uint256> vHave;

    CBlockLocator() {}

    CBlockLocator(const std::vector<uint256>& vHaveIn)
    {
        vHave = vHaveIn;
    }

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action) {
        int nVersion = s.GetVersion();
        if (!(s.GetType() & SER_GETHASH))
            READWRITE(nVersion);
        READWRITE(vHave);
    }

    void SetNull()
    {
        vHave.clear();
    }

    bool IsNull() const
    {
        return vHave.empty();
    }
};

/** Compute the consensus-critical block weight (see BIP 141). */
int64_t GetBlockWeight(const CBlock& tx);

#endif // BITCOIN_PRIMITIVES_BLOCK_H


text:
import discord
import datetime
from discord.ext import commands

class Fun:
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @commands.guild_only()
    async def say(self, ctx, *, message: str):
        await ctx.message.delete()
        await ctx.send(message)

def setup(bot):
    bot.add_cog(Fun(bot))


text:
This document provides high-level instructions on how to build and test the microservice.

* [Environment Setup](#setup)
* [Installing](#install)
* [Building](#build)
* [Testing](#test)
* [Contributing](#contrib)

##  Environment Setup

This is a Node.js project and you have to install Node.js tools.
You can download them from official Node.js website: https://nodejs.org/en/download/

After node is installed you can check it by running the following command:
```bash
node -version
```

Then you need to configure node tools:
```bash
# Install typescript compiler
npm install typescript -g

# Install mocha test runner
npm install mocha -g
```

To work with GitHub code repository you need to install Git from: https://git-scm.com/downloads

If you are planning to develop and test using persistent storages other than flat files
you may need to install database servers:
- Download and install MongoDB database from https://www.mongodb.org/downloads

##  Installing

After your environment is ready you can check out microservice source code from the Github repository:
```bash
git clone git@github.com:pip-services-infrastructure/pip-services-eventlog-node.git
```

Then go to the project folder and install dependent modules:

```bash
# Install dependencies
npm install
```

If you worked with the microservice before you can check out latest changes and update the dependencies:
```bash
# Update source code updates from github
git pull

# Update dependencies
npm update
```

##  Building

This microservice is written in TypeScript language which is transcompiled into JavaScript.
So, if you make changes to the source code you need to compile it before running or committing to github.
The process will output compiled javascript files into /bin folder.

```bash
tsc
```

When you do continuous edit-build-test cycle, you can run typescript compiler with --watch option
to detect and compile changes you make automatically:

```bash
tsc --watch
```

##  Testing

Before you execute tests you need to set configuration options in config.yml file.
As a starting point you can use example from config.example.yml:

```bash
copy config.example.yml config.yml
```

After that check all configuration options. Specifically, pay attention to connection options
for database and dependent microservices. For more information check [Configuration Guide](Configuration.md)

Command to run unit tests:
```bash
npm test
```

You can also execute benchmarks as:
```bash
npm run benchmark
```

##  Contributing

Developers interested in contributing should read the following instructions:

- [How to Contribute](http://www.pipservices.org/contribute/)
- [Guidelines](http://www.pipservices.org/contribute/guidelines)
- [Styleguide](http://www.pipservices.org/contribute/styleguide)
- [ChangeLog](CHANGELOG.md)

> Please do **not** ask general questions in an issue. Issues are only to report bugs, request
  enhancements, or request new features. For general questions and discussions, use the
  [Contributors Forum](http://www.pipservices.org/forums/forum/contributors/).

It is important to note that for each release, the [ChangeLog](CHANGELOG.md) is a resource that will
itemize all:

- Bug Fixes
- New Features
- Breaking Changes


text:
/**
 * @class Ext.form.ComboBox
 * @extends Ext.form.TriggerField
 *
A combobox control with support for autocomplete, remote-loading, paging and many other features.

 *
A ComboBox works in a similar manner to a traditional HTML <select> field. The difference is
 * that to submit the {@link #valueField}, you must specify a {@link #hiddenName} to create a hidden input
 * field to hold the value of the valueField. The {@link #displayField} is shown in the text field
 * which is named according to the {@link #name}.

 *
Events

 *
To do something when something in ComboBox is selected, configure the select event:

var cb = new Ext.form.ComboBox({
    // all of your config options
    listeners:{
         scope: yourScope,
         'select': yourFunction
    }
});

// Alternatively, you can assign events after the object is created:
var cb = new Ext.form.ComboBox(yourOptions);
cb.on('select', yourFunction, yourScope);
 *

 *
 *
ComboBox in Grid

 *
If using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a {@link Ext.grid.Column#renderer renderer}
 * will be needed to show the displayField when the editor is not active.  Set up the renderer manually, or implement
 * a reusable render, for example:

// create reusable renderer
Ext.util.Format.comboRenderer = function(combo){
    return function(value){
        var record = combo.findRecord(combo.{@link #valueField}, value);
        return record ? record.get(combo.{@link #displayField}) : combo.{@link #valueNotFoundText};
    }
}

// create the combo instance
var combo = new Ext.form.ComboBox({
    {@link #typeAhead}: true,
    {@link #triggerAction}: 'all',
    {@link #lazyRender}:true,
    {@link #mode}: 'local',
    {@link #store}: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [[1, 'item1'], [2, 'item2']]
    }),
    {@link #valueField}: 'myId',
    {@link #displayField}: 'displayText'
});

// snippet of column model used within grid
var cm = new Ext.grid.ColumnModel([{
       ...
    },{
       header: "Some Header",
       dataIndex: 'whatever',
       width: 130,
       editor: combo, // specify reference to combo instance
       renderer: Ext.util.Format.comboRenderer(combo) // pass combo instance to reusable renderer
    },
    ...
]);
 *

 *
 *
Filtering

 *
A ComboBox {@link #doQuery uses filtering itself}, for information about filtering the ComboBox
 * store manually see <tt>{@link #lastQuery}</tt>.

 * @constructor
 * Create a new ComboBox.
 * @param {Object} config Configuration options
 * @xtype combo
 */
Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, {
    /**
     * @cfg {Mixed} transform The id, DOM node or element of an existing HTML SELECT to convert to a ComboBox.
     * Note that if you specify this and the combo is going to be in an {@link Ext.form.BasicForm} or
     * {@link Ext.form.FormPanel}, you must also set <tt>{@link #lazyRender} = true</tt>.
     */
    /**
     * @cfg {Boolean} lazyRender <tt>true</tt> to prevent the ComboBox from rendering until requested
     * (should always be used when rendering into an {@link Ext.Editor} (e.g. {@link Ext.grid.EditorGridPanel Grids}),
     * defaults to <tt>false</tt>).
     */
    /**
     * @cfg {String/Object} autoCreate
A {@link Ext.DomHelper DomHelper} element spec, or <tt>true</tt> for a default
     * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
     * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:

     *
{tag: "input", type: "text", size: "24", autocomplete: "off"}

     */
    /**
     * @cfg {Ext.data.Store/Array} store The data source to which this combo is bound (defaults to <tt>undefined</tt>).
     * Acceptable values for this property are:
     *

     *
any {@link Ext.data.Store Store} subclass

     *
an Array : Arrays will be converted to a {@link Ext.data.ArrayStore} internally,
     * automatically generating {@link Ext.data.Field#name field names} to work with all data components.
     *

     *
1-dimensional array : (e.g., <tt>['Foo','Bar']</tt>)

     * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo
     * {@link #valueField} and {@link #displayField})

     *
2-dimensional array : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)

     * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
     * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}.
     *

     *
See also <tt>{@link #mode}</tt>.

     */
    /**
     * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
     * the dropdown list (defaults to undefined, with no header element)
     */

    // private
    defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
    /**
     * @cfg {Number} listWidth The width (used as a parameter to {@link Ext.Element#setWidth}) of the dropdown
     * list (defaults to the width of the ComboBox field).  See also <tt>{@link #minListWidth}</tt>
     */
    /**
     * @cfg {String} displayField The underlying {@link Ext.data.Field#name data field name} to bind to this
     * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field1'</tt> if
     * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
     * the store configuration}).
     *
See also <tt>{@link #valueField}</tt>.

     *
Note: if using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a
     * {@link Ext.grid.Column#renderer renderer} will be needed to show the displayField when the editor is not
     * active.

     */
    /**
     * @cfg {String} valueField The underlying {@link Ext.data.Field#name data value name} to bind to this
     * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field2'</tt> if
     * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
     * the store configuration}).
     *
Note: use of a <tt>valueField</tt> requires the user to make a selection in order for a value to be
     * mapped.  See also <tt>{@link #hiddenName}</tt>, <tt>{@link #hiddenValue}</tt>, and <tt>{@link #displayField}</tt>.

     */
    /**
     * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
     * field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically
     * post during a form submission.  See also {@link #valueField}.
     */
    /**
     * @cfg {String} hiddenId If <tt>{@link #hiddenName}</tt> is specified, <tt>hiddenId</tt> can also be provided
     * to give the hidden field a unique id.  The <tt>hiddenId</tt> and combo {@link Ext.Component#id id} should be
     * different, since no two DOM nodes should share the same id.
     */
    /**
     * @cfg {String} hiddenValue Sets the initial value of the hidden field if {@link #hiddenName} is
     * specified to contain the selected {@link #valueField}, from the Store. Defaults to the configured
     * <tt>{@link Ext.form.Field#value value}</tt>.
     */
    /**
     * @cfg {String} listClass The CSS class to add to the predefined <tt>'x-combo-list'</tt> class
     * applied the dropdown list element (defaults to '').
     */
    listClass : '',
    /**
     * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list
     * (defaults to <tt>'x-combo-selected'</tt>)
     */
    selectedClass : 'x-combo-selected',
    /**
     * @cfg {String} listEmptyText The empty text to display in the data view if no items are found.
     * (defaults to '')
     */
    listEmptyText: '',
    /**
     * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always
     * get the class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be appended if specified
     * (defaults to <tt>'x-form-arrow-trigger'</tt> which displays a downward arrow icon).
     */
    triggerClass : 'x-form-arrow-trigger',
    /**
     * @cfg {Boolean/String} shadow <tt>true</tt> or <tt>"sides"</tt> for the default effect, <tt>"frame"</tt> for
     * 4-way shadow, and <tt>"drop"</tt> for bottom-right
     */
    shadow : 'sides',
    /**
     * @cfg {String/Array} listAlign A valid anchor position value. See <tt>{@link Ext.Element#alignTo}</tt> for details
     * on supported anchor positions and offsets. To specify x/y offsets as well, this value
     * may be specified as an Array of <tt>{@link Ext.Element#alignTo}</tt> method arguments.

     *
[ 'tl-bl?', [6,0] ]
(defaults to <tt>'tl-bl?'</tt>)
     */
    listAlign : 'tl-bl?',
    /**
     * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown
     * (defaults to <tt>300</tt>)
     */
    maxHeight : 300,
    /**
     * @cfg {Number} minHeight The minimum height in pixels of the dropdown list when the list is constrained by its
     * distance to the viewport edges (defaults to <tt>90</tt>)
     */
    minHeight : 90,
    /**
     * @cfg {String} triggerAction The action to execute when the trigger is clicked.
     *

     *
<tt>'query'</tt> : Default
     *
{@link #doQuery run the query} using the {@link Ext.form.Field#getRawValue raw value}.

     *
<tt>'all'</tt> :
     *
{@link #doQuery run the query} specified by the <tt>{@link #allQuery}</tt> config option

     *

     *
See also {@link #queryParam}.

     */
    triggerAction : 'query',
    /**
     * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and
     * {@link #typeAhead} activate (defaults to <tt>4</tt> if <tt>{@link #mode} = 'remote'</tt> or <tt>0</tt> if
     * <tt>{@link #mode} = 'local'</tt>, does not apply if
     * <tt>{@link Ext.form.TriggerField#editable editable} = false</tt>).
     */
    minChars : 4,
    /**
     * @cfg {Boolean} autoSelect <tt>true</tt> to select the first result gathered by the data store (defaults
     * to <tt>true</tt>).  A false value would require a manual selection from the dropdown list to set the components value
     * unless the value of ({@link #typeAheadDelay}) were true.
     */
    autoSelect : true,
    /**
     * @cfg {Boolean} typeAhead <tt>true</tt> to populate and autoselect the remainder of the text being
     * typed after a configurable delay ({@link #typeAheadDelay}) if it matches a known value (defaults
     * to <tt>false</tt>)
     */
    typeAhead : false,
    /**
     * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and
     * sending the query to filter the dropdown list (defaults to <tt>500</tt> if <tt>{@link #mode} = 'remote'</tt>
     * or <tt>10</tt> if <tt>{@link #mode} = 'local'</tt>)
     */
    queryDelay : 500,
    /**
     * @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.PagingToolbar} is displayed in the
     * footer of the dropdown list and the {@link #doQuery filter queries} will execute with page start and
     * {@link Ext.PagingToolbar#pageSize limit} parameters. Only applies when <tt>{@link #mode} = 'remote'</tt>
     * (defaults to <tt>0</tt>).
     */
    pageSize : 0,
    /**
     * @cfg {Boolean} selectOnFocus <tt>true</tt> to select any existing text in the field immediately on focus.
     * Only applies when <tt>{@link Ext.form.TriggerField#editable editable} = true</tt> (defaults to
     * <tt>false</tt>).
     */
    selectOnFocus : false,
    /**
     * @cfg {String} queryParam Name of the query ({@link Ext.data.Store#baseParam baseParam} name for the store)
     * as it will be passed on the querystring (defaults to <tt>'query'</tt>)
     */
    queryParam : 'query',
    /**
     * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
     * when <tt>{@link #mode} = 'remote'</tt> (defaults to <tt>'Loading...'</tt>)
     */
    loadingText : 'Loading...',
    /**
     * @cfg {Boolean} resizable <tt>true</tt> to add a resize handle to the bottom of the dropdown list
     * (creates an {@link Ext.Resizable} with 'se' {@link Ext.Resizable#pinned pinned} handles).
     * Defaults to <tt>false</tt>.
     */
    resizable : false,
    /**
     * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if
     * <tt>{@link #resizable} = true</tt> (defaults to <tt>8</tt>)
     */
    handleHeight : 8,
    /**
     * @cfg {String} allQuery The text query to send to the server to return all records for the list
     * with no filtering (defaults to '')
     */
    allQuery: '',
    /**
     * @cfg {String} mode Acceptable values are:
     *

     *
<tt>'remote'</tt> : Default
     *
Automatically loads the <tt>{@link #store}</tt> the first time the trigger
     * is clicked. If you do not want the store to be automatically loaded the first time the trigger is
     * clicked, set to <tt>'local'</tt> and manually load the store.  To force a requery of the store
     * every time the trigger is clicked see <tt>{@link #lastQuery}</tt>.

     *
<tt>'local'</tt> :
     *
ComboBox loads local data

     *

var combo = new Ext.form.ComboBox({
    renderTo: document.body,
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',  // numeric value is the key
            'displayText'
        ],
        data: [[1, 'item1'], [2, 'item2']]  // data is local
    }),
    valueField: 'myId',
    displayField: 'displayText',
    triggerAction: 'all'
});
     *

     *

     */
    mode: 'remote',
    /**
     * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to <tt>70</tt>, will
     * be ignored if <tt>{@link #listWidth}</tt> has a higher value)
     */
    minListWidth : 70,
    /**
     * @cfg {Boolean} forceSelection <tt>true</tt> to restrict the selected value to one of the values in the list,
     * <tt>false</tt> to allow the user to set arbitrary text into the field (defaults to <tt>false</tt>)
     */
    forceSelection : false,
    /**
     * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
     * if <tt>{@link #typeAhead} = true</tt> (defaults to <tt>250</tt>)
     */
    typeAheadDelay : 250,
    /**
     * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
     * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
     * default text is used, it means there is no value set and no validation will occur on this field.
     */

    /**
     * @cfg {Boolean} lazyInit <tt>true</tt> to not initialize the list for this combo until the field is focused
     * (defaults to <tt>true</tt>)
     */
    lazyInit : true,

    /**
     * @cfg {Boolean} clearFilterOnReset <tt>true</tt> to clear any filters on the store (when in local mode) when reset is called
     * (defaults to <tt>true</tt>)
     */
    clearFilterOnReset : true,

    /**
     * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
     * If a hiddenName is specified, setting this to true will cause both the hidden field and the element to be submitted.
     * Defaults to <tt>undefined</tt>.
     */
    submitValue: undefined,

    /**
     * The value of the match string used to filter the store. Delete this property to force a requery.
     * Example use:
     *

var combo = new Ext.form.ComboBox({
    ...
    mode: 'remote',
    ...
    listeners: {
        // delete the previous query in the beforequery event or set
        // combo.lastQuery = null (this will reload the store the next time it expands)
        beforequery: function(qe){
            delete qe.combo.lastQuery;
        }
    }
});
     *

     * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used
     * configure the combo with <tt>lastQuery=''</tt>. Example use:
     *

var combo = new Ext.form.ComboBox({
    ...
    mode: 'local',
    triggerAction: 'all',
    lastQuery: ''
});
     *

     * @property lastQuery
     * @type String
     */

    // private
    initComponent : function(){
        Ext.form.ComboBox.superclass.initComponent.call(this);
        this.addEvents(
            /**
             * @event expand
             * Fires when the dropdown list is expanded
             * @param {Ext.form.ComboBox} combo This combo box
             */
            'expand',
            /**
             * @event collapse
             * Fires when the dropdown list is collapsed
             * @param {Ext.form.ComboBox} combo This combo box
             */
            'collapse',

            /**
             * @event beforeselect
             * Fires before a list item is selected. Return false to cancel the selection.
             * @param {Ext.form.ComboBox} combo This combo box
             * @param {Ext.data.Record} record The data record returned from the underlying store
             * @param {Number} index The index of the selected item in the dropdown list
             */
            'beforeselect',
            /**
             * @event select
             * Fires when a list item is selected
             * @param {Ext.form.ComboBox} combo This combo box
             * @param {Ext.data.Record} record The data record returned from the underlying store
             * @param {Number} index The index of the selected item in the dropdown list
             */
            'select',
            /**
             * @event beforequery
             * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
             * cancel property to true.
             * @param {Object} queryEvent An object that has these properties:

             *
combo : Ext.form.ComboBox
This combo box

             *
query : String
The query

             *
forceAll : Boolean
True to force "all" query

             *
cancel : Boolean
Set to true to cancel the query

             *

             */
            'beforequery'
        );
        if(this.transform){
            var s = Ext.getDom(this.transform);
            if(!this.hiddenName){
                this.hiddenName = s.name;
            }
            if(!this.store){
                this.mode = 'local';
                var d = [], opts = s.options;
                for(var i = 0, len = opts.length;i < len; i++){
                    var o = opts[i],
                        value = (o.hasAttribute ? o.hasAttribute('value') : o.getAttributeNode('value').specified) ? o.value : o.text;
                    if(o.selected && Ext.isEmpty(this.value, true)) {
                        this.value = value;
                    }
                    d.push([value, o.text]);
                }
                this.store = new Ext.data.ArrayStore({
                    idIndex: 0,
                    fields: ['value', 'text'],
                    data : d,
                    autoDestroy: true
                });
                this.valueField = 'value';
                this.displayField = 'text';
            }
            s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
            if(!this.lazyRender){
                this.target = true;
                this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
                this.render(this.el.parentNode, s);
            }
            Ext.removeNode(s);
        }
        //auto-configure store from local array data
        else if(this.store){
            this.store = Ext.StoreMgr.lookup(this.store);
            if(this.store.autoCreated){
                this.displayField = this.valueField = 'field1';
                if(!this.store.expandData){
                    this.displayField = 'field2';
                }
                this.mode = 'local';
            }
        }

        this.selectedIndex = -1;
        if(this.mode == 'local'){
            if(!Ext.isDefined(this.initialConfig.queryDelay)){
                this.queryDelay = 10;
            }
            if(!Ext.isDefined(this.initialConfig.minChars)){
                this.minChars = 0;
            }
        }
    },

    // private
    onRender : function(ct, position){
        if(this.hiddenName && !Ext.isDefined(this.submitValue)){
            this.submitValue = false;
        }
        Ext.form.ComboBox.superclass.onRender.call(this, ct, position);
        if(this.hiddenName){
            this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
                    id: (this.hiddenId || Ext.id())}, 'before', true);

        }
        if(Ext.isGecko){
            this.el.dom.setAttribute('autocomplete', 'off');
        }

        if(!this.lazyInit){
            this.initList();
        }else{
            this.on('focus', this.initList, this, {single: true});
        }
    },

    // private
    initValue : function(){
        Ext.form.ComboBox.superclass.initValue.call(this);
        if(this.hiddenField){
            this.hiddenField.value =
                Ext.value(Ext.isDefined(this.hiddenValue) ? this.hiddenValue : this.value, '');
        }
    },

    getParentZIndex : function(){
        var zindex;
        if (this.ownerCt){
            this.findParentBy(function(ct){
                zindex = parseInt(ct.getPositionEl().getStyle('z-index'), 10);
                return !!zindex;
            });
        }
        return zindex;
    },

    getZIndex : function(listParent){
        listParent = listParent || Ext.getDom(this.getListParent() || Ext.getBody());
        var zindex = parseInt(Ext.fly(listParent).getStyle('z-index'), 10);
        if(!zindex){
            zindex = this.getParentZIndex();
        }
        return (zindex || 12000) + 5;
    },

    // private
    initList : function(){
        if(!this.list){
            var cls = 'x-combo-list',
                listParent = Ext.getDom(this.getListParent() || Ext.getBody());

            this.list = new Ext.Layer({
                parentEl: listParent,
                shadow: this.shadow,
                cls: [cls, this.listClass].join(' '),
                constrain:false,
                zindex: this.getZIndex(listParent)
            });

            var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
            this.list.setSize(lw, 0);
            this.list.swallowEvent('mousewheel');
            this.assetHeight = 0;
            if(this.syncFont !== false){
                this.list.setStyle('font-size', this.el.getStyle('font-size'));
            }
            if(this.title){
                this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
                this.assetHeight += this.header.getHeight();
            }

            this.innerList = this.list.createChild({cls:cls+'-inner'});
            this.mon(this.innerList, 'mouseover', this.onViewOver, this);
            this.mon(this.innerList, 'mousemove', this.onViewMove, this);
            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));

            if(this.pageSize){
                this.footer = this.list.createChild({cls:cls+'-ft'});
                this.pageTb = new Ext.PagingToolbar({
                    store: this.store,
                    pageSize: this.pageSize,
                    renderTo:this.footer
                });
                this.assetHeight += this.footer.getHeight();
            }

            if(!this.tpl){
                /**
                * @cfg {String/Ext.XTemplate} tpl
The template string, or {@link Ext.XTemplate} instance to
                * use to display each item in the dropdown list. The dropdown list is displayed in a
                * DataView. See {@link #view}.

                *
The default template string is:

                  '<tpl for="."><div class="x-combo-list-item">{' + this.displayField + '}</div></tpl>'
                *

                *
Override the default value to create custom UI layouts for items in the list.
                * For example:

                  '<tpl for="."><div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}</div></tpl>'
                *

                *
The template must contain one or more substitution parameters using field
                * names from the Combo's {@link #store Store}. In the example above an
                *
ext:qtip
 attribute is added to display other fields from the Store.

                *
To preserve the default visual look of list items, add the CSS class name
                *
x-combo-list-item
 to the template's container element.

                *
Also see {@link #itemSelector} for additional details.

                */
                this.tpl = '<tpl for=".">
{' + this.displayField + '}
</tpl>';
                /**
                 * @cfg {String} itemSelector
                 *
A simple CSS selector (e.g. div.some-class or span:first-child) that will be
                 * used to determine what nodes the {@link #view Ext.DataView} which handles the dropdown
                 * display will be working with.

                 *
Note: this setting is required if a custom XTemplate has been
                 * specified in {@link #tpl} which assigns a class other than
'x-combo-list-item'

                 * to dropdown list items
                 */
            }

            /**
            * The {@link Ext.DataView DataView} used to display the ComboBox's options.
            * @type Ext.DataView
            */
            this.view = new Ext.DataView({
                applyTo: this.innerList,
                tpl: this.tpl,
                singleSelect: true,
                selectedClass: this.selectedClass,
                itemSelector: this.itemSelector || '.' + cls + '-item',
                emptyText: this.listEmptyText,
                deferEmptyText: false
            });

            this.mon(this.view, {
                containerclick : this.onViewClick,
                click : this.onViewClick,
                scope :this
            });

            this.bindStore(this.store, true);

            if(this.resizable){
                this.resizer = new Ext.Resizable(this.list,  {
                   pinned:true, handles:'se'
                });
                this.mon(this.resizer, 'resize', function(r, w, h){
                    this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
                    this.listWidth = w;
                    this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
                    this.restrictHeight();
                }, this);

                this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
            }
        }
    },

    /**
     *
Returns the element used to house this ComboBox's pop-up list. Defaults to the document body.

     * A custom implementation may be provided as a configuration option if the floating list needs to be rendered
     * to a different Element. An example might be rendering the list inside a Menu so that clicking
     * the list does not hide the Menu:

var store = new Ext.data.ArrayStore({
    autoDestroy: true,
    fields: ['initials', 'fullname'],
    data : [
        ['FF', 'Fred Flintstone'],
        ['BR', 'Barney Rubble']
    ]
});

var combo = new Ext.form.ComboBox({
    store: store,
    displayField: 'fullname',
    emptyText: 'Select a name...',
    forceSelection: true,
    getListParent: function() {
        return this.el.up('.x-menu');
    },
    iconCls: 'no-icon', //use iconCls if placing within menu to shift to right side of menu
    mode: 'local',
    selectOnFocus: true,
    triggerAction: 'all',
    typeAhead: true,
    width: 135
});

var menu = new Ext.menu.Menu({
    id: 'mainMenu',
    items: [
        combo // A Field in a Menu
    ]
});

     */
    getListParent : function() {
        return document.body;
    },

    /**
     * Returns the store associated with this combo.
     * @return {Ext.data.Store} The store
     */
    getStore : function(){
        return this.store;
    },

    // private
    bindStore : function(store, initial){
        if(this.store && !initial){
            if(this.store !== store && this.store.autoDestroy){
                this.store.destroy();
            }else{
                this.store.un('beforeload', this.onBeforeLoad, this);
                this.store.un('load', this.onLoad, this);
                this.store.un('exception', this.collapse, this);
            }
            if(!store){
                this.store = null;
                if(this.view){
                    this.view.bindStore(null);
                }
                if(this.pageTb){
                    this.pageTb.bindStore(null);
                }
            }
        }
        if(store){
            if(!initial) {
                this.lastQuery = null;
                if(this.pageTb) {
                    this.pageTb.bindStore(store);
                }
            }

            this.store = Ext.StoreMgr.lookup(store);
            this.store.on({
                scope: this,
                beforeload: this.onBeforeLoad,
                load: this.onLoad,
                exception: this.collapse
            });

            if(this.view){
                this.view.bindStore(store);
            }
        }
    },

    reset : function(){
        if(this.clearFilterOnReset && this.mode == 'local'){
            this.store.clearFilter();
        }
        Ext.form.ComboBox.superclass.reset.call(this);
    },

    // private
    initEvents : function(){
        Ext.form.ComboBox.superclass.initEvents.call(this);

        /**
         * @property keyNav
         * @type Ext.KeyNav
         *
A {@link Ext.KeyNav KeyNav} object which handles navigation keys for this ComboBox. This performs actions
         * based on keystrokes typed when the input field is focused.

         *
After the ComboBox has been rendered, you may override existing navigation key functionality,
         * or add your own based upon key names as specified in the {@link Ext.KeyNav KeyNav} class.

         *
The function is executed in the scope (this reference of the ComboBox. Example:

myCombo.keyNav.esc = function(e) {  // Override ESC handling function
    this.collapse();                // Standard behaviour of Ext's ComboBox.
    this.setValue(this.startValue); // We reset to starting value on ESC
};
myCombo.keyNav.tab = function() {   // Override TAB handling function
    this.onViewClick(false);        // Select the currently highlighted row
};

         */
        this.keyNav = new Ext.KeyNav(this.el, {
            "up" : function(e){
                this.inKeyMode = true;
                this.selectPrev();
            },

            "down" : function(e){
                if(!this.isExpanded()){
                    this.onTriggerClick();
                }else{
                    this.inKeyMode = true;
                    this.selectNext();
                }
            },

            "enter" : function(e){
                this.onViewClick();
            },

            "esc" : function(e){
                this.collapse();
            },

            "tab" : function(e){
                if (this.forceSelection === true) {
                    this.collapse();
                } else {
                    this.onViewClick(false);
                }
                return true;
            },

            scope : this,

            doRelay : function(e, h, hname){
                if(hname == 'down' || this.scope.isExpanded()){
                    // this MUST be called before ComboBox#fireKey()
                    var relay = Ext.KeyNav.prototype.doRelay.apply(this, arguments);
                    if((((Ext.isIE9 && Ext.isStrict) || Ext.isIE10p) || !Ext.isIE) && Ext.EventManager.useKeydown){
                        // call Combo#fireKey() for browsers which use keydown event (except IE)
                        this.scope.fireKey(e);
                    }
                    return relay;
                }
                return true;
            },

            forceKeyDown : true,
            defaultEventAction: 'stopEvent'
        });
        this.queryDelay = Math.max(this.queryDelay || 10,
                this.mode == 'local' ? 10 : 250);
        this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
        if(this.typeAhead){
            this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
        }
        if(!this.enableKeyEvents){
            this.mon(this.el, 'keyup', this.onKeyUp, this);
        }
    },

    // private
    onDestroy : function(){
        if (this.dqTask){
            this.dqTask.cancel();
            this.dqTask = null;
        }
        this.bindStore(null);
        Ext.destroy(
            this.resizer,
            this.view,
            this.pageTb,
            this.list
        );
        Ext.destroyMembers(this, 'hiddenField');
        Ext.form.ComboBox.superclass.onDestroy.call(this);
    },

    // private
    fireKey : function(e){
        if (!this.isExpanded()) {
            Ext.form.ComboBox.superclass.fireKey.call(this, e);
        }
    },

    // private
    onResize : function(w, h){
        Ext.form.ComboBox.superclass.onResize.apply(this, arguments);
        if(!isNaN(w) && this.isVisible() && this.list){
            this.doResize(w);
        }else{
            this.bufferSize = w;
        }
    },

    doResize: function(w){
        if(!Ext.isDefined(this.listWidth)){
            var lw = Math.max(w, this.minListWidth);
            this.list.setWidth(lw);
            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
        }
    },

    // private
    onEnable : function(){
        Ext.form.ComboBox.superclass.onEnable.apply(this, arguments);
        if(this.hiddenField){
            this.hiddenField.disabled = false;
        }
    },

    // private
    onDisable : function(){
        Ext.form.ComboBox.superclass.onDisable.apply(this, arguments);
        if(this.hiddenField){
            this.hiddenField.disabled = true;
        }
    },

    // private
    onBeforeLoad : function(){
        if(!this.hasFocus){
            return;
        }
        this.innerList.update(this.loadingText ?
               '
'+this.loadingText+'
' : '');
        this.restrictHeight();
        this.selectedIndex = -1;
    },

    // private
    onLoad : function(){
        if(!this.hasFocus){
            return;
        }
        if(this.store.getCount() > 0 || this.listEmptyText){
            this.expand();
            this.restrictHeight();
            if(this.lastQuery == this.allQuery){
                if(this.editable){
                    this.el.dom.select();
                }

                if(this.autoSelect !== false && !this.selectByValue(this.value, true)){
                    this.select(0, true);
                }
            }else{
                if(this.autoSelect !== false){
                    this.selectNext();
                }
                if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
                    this.taTask.delay(this.typeAheadDelay);
                }
            }
        }else{
            this.collapse();
        }

    },

    // private
    onTypeAhead : function(){
        if(this.store.getCount() > 0){
            var r = this.store.getAt(0);
            var newValue = r.data[this.displayField];
            var len = newValue.length;
            var selStart = this.getRawValue().length;
            if(selStart != len){
                this.setRawValue(newValue);
                this.selectText(selStart, newValue.length);
            }
        }
    },

    // private
    assertValue : function(){
        var val = this.getRawValue(),
            rec;

        if(this.valueField && Ext.isDefined(this.value)){
            rec = this.findRecord(this.valueField, this.value);
        }
        if(!rec || rec.get(this.displayField) != val){
            rec = this.findRecord(this.displayField, val);
        }
        if(!rec && this.forceSelection){
            if(val.length > 0 && val != this.emptyText){
                this.el.dom.value = Ext.value(this.lastSelectionText, '');
                this.applyEmptyText();
            }else{
                this.clearValue();
            }
        }else{
            if(rec && this.valueField){
                // onSelect may have already set the value and by doing so
                // set the display field properly.  Let's not wipe out the
                // valueField here by just sending the displayField.
                if (this.value == val){
                    return;
                }
                val = rec.get(this.valueField || this.displayField);
            }
            this.setValue(val);
        }
    },

    // private
    onSelect : function(record, index){
        if(this.fireEvent('beforeselect', this, record, index) !== false){
            this.setValue(record.data[this.valueField || this.displayField]);
            this.collapse();
            this.fireEvent('select', this, record, index);
        }
    },

    // inherit docs
    getName: function(){
        var hf = this.hiddenField;
        return hf && hf.name ? hf.name : this.hiddenName || Ext.form.ComboBox.superclass.getName.call(this);
    },

    /**
     * Returns the currently selected field value or empty string if no value is set.
     * @return {String} value The selected value
     */
    getValue : function(){
        if(this.valueField){
            return Ext.isDefined(this.value) ? this.value : '';
        }else{
            return Ext.form.ComboBox.superclass.getValue.call(this);
        }
    },

    /**
     * Clears any text/value currently set in the field
     */
    clearValue : function(){
        if(this.hiddenField){
            this.hiddenField.value = '';
        }
        this.setRawValue('');
        this.lastSelectionText = '';
        this.applyEmptyText();
        this.value = '';
    },

    /**
     * Sets the specified value into the field.  If the value finds a match, the corresponding record text
     * will be displayed in the field.  If the value does not match the data value of an existing item,
     * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
     * Otherwise the field will be blank (although the value will still be set).
     * @param {String} value The value to match
     * @return {Ext.form.Field} this
     */
    setValue : function(v){
        var text = v;
        if(this.valueField){
            var r = this.findRecord(this.valueField, v);
            if(r){
                text = r.data[this.displayField];
            }else if(Ext.isDefined(this.valueNotFoundText)){
                text = this.valueNotFoundText;
            }
        }
        this.lastSelectionText = text;
        if(this.hiddenField){
            this.hiddenField.value = Ext.value(v, '');
        }
        Ext.form.ComboBox.superclass.setValue.call(this, text);
        this.value = v;
        return this;
    },

    // private
    findRecord : function(prop, value){
        var record;
        if(this.store.getCount() > 0){
            this.store.each(function(r){
                if(r.data[prop] == value){
                    record = r;
                    return false;
                }
            });
        }
        return record;
    },

    // private
    onViewMove : function(e, t){
        this.inKeyMode = false;
    },

    // private
    onViewOver : function(e, t){
        if(this.inKeyMode){ // prevent key nav and mouse over conflicts
            return;
        }
        var item = this.view.findItemFromChild(t);
        if(item){
            var index = this.view.indexOf(item);
            this.select(index, false);
        }
    },

    // private
    onViewClick : function(doFocus){
        var index = this.view.getSelectedIndexes()[0],
            s = this.store,
            r = s.getAt(index);
        if(r){
            this.onSelect(r, index);
        }else {
            this.collapse();
        }
        if(doFocus !== false){
            this.el.focus();
        }
    },

    // private
    restrictHeight : function(){
        this.innerList.dom.style.height = '';
        var inner = this.innerList.dom,
            pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight,
            h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight),
            ha = this.getPosition()[1]-Ext.getBody().getScroll().top,
            hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,
            space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;

        h = Math.min(h, space, this.maxHeight);

        this.innerList.setHeight(h);
        this.list.beginUpdate();
        this.list.setHeight(h+pad);
        this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
        this.list.endUpdate();
    },

    /**
     * Returns true if the dropdown list is expanded, else false.
     */
    isExpanded : function(){
        return this.list && this.list.isVisible();
    },

    /**
     * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
     * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
     * @param {String} value The data value of the item to select
     * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
     * selected item if it is not currently in view (defaults to true)
     * @return {Boolean} True if the value matched an item in the list, else false
     */
    selectByValue : function(v, scrollIntoView){
        if(!Ext.isEmpty(v, true)){
            var r = this.findRecord(this.valueField || this.displayField, v);
            if(r){
                this.select(this.store.indexOf(r), scrollIntoView);
                return true;
            }
        }
        return false;
    },

    /**
     * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
     * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
     * @param {Number} index The zero-based index of the list item to select
     * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
     * selected item if it is not currently in view (defaults to true)
     */
    select : function(index, scrollIntoView){
        this.selectedIndex = index;
        this.view.select(index);
        if(scrollIntoView !== false){
            var el = this.view.getNode(index);
            if(el){
                this.innerList.scrollChildIntoView(el, false);
            }
        }

    },

    // private
    selectNext : function(){
        var ct = this.store.getCount();
        if(ct > 0){
            if(this.selectedIndex == -1){
                this.select(0);
            }else if(this.selectedIndex < ct-1){
                this.select(this.selectedIndex+1);
            }
        }
    },

    // private
    selectPrev : function(){
        var ct = this.store.getCount();
        if(ct > 0){
            if(this.selectedIndex == -1){
                this.select(0);
            }else if(this.selectedIndex !== 0){
                this.select(this.selectedIndex-1);
            }
        }
    },

    // private
    onKeyUp : function(e){
        var k = e.getKey();
        if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){

            this.lastKey = k;
            this.dqTask.delay(this.queryDelay);
        }
        Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
    },

    // private
    validateBlur : function(){
        return !this.list || !this.list.isVisible();
    },

    // private
    initQuery : function(){
        this.doQuery(this.getRawValue());
    },

    // private
    beforeBlur : function(){
        this.assertValue();
    },

    // private
    postBlur  : function(){
        Ext.form.ComboBox.superclass.postBlur.call(this);
        this.collapse();
        this.inKeyMode = false;
    },

    /**
     * Execute a query to filter the dropdown list.  Fires the {@link #beforequery} event prior to performing the
     * query allowing the query action to be canceled if needed.
     * @param {String} query The SQL query to execute
     * @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
     * characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option.  It
     * also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
     */
    doQuery : function(q, forceAll){
        q = Ext.isEmpty(q) ? '' : q;
        var qe = {
            query: q,
            forceAll: forceAll,
            combo: this,
            cancel:false
        };
        if(this.fireEvent('beforequery', qe)===false || qe.cancel){
            return false;
        }
        q = qe.query;
        forceAll = qe.forceAll;
        if(forceAll === true || (q.length >= this.minChars)){
            if(this.lastQuery !== q){
                this.lastQuery = q;
                if(this.mode == 'local'){
                    this.selectedIndex = -1;
                    if(forceAll){
                        this.store.clearFilter();
                    }else{
                        this.store.filter(this.displayField, q);
                    }
                    this.onLoad();
                }else{
                    this.store.baseParams[this.queryParam] = q;
                    this.store.load({
                        params: this.getParams(q)
                    });
                    this.expand();
                }
            }else{
                this.selectedIndex = -1;
                this.onLoad();
            }
        }
    },

    // private
    getParams : function(q){
        var params = {},
            paramNames = this.store.paramNames;
        if(this.pageSize){
            params[paramNames.start] = 0;
            params[paramNames.limit] = this.pageSize;
        }
        return params;
    },

    /**
     * Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
     */
    collapse : function(){
        if(!this.isExpanded()){
            return;
        }
        this.list.hide();
        Ext.getDoc().un('mousewheel', this.collapseIf, this);
        Ext.getDoc().un('mousedown', this.collapseIf, this);
        this.fireEvent('collapse', this);
    },

    // private
    collapseIf : function(e){
        if(!this.isDestroyed && !e.within(this.wrap) && !e.within(this.list)){
            this.collapse();
        }
    },

    /**
     * Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
     */
    expand : function(){
        if(this.isExpanded() || !this.hasFocus){
            return;
        }

        if(this.title || this.pageSize){
            this.assetHeight = 0;
            if(this.title){
                this.assetHeight += this.header.getHeight();
            }
            if(this.pageSize){
                this.assetHeight += this.footer.getHeight();
            }
        }

        if(this.bufferSize){
            this.doResize(this.bufferSize);
            delete this.bufferSize;
        }
        this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));

        // zindex can change, re-check it and set it if necessary
        this.list.setZIndex(this.getZIndex());
        this.list.show();
        if(Ext.isGecko2){
            this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
        }
        this.mon(Ext.getDoc(), {
            scope: this,
            mousewheel: this.collapseIf,
            mousedown: this.collapseIf
        });
        this.fireEvent('expand', this);
    },

    /**
     * @method onTriggerClick
     * @hide
     */
    // private
    // Implements the default empty TriggerField.onTriggerClick function
    onTriggerClick : function(){
        if(this.readOnly || this.disabled){
            return;
        }
        if(this.isExpanded()){
            this.collapse();
            this.el.focus();
        }else {
            this.onFocus({});
            if(this.triggerAction == 'all') {
                this.doQuery(this.allQuery, true);
            } else {
                this.doQuery(this.getRawValue());
            }
            this.el.focus();
        }
    }

    /**
     * @hide
     * @method autoSize
     */
    /**
     * @cfg {Boolean} grow @hide
     */
    /**
     * @cfg {Number} growMin @hide
     */
    /**
     * @cfg {Number} growMax @hide
     */

});
Ext.reg('combo', Ext.form.ComboBox);


text:
package serviceaccounts

import (
	"fmt"
	"time"

	kapi "k8s.io/kubernetes/pkg/api"
	kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/client/restclient"
	kclient "k8s.io/kubernetes/pkg/client/unversioned"
	adapter "k8s.io/kubernetes/pkg/client/unversioned/adapters/internalclientset"

	"github.com/openshift/origin/pkg/client"
)

// TokenRetriever defined an interface for getting an API token for a service account
type TokenRetriever interface {
	GetToken(serviceAccountNamespace, serviceAccountName string) (token string, err error)
}

// ClientLookupTokenRetriever uses its client to look up a service account token
type ClientLookupTokenRetriever struct {
	Client kclientset.Interface
}

// GetToken returns a token for the named service account or an error if none existed after a timeout
func (s *ClientLookupTokenRetriever) GetToken(namespace, name string) (string, error) {
	for i := 0; i < 30; i++ {
		// Wait on subsequent retries
		if i != 0 {
			time.Sleep(time.Second)
		}

		// Get the service account
		serviceAccount, err := s.Client.Core().ServiceAccounts(namespace).Get(name)
		if err != nil {
			continue
		}

		// Get the secrets
		// TODO: JTL: create one directly once we have that ability
		for _, secretRef := range serviceAccount.Secrets {
			secret, err2 := s.Client.Core().Secrets(namespace).Get(secretRef.Name)
			if err2 != nil {
				// Tolerate fetch errors on a particular secret
				continue
			}
			if IsValidServiceAccountToken(serviceAccount, secret) {
				// Return a valid token
				return string(secret.Data[kapi.ServiceAccountTokenKey]), nil
			}
		}
	}

	return "", fmt.Errorf("Could not get token for %s/%s", namespace, name)
}

// Clients returns an OpenShift and Kubernetes client with the credentials of the named service account
// TODO: change return types to client.Interface/kclientset.Interface to allow auto-reloading credentials
func Clients(config restclient.Config, tokenRetriever TokenRetriever, namespace, name string) (*restclient.Config, *client.Client, *kclient.Client, *kclientset.Clientset, error) {
	// Clear existing auth info
	config.Username = ""
	config.Password = ""
	config.CertFile = ""
	config.CertData = []byte{}
	config.KeyFile = ""
	config.KeyData = []byte{}
	config.BearerToken = ""

	kubeUserAgent := ""
	openshiftUserAgent := ""

	// they specified, don't mess with it
	if len(config.UserAgent) > 0 {
		kubeUserAgent = config.UserAgent
		openshiftUserAgent = config.UserAgent

	} else {
		kubeUserAgent = fmt.Sprintf("%s system:serviceaccount:%s:%s", restclient.DefaultKubernetesUserAgent(), namespace, name)
		openshiftUserAgent = fmt.Sprintf("%s system:serviceaccount:%s:%s", client.DefaultOpenShiftUserAgent(), namespace, name)
	}

	// For now, just initialize the token once
	// TODO: refetch the token if the client encounters 401 errors
	token, err := tokenRetriever.GetToken(namespace, name)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	config.BearerToken = token

	config.UserAgent = openshiftUserAgent
	c, err := client.New(&config)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	config.UserAgent = kubeUserAgent
	kc, err := kclient.New(&config)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	kcset := adapter.FromUnversionedClient(kc)

	return &config, c, kc, kcset, nil
}

// IsValidServiceAccountToken returns true if the given secret contains a service account token valid for the given service account
func IsValidServiceAccountToken(serviceAccount *kapi.ServiceAccount, secret *kapi.Secret) bool {
	if secret.Type != kapi.SecretTypeServiceAccountToken {
		return false
	}
	if secret.Namespace != serviceAccount.Namespace {
		return false
	}
	if secret.Annotations[kapi.ServiceAccountNameKey] != serviceAccount.Name {
		return false
	}
	if secret.Annotations[kapi.ServiceAccountUIDKey] != string(serviceAccount.UID) {
		return false
	}
	if len(secret.Data[kapi.ServiceAccountTokenKey]) == 0 {
		return false
	}
	return true
}


text:
CKEDITOR.editorConfig = function( config )
{
    // Define changes to default configuration here. For example:
    //config.language = 'en-au';
    //config.startupOutlineBlocks = true;
    //config.uiColor = '#AADC6E';
};


text:
export GO111MODULE=off

TAGS ?= seccomp
BUILDFLAGS := -tags "$(AUTOTAGS) $(TAGS)"
GO := go
PACKAGE := github.com/seccomp/containers-golang

sources := $(wildcard *.go)

.PHONY: seccomp.json
seccomp.json: $(sources)
	$(GO) build -compiler gc $(BUILDFLAGS) ./cmd/generate.go
	$(GO) build -compiler gc ./cmd/generate.go
	$(GO) run ${BUILDFLAGS} cmd/generate.go

all: seccomp.json

.PHONY: test-unit
test-unit:
	$(GO) test -v $(BUILDFLAGS) $(shell $(GO) list ./... | grep -v ^$(PACKAGE)/vendor)
	$(GO) test -v $(shell $(GO) list ./... | grep -v ^$(PACKAGE)/vendor)

.PHONY: vendor
vendor:
	export GO111MODULE=on \
		$(GO) mod tidy && \
		$(GO) mod vendor && \
		$(GO) mod verify

.PHONY: clean
clean:
	rm -f generate


text:
package edu.neu.ccs.pyramid.multilabel_classification.cbm;

import edu.neu.ccs.pyramid.classification.PriorProbClassifier;
import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticLoss;
import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticRegression;
import edu.neu.ccs.pyramid.classification.logistic_regression.RidgeLogisticOptimizer;
import edu.neu.ccs.pyramid.dataset.DataSetUtil;
import edu.neu.ccs.pyramid.dataset.MultiLabelClfDataSet;
import edu.neu.ccs.pyramid.optimization.LBFGS;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * CBM optimizer for LR base learners
 * Created by chengli on 3/21/17.
 */
public class LRCBMOptimizer extends AbstractCBMOptimizer {
    private static final Logger logger = LogManager.getLogger();
    // regularization for multiClassClassifier
    private double priorVarianceMultiClass =1;
    // regularization for binary logisticRegression
    private double priorVarianceBinary =1;

    private double initialStepSize=1;

    public LRCBMOptimizer(CBM cbm, MultiLabelClfDataSet dataSet) {
        super(cbm, dataSet);
    }

    public void setPriorVarianceMultiClass(double priorVarianceMultiClass) {
        this.priorVarianceMultiClass = priorVarianceMultiClass;
    }

    public void setPriorVarianceBinary(double priorVarianceBinary) {
        this.priorVarianceBinary = priorVarianceBinary;
    }

    public void setInitialStepSize(double initialStepSize) {
        this.initialStepSize = initialStepSize;
    }

    @Override
    protected void updateBinaryClassifier(int component, int label, MultiLabelClfDataSet activeDataset, double[] activeGammas) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        if (cbm.binaryClassifiers[component][label] == null || cbm.binaryClassifiers[component][label] instanceof PriorProbClassifier){
            cbm.binaryClassifiers[component][label] = new LogisticRegression(2, activeDataset.getNumFeatures());
        }

        RidgeLogisticOptimizer ridgeLogisticOptimizer;

        int[] binaryLabels = DataSetUtil.toBinaryLabels(activeDataset.getMultiLabels(), label);
        // no parallelism
        ridgeLogisticOptimizer = new RidgeLogisticOptimizer((LogisticRegression)cbm.binaryClassifiers[component][label],
                activeDataset, binaryLabels, activeGammas, priorVarianceBinary, false);

        ((LBFGS)ridgeLogisticOptimizer.getOptimizer()).getLineSearcher().setInitialStepLength(initialStepSize);

        ridgeLogisticOptimizer.getOptimizer().getTerminator().setMaxIteration(binaryUpdatesPerIter);
        ridgeLogisticOptimizer.optimize();
        if (logger.isDebugEnabled()){
            logger.debug("time spent on updating component "+component+" label "+label+" = "+stopWatch);
        }
    }

    @Override
    protected void updateMultiClassClassifier() {
        if (logger.isDebugEnabled()){
            logger.debug("start updateMultiClassClassifier");
        }
        // parallel
        RidgeLogisticOptimizer ridgeLogisticOptimizer = new RidgeLogisticOptimizer((LogisticRegression)cbm.multiClassClassifier,
                dataSet, gammas, priorVarianceMultiClass, true);

        ((LBFGS)ridgeLogisticOptimizer.getOptimizer()).getLineSearcher().setInitialStepLength(initialStepSize);

        ridgeLogisticOptimizer.getOptimizer().getTerminator().setMaxIteration(multiclassUpdatesPerIter);
        ridgeLogisticOptimizer.optimize();
        if (logger.isDebugEnabled()){
            logger.debug("finish updateMultiClassClassifier");
        }
    }

    // todo deal with prior classifier
    @Override
    protected double binaryObj(int component, int classIndex) {
        int[] binaryLabels = DataSetUtil.toBinaryLabels(dataSet.getMultiLabels(), classIndex);
        double[][] targetsDistribution = DataSetUtil.labelsToDistributions(binaryLabels, 2);
        double[] weights = new double[dataSet.getNumDataPoints()];
        for (int i=0;i<dataSet.getNumDataPoints();i++){
            weights[i] = gammas[i][component];
        }
        LogisticLoss logisticLoss = new LogisticLoss((LogisticRegression) cbm.binaryClassifiers[component][classIndex],
                dataSet, weights, targetsDistribution, priorVarianceBinary, false);
        return logisticLoss.getValue();
    }

    @Override
    protected double multiClassClassifierObj() {
        LogisticLoss logisticLoss =  new LogisticLoss((LogisticRegression) cbm.multiClassClassifier,
                dataSet, gammas, priorVarianceMultiClass, true);
        return logisticLoss.getValue();
    }
}


text:
Format of the definition:
<radiogroup class="form-group">
    {% for definition in form-data.definitions %}

        {{ definition.name }} details
        <input type="radio" name="spec-format" value="{{ definition.name }}" {% if definition.checked %}checked {% endif %}/>

    {% endfor %}
</radiogroup>