text:
package bleve

import (
	"encoding/json"
	"fmt"
	"os"
	"sync"
	"sync/atomic"
	"time"

	"github.com/blevesearch/bleve/document"
	"github.com/blevesearch/bleve/index"
	"github.com/blevesearch/bleve/index/store"
	"github.com/blevesearch/bleve/index/upside_down"
	"github.com/blevesearch/bleve/registry"
	"github.com/blevesearch/bleve/search"
	"github.com/blevesearch/bleve/search/collectors"
	"github.com/blevesearch/bleve/search/facets"
)

type indexImpl struct {
	path  string
	meta  *indexMeta
	s     store.KVStore
	i     index.Index
	m     *IndexMapping
	mutex sync.RWMutex
	open  bool
	stats *IndexStat
}

const storePath = "store"

var mappingInternalKey = []byte("_mapping")

func indexStorePath(path string) string {
	return path + string(os.PathSeparator) + storePath
}

func newMemIndex(mapping *IndexMapping) (*indexImpl, error) {
	rv := indexImpl{
		path:  "",
		m:     mapping,
		meta:  newIndexMeta("mem", nil),
		stats: &IndexStat{},
	}

	storeConstructor := registry.KVStoreConstructorByName(rv.meta.Storage)
	if storeConstructor == nil {
		return nil, ErrorUnknownStorageType
	}
	// now open the store
	var err error
	rv.s, err = storeConstructor(nil)
	if err != nil {
		return nil, err
	}

	// open the index
	rv.i = upside_down.NewUpsideDownCouch(rv.s, Config.analysisQueue)
	err = rv.i.Open()
	if err != nil {
		return nil, err
	}
	rv.stats.indexStat = rv.i.Stats()

	// now persist the mapping
	mappingBytes, err := json.Marshal(mapping)
	if err != nil {
		return nil, err
	}
	err = rv.i.SetInternal(mappingInternalKey, mappingBytes)
	if err != nil {
		return nil, err
	}

	// mark the index as open
	rv.mutex.Lock()
	defer rv.mutex.Unlock()
	rv.open = true
	return &rv, nil
}

func newIndexUsing(path string, mapping *IndexMapping, kvstore string, kvconfig map[string]interface{}) (*indexImpl, error) {
	// first validate the mapping
	err := mapping.validate()
	if err != nil {
		return nil, err
	}

	if path == "" {
		return newMemIndex(mapping)
	}

	if kvconfig == nil {
		kvconfig = map[string]interface{}{}
	}

	rv := indexImpl{
		path:  path,
		m:     mapping,
		meta:  newIndexMeta(kvstore, kvconfig),
		stats: &IndexStat{},
	}
	storeConstructor := registry.KVStoreConstructorByName(rv.meta.Storage)
	if storeConstructor == nil {
		return nil, ErrorUnknownStorageType
	}
	// at this point there is hope that we can be successful, so save index meta
	err = rv.meta.Save(path)
	if err != nil {
		return nil, err
	}
	kvconfig["create_if_missing"] = true
	kvconfig["error_if_exists"] = true
	kvconfig["path"] = indexStorePath(path)

	// now create the store
	rv.s, err = storeConstructor(kvconfig)
	if err != nil {
		return nil, err
	}

	// open the index
	rv.i = upside_down.NewUpsideDownCouch(rv.s, Config.analysisQueue)
	err = rv.i.Open()
	if err != nil {
		return nil, err
	}
	rv.stats.indexStat = rv.i.Stats()

	// now persist the mapping
	mappingBytes, err := json.Marshal(mapping)
	if err != nil {
		return nil, err
	}
	err = rv.i.SetInternal(mappingInternalKey, mappingBytes)
	if err != nil {
		return nil, err
	}

	// mark the index as open
	rv.mutex.Lock()
	defer rv.mutex.Unlock()
	rv.open = true
	return &rv, nil
}

func openIndexUsing(path string, runtimeConfig map[string]interface{}) (rv *indexImpl, err error) {

	rv = &indexImpl{
		path:  path,
		stats: &IndexStat{},
	}

	rv.meta, err = openIndexMeta(path)
	if err != nil {
		return nil, err
	}

	storeConstructor := registry.KVStoreConstructorByName(rv.meta.Storage)
	if storeConstructor == nil {
		return nil, ErrorUnknownStorageType
	}

	storeConfig := rv.meta.Config
	if storeConfig == nil {
		storeConfig = map[string]interface{}{}
	}

	storeConfig["path"] = indexStorePath(path)
	storeConfig["create_if_missing"] = false
	storeConfig["error_if_exists"] = false
	for rck, rcv := range runtimeConfig {
		storeConfig[rck] = rcv
	}

	// now open the store
	rv.s, err = storeConstructor(storeConfig)
	if err != nil {
		return nil, err
	}

	// open the index
	rv.i = upside_down.NewUpsideDownCouch(rv.s, Config.analysisQueue)
	err = rv.i.Open()
	if err != nil {
		return nil, err
	}
	rv.stats.indexStat = rv.i.Stats()

	// now load the mapping
	indexReader, err := rv.i.Reader()
	if err != nil {
		return nil, err
	}
	defer func() {
		if cerr := indexReader.Close(); cerr != nil && err == nil {
			err = cerr
		}
	}()

	mappingBytes, err := indexReader.GetInternal(mappingInternalKey)
	if err != nil {
		return nil, err
	}

	var im IndexMapping
	err = json.Unmarshal(mappingBytes, &im)
	if err != nil {
		return nil, err
	}

	// mark the index as open
	rv.mutex.Lock()
	defer rv.mutex.Unlock()
	rv.open = true

	// validate the mapping
	err = im.validate()
	if err != nil {
		// note even if the mapping is invalid
		// we still return an open usable index
		return rv, err
	}

	rv.m = &im
	return rv, err
}

// Advanced returns implementation internals
// necessary ONLY for advanced usage.
func (i *indexImpl) Advanced() (index.Index, store.KVStore, error) {
	return i.i, i.s, nil
}

// Mapping returns the IndexMapping in use by this
// Index.
func (i *indexImpl) Mapping() *IndexMapping {
	return i.m
}

// Index the object with the specified identifier.
// The IndexMapping for this index will determine
// how the object is indexed.
func (i *indexImpl) Index(id string, data interface{}) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	doc := document.NewDocument(id)
	err := i.m.mapDocument(doc, data)
	if err != nil {
		return err
	}
	err = i.i.Update(doc)
	if err != nil {
		return err
	}
	return nil
}

// Delete entries for the specified identifier from
// the index.
func (i *indexImpl) Delete(id string) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	err := i.i.Delete(id)
	if err != nil {
		return err
	}
	return nil
}

// Batch executes multiple Index and Delete
// operations at the same time.  There are often
// significant performance benefits when performing
// operations in a batch.
func (i *indexImpl) Batch(b *Batch) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	return i.i.Batch(b.internal)
}

// Document is used to find the values of all the
// stored fields for a document in the index.  These
// stored fields are put back into a Document object
// and returned.
func (i *indexImpl) Document(id string) (doc *document.Document, err error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}
	indexReader, err := i.i.Reader()
	if err != nil {
		return nil, err
	}
	defer func() {
		if cerr := indexReader.Close(); err == nil && cerr != nil {
			err = cerr
		}
	}()

	doc, err = indexReader.Document(id)
	if err != nil {
		return nil, err
	}
	return doc, nil
}

// DocCount returns the number of documents in the
// index.
func (i *indexImpl) DocCount() (uint64, error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return 0, ErrorIndexClosed
	}

	return i.i.DocCount()
}

// Search executes a search request operation.
// Returns a SearchResult object or an error.
func (i *indexImpl) Search(req *SearchRequest) (sr *SearchResult, err error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	searchStart := time.Now()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	collector := collectors.NewTopScorerSkipCollector(req.Size, req.From)

	// open a reader for this search
	indexReader, err := i.i.Reader()
	if err != nil {
		return nil, fmt.Errorf("error opening index reader %v", err)
	}
	defer func() {
		if cerr := indexReader.Close(); err == nil && cerr != nil {
			err = cerr
		}
	}()

	searcher, err := req.Query.Searcher(indexReader, i.m, req.Explain)
	if err != nil {
		return nil, err
	}
	defer func() {
		if serr := searcher.Close(); err == nil && serr != nil {
			err = serr
		}
	}()

	if req.Facets != nil {
		facetsBuilder := search.NewFacetsBuilder(indexReader)
		for facetName, facetRequest := range req.Facets {
			if facetRequest.NumericRanges != nil {
				// build numeric range facet
				facetBuilder := facets.NewNumericFacetBuilder(facetRequest.Field, facetRequest.Size)
				for _, nr := range facetRequest.NumericRanges {
					facetBuilder.AddRange(nr.Name, nr.Min, nr.Max)
				}
				facetsBuilder.Add(facetName, facetBuilder)
			} else if facetRequest.DateTimeRanges != nil {
				// build date range facet
				facetBuilder := facets.NewDateTimeFacetBuilder(facetRequest.Field, facetRequest.Size)
				dateTimeParser := i.m.dateTimeParserNamed(i.m.DefaultDateTimeParser)
				for _, dr := range facetRequest.DateTimeRanges {
					dr.ParseDates(dateTimeParser)
					facetBuilder.AddRange(dr.Name, dr.Start, dr.End)
				}
				facetsBuilder.Add(facetName, facetBuilder)
			} else {
				// build terms facet
				facetBuilder := facets.NewTermsFacetBuilder(facetRequest.Field, facetRequest.Size)
				facetsBuilder.Add(facetName, facetBuilder)
			}
		}
		collector.SetFacetsBuilder(facetsBuilder)
	}

	err = collector.Collect(searcher)
	if err != nil {
		return nil, err
	}

	hits := collector.Results()

	if req.Highlight != nil {
		// get the right highlighter
		highlighter, err := Config.Cache.HighlighterNamed(Config.DefaultHighlighter)
		if err != nil {
			return nil, err
		}
		if req.Highlight.Style != nil {
			highlighter, err = Config.Cache.HighlighterNamed(*req.Highlight.Style)
			if err != nil {
				return nil, err
			}
		}
		if highlighter == nil {
			return nil, fmt.Errorf("no highlighter named `%s` registered", *req.Highlight.Style)
		}

		for _, hit := range hits {
			doc, err := indexReader.Document(hit.ID)
			if err == nil {
				highlightFields := req.Highlight.Fields
				if highlightFields == nil {
					// add all fields with matches
					highlightFields = make([]string, 0, len(hit.Locations))
					for k := range hit.Locations {
						highlightFields = append(highlightFields, k)
					}
				}

				for _, hf := range highlightFields {
					highlighter.BestFragmentsInField(hit, doc, hf, 1)
				}
			}
		}
	}

	if len(req.Fields) > 0 {
		for _, hit := range hits {
			// FIXME avoid loading doc second time
			// if we already loaded it for highlighting
			doc, err := indexReader.Document(hit.ID)
			if err == nil {
				for _, f := range req.Fields {
					for _, docF := range doc.Fields {
						if f == "*" || docF.Name() == f {
							var value interface{}
							switch docF := docF.(type) {
							case *document.TextField:
								value = string(docF.Value())
							case *document.NumericField:
								num, err := docF.Number()
								if err == nil {
									value = num
								}
							case *document.DateTimeField:
								datetime, err := docF.DateTime()
								if err == nil {
									value = datetime.Format(time.RFC3339)
								}
							}
							if value != nil {
								hit.AddFieldValue(docF.Name(), value)
							}
						}
					}
				}
			}
		}
	}

	atomic.AddUint64(&i.stats.searches, 1)
	searchDuration := time.Since(searchStart)
	atomic.AddUint64(&i.stats.searchTime, uint64(searchDuration))

	if searchDuration > Config.SlowSearchLogThreshold {
		logger.Printf("slow search took %s - %v", searchDuration, req)
	}

	return &SearchResult{
		Request:  req,
		Hits:     hits,
		Total:    collector.Total(),
		MaxScore: collector.MaxScore(),
		Took:     searchDuration,
		Facets:   collector.FacetResults(),
	}, nil
}

// Fields returns the name of all the fields this
// Index has operated on.
func (i *indexImpl) Fields() (fields []string, err error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	indexReader, err := i.i.Reader()
	if err != nil {
		return nil, err
	}
	defer func() {
		if cerr := indexReader.Close(); err == nil && cerr != nil {
			err = cerr
		}
	}()

	fields, err = indexReader.Fields()
	if err != nil {
		return nil, err
	}
	return fields, nil
}

func (i *indexImpl) FieldDict(field string) (index.FieldDict, error) {
	i.mutex.RLock()

	if !i.open {
		i.mutex.RUnlock()
		return nil, ErrorIndexClosed
	}

	indexReader, err := i.i.Reader()
	if err != nil {
		i.mutex.RUnlock()
		return nil, err
	}

	fieldDict, err := indexReader.FieldDict(field)
	if err != nil {
		i.mutex.RUnlock()
		return nil, err
	}

	return &indexImplFieldDict{
		index:       i,
		indexReader: indexReader,
		fieldDict:   fieldDict,
	}, nil
}

func (i *indexImpl) FieldDictRange(field string, startTerm []byte, endTerm []byte) (index.FieldDict, error) {
	i.mutex.RLock()

	if !i.open {
		i.mutex.RUnlock()
		return nil, ErrorIndexClosed
	}

	indexReader, err := i.i.Reader()
	if err != nil {
		i.mutex.RUnlock()
		return nil, err
	}

	fieldDict, err := indexReader.FieldDictRange(field, startTerm, endTerm)
	if err != nil {
		i.mutex.RUnlock()
		return nil, err
	}

	return &indexImplFieldDict{
		index:       i,
		indexReader: indexReader,
		fieldDict:   fieldDict,
	}, nil
}

func (i *indexImpl) FieldDictPrefix(field string, termPrefix []byte) (index.FieldDict, error) {
	i.mutex.RLock()

	if !i.open {
		i.mutex.RUnlock()
		return nil, ErrorIndexClosed
	}

	indexReader, err := i.i.Reader()
	if err != nil {
		i.mutex.RUnlock()
		return nil, err
	}

	fieldDict, err := indexReader.FieldDictPrefix(field, termPrefix)
	if err != nil {
		i.mutex.RUnlock()
		return nil, err
	}

	return &indexImplFieldDict{
		index:       i,
		indexReader: indexReader,
		fieldDict:   fieldDict,
	}, nil
}

// DumpAll writes all index rows to a channel.
// INTERNAL: do not rely on this function, it is
// only intended to be used by the debug utilities
func (i *indexImpl) DumpAll() chan interface{} {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}

	return i.i.DumpAll()
}

// DumpFields writes all field rows in the index
// to a channel.
// INTERNAL: do not rely on this function, it is
// only intended to be used by the debug utilities
func (i *indexImpl) DumpFields() chan interface{} {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}
	return i.i.DumpFields()
}

// DumpDoc writes all rows in the index associated
// with the specified identifier to a channel.
// INTERNAL: do not rely on this function, it is
// only intended to be used by the debug utilities
func (i *indexImpl) DumpDoc(id string) chan interface{} {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil
	}
	return i.i.DumpDoc(id)
}

func (i *indexImpl) Close() error {
	i.mutex.Lock()
	defer i.mutex.Unlock()

	i.open = false
	return i.i.Close()
}

func (i *indexImpl) Stats() *IndexStat {
	return i.stats
}

func (i *indexImpl) GetInternal(key []byte) (val []byte, err error) {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return nil, ErrorIndexClosed
	}

	reader, err := i.i.Reader()
	if err != nil {
		return nil, err
	}
	defer func() {
		if cerr := reader.Close(); err == nil && cerr != nil {
			err = cerr
		}
	}()

	val, err = reader.GetInternal(key)
	if err != nil {
		return nil, err
	}
	return val, nil
}

func (i *indexImpl) SetInternal(key, val []byte) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	return i.i.SetInternal(key, val)
}

func (i *indexImpl) DeleteInternal(key []byte) error {
	i.mutex.RLock()
	defer i.mutex.RUnlock()

	if !i.open {
		return ErrorIndexClosed
	}

	return i.i.DeleteInternal(key)
}

// NewBatch creates a new empty batch.
func (i *indexImpl) NewBatch() *Batch {
	return &Batch{
		index:    i,
		internal: index.NewBatch(),
	}
}

type indexImplFieldDict struct {
	index       *indexImpl
	indexReader index.IndexReader
	fieldDict   index.FieldDict
}

func (f *indexImplFieldDict) Next() (*index.DictEntry, error) {
	return f.fieldDict.Next()
}

func (f *indexImplFieldDict) Close() error {
	defer f.index.mutex.RUnlock()
	err := f.fieldDict.Close()
	if err != nil {
		return err
	}
	return f.indexReader.Close()
}


text:
package jps

import "strconv"

//RangeAll returns a Range which covers all the data.
//It ranges from the first byte (0), to the last byte (-1).
func RangeAll() Range { return Range{0, -1} }

//Range represents a byte range from Start to End (inclusive).
//If byte values are posative, then they are absolute offsets with 0 being the first byte of the file.
//Negative byte index's are from the end of the file, with -1 being the last byte, and -2 being the second to last byte etc.
type Range struct {
	Start int64
	End   int64
}

//NewRange returns a Range struct with the given start and end indexs.
//Note that Range values are inclusive.
func NewRange(start, end int64) Range {
	return Range{start, end}
}

//StartEnd returns the start and end byte indexs (inclusive) for a file with the given size.
//Aka, if either r.Start or r.End is negative, the size is added to them.
//Also see r.Abs, which returns a Range type given a size.
func (r Range) StartEnd(size int64) (int64, int64) {
	r = r.Abs(size)
	return r.Start, r.End
}

//Abs returns a new Range struct with absolute (non-negative) byte indexs.
//These are calculated using the given size - aka, if either r.Start or r.End is negative, the size is added to them.
//This function is used for r.StartEnd(size).
func (r Range) Abs(size int64) Range {
	if r.Start < 0 {
		r.Start += size
	}
	if r.End < 0 {
		r.End += size
	}
	return r
}

//IsAbsolute returns true if the Range is absolute.
//A Range is absolute when it does not depend on the size of the data it is a range of - aka when neither r.Start nor r.End are nagative.
//r.Abs(size) can be used to generate an absolute byte range.
func (r Range) IsAbsolute() bool {
	return r.Start >= 0 && r.End >= 0
}

//Length returns the length of the range.
//If the length is dependent on the size of the data to range over, then the sizeMul != 0 and the length is `l+sizeMul*size`
//See r.AbsLength(size) if you already know the size of the data.
func (r Range) Length() (l int64, sizeMul int64) {
	/* The cases are as follows:
	 * r.Start > 0 && r.End > 0 (the range is absolute):
	 *     l = r.End - r.Start + 1; sizeMul = 0
	 * r.Start < 0 && e.End < 0 (the range is 'absolute from the end' - both offsets are fixed from the end of the data):
	 *     l = r.End - r.Start + 1; sizeMul = 0
	 * r.Start > 0 && e.End < 0 (a fixed start byte, and a end byte dependent on the length):
	 *     l = (r.End + size) - r.Start + 1
	 *     => l = r.End - r.Start + 1; sizeMul = 1
	 * r.Start < 0 && r.End > 0 (I don't know why you'd want this type of range...):
	 *     l = r.End - (r.Start + size) + 1
	 *     => l = r.End - r.Start + 1; sizeMul = -1
	 */
	l = r.End - r.Start + 1
	if r.Start < 0 {
		if r.End > 0 {
			sizeMul = -1
		}
	} else if r.End < 0 {
		sizeMul = 1
	}
	return
}

func (r Range) isNoLength() bool {
	if r.Start < 0 && r.End > 0 {
		return false
	}
	if r.End < 0 {
		return false
	}
	return r.End-r.Start < 0
}

//AbsLength : if r is used on data with size `size`, then r.AbsLength(size) returns the abount of bytes within the range r.
//l, sizeMul := r.Length(); return l + sizeMul*size  (see r.Length())
func (r Range) AbsLength(size int64) int64 {
	//Warning: this function works on the basis that Length is defined to return the value which makes this expression correct;
	// you should probably not change this unless you are changing r.Length().
	l, sizeMul := r.Length()
	return l + sizeMul*size
}

func (r Range) String() string {
	return "Range{ " + strconv.FormatInt(r.Start, 10) + " - " + strconv.FormatInt(r.End, 10) + " }"
}

//SortRanges sorts the given ranges (in place) in assending order of their Start value.
func SortRanges(rs []Range) {
	for i := 1; i < len(rs); i++ {
		r := rs[i]
		for j := i - 1; 0 <= j && r.Start < rs[j].Start; j-- {
			rs[j+1] = rs[j]
			rs[j] = r
		}
	}
}

//MergeRanges, for all i, merges range i with i+1 if they overlap.
//This doesn't merge overlaping ranges if there is a non-overlaping range between them. This is
// to allow for data requested first to be delivered first, as noted in the HTTP spec.
//If you don't care about the order of ranges, which is permittable, then sorting before calling
// this function will merge all overlaping ranges.
//This does merging in place, then returns a slice of the origional slice. So the slice passed
// should not be used afterwards.
func MergeRanges(rs []Range) []Range {
	if len(rs) == 0 {
		return rs
	}
	//Remove the first element if it's a 0 length range.
	r1 := rs[0]
	if r1.isNoLength() {
		return MergeRanges(rs[1:])
	}
	for i := 1; i < len(rs); {
		//We will uphold r1 = rs[i-1]; r2 = rs[i]
		r2 := rs[i]
		if r2.Start >= 0 {
			if r2.End >= 0 {
				if r2.End < r2.Start {
					// Remove <=0 length ranges
					rs = rs[:i+copy(rs[i:], rs[i+1:])]
					continue
				}
				if r1.Start >= 0 {
					// Both have absolute starting positions
					if r1.Start <= r2.Start {
						// r1 comes first
						if r2.Start <= r1.End {
							// They overlap!
							// Merge r2 in to r1
							if r1.End < r2.End {
								r1.End = r2.End
								rs[i-1].End = r2.End
							}
							// Remove r2
							rs = rs[:i+copy(rs[i:], rs[i+1:])]
							continue
						} // else they don't overlap
					} else {
						// r2 comes first
						if r1.Start <= r2.End {
							// They overlap...
							// So merge r2 to r1
							r1.Start = r2.Start
							if r1.End < r2.End {
								r1.End = r2.End
							}
							rs[i-1] = r1
							// Remove r2
							rs = rs[:i+copy(rs[i:], rs[i+1:])]
							continue
						} // else they don't overlap
					}
				}
			}
		} // for now, we only merge absolute ranges TODO: check End?
		r1 = r2
		i++
	}
	return rs
}

//TidyRanges uses SortRanges then MergeRanges on rs, producing a list of sorted and non-overlaping
// ranges.
//This algorithm modifies the origional slice so the slice passed should not be used afterwards.
func TidyRanges(rs []Range) []Range {
	SortRanges(rs)
	return MergeRanges(rs)
}

redpajama_set_name: RedPajamaGithub


text:
import { useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useModal, ErrorDisplay, useConfirm, LoadQueryWrapper } from '@neinteractiveliterature/litform';

import ConventionFormHeader from '../ConventionAdmin/ConventionFormHeader';
import { useConventionQueryFromIdParam } from './conventionQueryHooks';
import NewConventionModal from './NewConventionModal';
import usePageTitle from '../usePageTitle';
import { useSetConventionCanceledMutation } from './mutations.generated';
import humanize from '../humanize';

export default LoadQueryWrapper(useConventionQueryFromIdParam, function ConventionDisplay({ data }) {
  const confirm = useConfirm();
  const cloneModal = useModal();
  const [setConventionCanceled] = useSetConventionCanceledMutation();
  const location = useLocation();

  const { close: closeCloneModal } = cloneModal;

  usePageTitle(data.convention.name);
  useEffect(() => {
    closeCloneModal();
  }, [closeCloneModal, location.pathname]);

  const { convention } = data;
  const { organization } = convention;
  const conventionUrl = new URL(`//${convention.domain}`, window.location.href);
  conventionUrl.port = window.location.port;
  const editConventionSettingsUrl = new URL(conventionUrl.toString(), window.location.href);
  editConventionSettingsUrl.pathname = '/convention/edit';

  return (
    <>
      <ConventionFormHeader convention={convention} />

Ticket mode

{humanize(convention.ticket_mode)}

Organization

          {organization ? <Link to={`/organizations/${organization.id}`}>{organization.name}</Link> : 'None'}

Web site

          {conventionUrl.toString()}

Email from

{convention.email_from}

          Edit convention settings

        <button type="button" className="btn btn-outline-secondary me-2" onClick={cloneModal.open}>
          Clone convention
        </button>

        {convention.canceled ? (
          <button
            type="button"
            className="btn btn-outline-danger"
            onClick={() =>
              confirm({
                prompt: `Are you sure you want to uncancel ${convention.name}?`,
                action: () =>
                  setConventionCanceled({
                    variables: { id: convention.id, canceled: false },
                  }),
                renderError: (e) => <ErrorDisplay graphQLError={e} />,
              })
            }
          >
            Uncancel convention
          </button>
        ) : (
          <button
            type="button"
            className="btn btn-outline-danger"
            onClick={() =>
              confirm({
                prompt: `Are you sure you want to cancel ${convention.name}?`,
                action: () =>
                  setConventionCanceled({
                    variables: { id: convention.id, canceled: true },
                  }),
                renderError: (e) => <ErrorDisplay graphQLError={e} />,
              })
            }
          >
            Cancel convention
          </button>
        )}

      <NewConventionModal visible={cloneModal.visible} close={cloneModal.close} cloneConvention={convention} />
    </>
  );
});


text:
/**
 * @Author: will
 * @Date:   2017-09-07T20:49:16+08:00
 * @Filename: TabView.js
 * @Last modified by:   will
 * @Last modified time: 2017-09-12T12:26:32+08:00
 */

// TabView.js

'use strict';

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {StyleSheet, View} from 'react-native';

import Theme from '../themes/Theme';
import TabSheet from './TabSheet';
import TabButton from './TabButton';
import Projector from '../Projector/Projector';
import Carousel from '../Carousel/Carousel';

export default class TabView extends Component {

  static propTypes = {
    ...View.propTypes,
    type: PropTypes.oneOf(['projector', 'carousel']),
    barStyle: View.propTypes.style,
    activeIndex: PropTypes.number,
    onChange: PropTypes.func, //(index)
  };

  static defaultProps = {
    ...View.defaultProps,
    type: 'projector',
  };

  static Sheet = TabSheet;
  static Button = TabButton;

  constructor(props) {
    super(props);
    this.state = {
      activeIndex: this.props.activeIndex ? this.props.activeIndex : 0,
    };
  }

  get activeIndex() {
    let activeIndex = this.props.activeIndex;
    if (activeIndex || activeIndex === 0) return activeIndex;
    else return this.state.activeIndex;
  }

  buildProps() {
    let {style, barStyle, children, ...others} = this.props;

    style = [{
      flexDirection: 'column',
      alignItems: 'stretch',
    }].concat(style);
    barStyle = [{
      backgroundColor: Theme.tvBarColor,
      position: 'absolute',
      left: 0,
      bottom: 0,
      right: 0,
      height: Theme.tvBarHeight,
      paddingTop: Theme.tvBarPaddingTop,
      paddingBottom: Theme.tvBarPaddingBottom,
      borderTopWidth: Theme.tvBarSeparatorWidth,
      borderColor: Theme.tvBarSeparatorColor,
    }].concat(barStyle);
    barStyle = StyleSheet.flatten(barStyle);
    let {height, paddingTop, paddingBottom} = barStyle;
    let buttonContainerStyle = {
      position: 'absolute',
      left: 0,
      bottom: 0,
      right: 0,
      paddingTop,
      paddingBottom,
      flexDirection: 'row',
      alignItems: 'flex-end',
      justifyContent: 'space-around',
    };
    let buttonStyle = {
      minHeight: height - paddingTop - paddingBottom,
    };

    if (!(children instanceof Array)) {
      if (children) children = [children];
      else children = [];
    }
    children = children.filter(item => item); //remove empty item

    this.props = {style, barStyle, buttonContainerStyle, buttonStyle, children, ...others};
  }

  renderBar() {
    //Overflow is not supported on Android, then use a higher container view to support "big icon button"
    let {barStyle, buttonContainerStyle, buttonStyle, onChange, children} = this.props;
    let sheetCount = 0;
    return (
      <View pointerEvents='box-none'>
        <View style={barStyle} />
        <View style={buttonContainerStyle} pointerEvents='box-none'>
          {children.map((item, index) => {
            let {type, title, icon, activeIcon, titleStyle, activeTitleStyle,tintColor,
              iconContainerStyle, badge, onPress} = item.props;
            let sheetIndex = sheetCount;
            if (type === 'sheet') sheetCount += 1;
            return (
              <this.constructor.Button
                key={index}
                titleStyle={titleStyle}
                activeTitleStyle={activeTitleStyle}
                tintColor={tintColor}
                style={buttonStyle}
                title={title}
                icon={icon}
                activeIcon={activeIcon}
                active={type === 'sheet' ? sheetIndex === this.activeIndex : false}
                iconContainerStyle={iconContainerStyle}
                badge={badge}
                onPress={e => {
                  if (type === 'sheet') {
                    this.setState({activeIndex: sheetIndex}, () => {
                      this.refs.carousel && this.refs.carousel.scrollToPage(sheetIndex);
                      onChange && onChange(sheetIndex);
                    });
                  }
                  onPress && onPress(e);
                }}
                />
            );
          })}
        </View>
      </View>
    );
  }

  renderProjector() {
    return (
      <Projector style={{flex: 1}} index={this.activeIndex}>
        {this.props.children.filter(item => item && item.props.type === 'sheet')}
      </Projector>
    );
  }

  renderCarousel() {
    let {children, onChange} = this.props;
    return (
      <Carousel
        style={{flex: 1}}
        carousel={false}
        startIndex={this.activeIndex}
        cycle={false}
        ref='carousel'
        onChange={index => {
          if (typeof index !== 'number') return;
          this.setState({activeIndex: index}, () => onChange && onChange(index));
        }}
      >
        {children.filter(item => item && item.props.type === 'sheet')}
      </Carousel>
    );
  }

  render() {
    this.buildProps();

    let {barStyle, type, children, ...others} = this.props;
    return (
      <View {...others}>
        {type === 'carousel' ? this.renderCarousel() : this.renderProjector()}
        <View style={{height: barStyle.height, width: 1}} />
        {this.renderBar()}
      </View>
    );
  }

}


text:
package com.twolattes.json.views;

import com.twolattes.json.Entity;
import com.twolattes.json.Value;

@Entity
public class NormalOrFull {
  @Value int foo = 89;

  @Value(views = "full") int bar = 78;
}


text:
import { Component, HostListener } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import sdk, { Project } from '@stackblitz/sdk';

import { ContentSection } from '../../models/content-section.model';
import { ComponentExample } from '../../models/components-examples.model';
import { main } from './stackblitz/main';
import { polyfills } from './stackblitz/polyfills';
import { getAppModuleCode, NgxModuleData } from './stackblitz/app.module';
import { getIndexHtmlCode } from './stackblitz/html';
import {
  getComponentClassName,
  getTagName,
  getTemplateFileName,
  getCSSCodeDatepickerCustomClass
} from './stackblitz/helpers';
import { Utils } from 'ngx-bootstrap/utils';
import { Subscription } from 'rxjs';
import { AvailableTabsNames } from '../../models/common.models';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'examples',
  templateUrl: './examples.component.html'
})
export class ExamplesComponent {
  examples: ComponentExample[];
  moduleData: NgxModuleData;
  tabName?: AvailableTabsNames;
  routeSubscription: Subscription;

  constructor(public section: ContentSection, private route: ActivatedRoute, router: Router) {
    this.examples = section.content as ComponentExample[];
    this.moduleData = this.route.snapshot.data && this.route.snapshot.data[1];
    this.moduleData.moduleRoute = router.routerState.snapshot.url;
    this.tabName = router.parseUrl(router.url).queryParams?.['tab'];
    this.routeSubscription = router.events.subscribe((event: any) => {
      if (event instanceof NavigationEnd) {
        this.tabName = router.parseUrl(router.url).queryParams?.['tab'];
      }
    });
  }

  @HostListener('document:click', ['$event'])
  preventEmptyHrefNav(event: MouseEvent & { target: Element }): void {
    let element: Element = event.target;
    let preventNav = element.getAttribute('href') === '#';

    if (preventNav) {
      event.preventDefault();

      return;
    }

    if (element.tagName !== 'A') {
      while (element.parentElement && element !== document.body) {
        if (preventNav) {
          event.preventDefault();

          return;
        }
        element = element.parentElement;
        preventNav = element.getAttribute('href') === '#';
      }
    }
  }

  openStackBlitzDemo(ts?: string, html?: string) {
    if (!ts || !html) {
      return;
    }

    const className = getComponentClassName(ts);
    const tag = getTagName(ts);
    const templateName = getTemplateFileName(ts);
    if (tag && className) {
      const project: Project = {
        template: 'angular-cli',
        title: `ngx-bootstrap stackblitz demo `,
        description: 'stackblitz demo',
        files: {
          'index.html': getIndexHtmlCode(tag, this.moduleData, Utils.stackOverflowConfig()),
          'styles.css': `body {padding: 30px; position: relative}
        ${this.moduleData.moduleRoute === '/sortable' ?
            `.sortable-item {
      padding: 6px 12px;
      margin-bottom: 4px;
      font-size: 14px;
      line-height: 1.4em;
      text-align: center;
      cursor: grab;
      border: 1px solid transparent;
      border-radius: 4px;
      border-color: #adadad;
    }

    .sortable-item-active {
      background-color: #e6e6e6;
      box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
    }

    .sortable-wrapper {
      min-height: 150px;
    }` : ''}
    ${this.moduleData.moduleRoute === '/accordion' ?
            `.card.customClass,
.card.customClass .card-header,
.panel.customClass {
  background-color: #5bc0de;
  color: #fff;
}
.panel.customClass .panel-body {
  background-color: #337aa7;
}` : ''}`,
          '.angular-cli.json': `{"apps": [{"styles": ["styles.css"]}]}`,
          'main.ts': main,
          'polyfills.ts': polyfills,
          'app/app.module.ts': getAppModuleCode(className, this.moduleData),
          'app/ngx-bootstrap-demo.component.ts': this.getTs(ts)
        },
        dependencies: {
          '@angular/animations': 'latest',
          'web-animations-js': 'latest',
          'ngx-bootstrap': 'next'
        },

      };
      if (className === 'DemoDatepickerDateCustomClassesComponent') {
        project.files['app/date-custom-classes.scss'] = getCSSCodeDatepickerCustomClass();
      }
      project.files[`app/${templateName}`] = this.getHtml(html);

      sdk.openProject(project);
    }
  }

  initFragment(anchor: string) {
    const spAnchor = anchor.split('-');
    return spAnchor.slice(0, spAnchor.length - 1).join('-');
  }

  private getHtml(html: string): string {
    return this.moduleData.moduleRoute === '/carousel' ?
      html.replace(/src="/g, 'src="https://valor-software.com/ngx-bootstrap/') : html;
  }

  private getTs(ts: string): string {
    return this.moduleData.moduleRoute === '/carousel' ?
      ts.replace(/assets/g, 'https://valor-software.com/ngx-bootstrap/assets') : ts;
  }
}


text:
<?php

namespace Sylius\Bundle\AddressingBundle\Form\Type;

use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
final class CountryChoiceType extends AbstractType
{
    /**
     * @var RepositoryInterface
     */
    private $countryRepository;

    /**
     * @param RepositoryInterface $countryRepository
     */
    public function __construct(RepositoryInterface $countryRepository)
    {
        $this->countryRepository = $countryRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'choices' => function (Options $options) {
                    if (null === $options['enabled']) {
                        $countries = $this->countryRepository->findAll();
                    } else {
                        $countries = $this->countryRepository->findBy(['enabled' => $options['enabled']]);
                    }

                    /*
                     * PHP 5.* bug, fixed in PHP 7: https://bugs.php.net/bug.php?id=50688
                     * "usort(): Array was modified by the user comparison function"
                     */
                    @usort($countries, function ($a, $b) {
                        return $a->getName() < $b->getName() ? -1 : 1;
                    });

                    return $countries;
                },
                'choice_value' => 'code',
                'choice_label' => 'name',
                'choice_translation_domain' => false,
                'enabled' => true,
                'label' => 'sylius.form.address.country',
                'placeholder' => 'sylius.form.country.select',
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return ChoiceType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'sylius_country_choice';
    }
}


text:
package models.daos

import javax.inject.Inject

import java.util.UUID

import scala.concurrent.Future

import play.modules.reactivemongo.ReactiveMongoApi

import reactivemongo.api._
import reactivemongo.api.collections.bson._

import scala.concurrent.ExecutionContext.Implicits.global

import shared.Setting

class SettingDAOMongoImpl @Inject() (reactiveMongoApi: ReactiveMongoApi) extends SettingDAO {

  val hash = new utils.misc.MongoSimpleHashMap[java.util.UUID, Setting](
    "settings",
    (uuid: java.util.UUID) => uuid.toString,
    new reactivemongo.bson.BSONDocumentWriter[Setting] {
      def write(setting: Setting): reactivemongo.bson.BSONDocument =
        reactivemongo.bson.BSONDocument(
          "piecetype" -> setting.piecetype,
          "note" -> setting.note
        )
    },
    new reactivemongo.bson.BSONDocumentReader[Setting] {
      def read(bson: reactivemongo.bson.BSONDocument): Setting = {
        val result = Setting(
          piecetype = bson.getAs[String]("piecetype"),
          note = bson.getAs[String]("note")
        )
        result
      }
    },
    reactiveMongoApi
  )

  def get(settingID: java.util.UUID): Future[Option[Setting]] = hash.find(settingID)

  def set(settingID: java.util.UUID, setting: Setting) = hash.update(settingID, setting)

  def delete(settingID: java.util.UUID) = hash.delete(settingID)

}


text:
class Course < ActiveRecord::Base
  belongs_to :subject
  has_many :sections
  has_many :groups
  has_and_belongs_to_many :geneds
  has_and_belongs_to_many :users
  set_primary_key :id

  def users
    users = []
    User.transaction do
      self.user_ids.each do |user_id|
        begin
          users << User.find( user_id )
        rescue ActiveRecord::RecordNotFound
          return users
        end
      end
    end
    users.sort_by { rand }
  end

  def to_s
    subject_code + " " + number.to_s
  end

  def key( str )
    "course:#{self.id}:#{str}"
  end

  def credit_hours
    return "" if hours_min.nil? or hours_max.nil?
    if hours_min - hours_max != 0
      "#{hours_min}-#{hours_max}"
    else
      "#{hours_min}"
    end
  end

  def hours
    "#{credit_hours} hr"
  end

  def semester
    subject.semester
  end

end


text:
package com.soprasteria.initiatives.auth.config;

import com.soprasteria.initiatives.auth.domain.User;
import com.soprasteria.initiatives.auth.service.UserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class SSOAuthenticationProvider implements AuthenticationProvider {

    private UserService userService;

    public SSOAuthenticationProvider(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) {
        String username = authentication.getPrincipal().toString();
        return userService.findByUsernameIgnoreCase(username)
                .map(this::buildAuthentication)
                .block();
    }

    private Authentication buildAuthentication(User user) {
        List<GrantedAuthority> authorities = user.getAuthorities()
                .stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                .collect(Collectors.toList());
        AuthenticatedUser authenticatedUser =
                new AuthenticatedUser(user.getUsername(), user.getFirstName(), user.getLastName(), authorities);
        return new UsernamePasswordAuthenticationToken(authenticatedUser, "", authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}


text:
//
//  LuaAutocomplete.m
//  https://github.com/kolyvan/luakit
//
//  Created by Kolyvan on 03.04.15.
//

#import "LuaAutocomplete.h"
#import "LuaState.h"
#import "lua.h"
#import <objc/runtime.h>

/////

static NSString *const kAnyVar = @"_ANYVAR_";

@interface LuaTokenVar : NSObject
@property (readonly, nonatomic, strong) NSString *name;
@property (readonly, nonatomic) int luaType;
@end

@implementation LuaTokenVar

- (instancetype) initWithName:(NSString *)name
                      luaType:(int)luaType
{
    self = [super init];
    if (self) {
        _name = name;
        _luaType = luaType;
    }
    return self;
}

- (BOOL) isEqual:(id)other
{
    if (self == other) {
        return YES;
    }

    if (!other) {
        return NO;
    }

    if (![other isKindOfClass:[LuaTokenVar class]]) {
        return NO;
    }

    return  _luaType == ((LuaTokenVar *)other).luaType &&
            [_name isEqualToString:((LuaTokenVar *)other).name];
}

@end

static BOOL probeRelatedToken(NSArray *tokens, NSString *start, NSString *end)
{
    const NSUInteger p0 = [tokens indexOfObject:start];
    if (p0 != NSNotFound) {
        const NSUInteger p1 = [tokens indexOfObject:end];
        return (p1 == NSNotFound || p1 > p0);
    }
    return NO;
}

static BOOL probeUnpairedToken(NSArray *tokens, NSString *op)
{
    NSUInteger i = 0;
    for (id p in tokens) {
        if ([p isEqual:op]) {
            i += 1;
        }
    }
    return (i && (i%2));
}

static BOOL probeUnpairedToken2(NSArray *tokens, NSString *start, NSString *end)
{
    NSUInteger n0 = 0, n1 = 0;
    for (id p in tokens) {
        if ([p isEqual:start]) {
            n0 += 1;
        } else if ([p isEqual:end]) {
            n1 += 1;
        }
    }
    return n1 < n0;
}

/////

@interface LuaAutocomplete()
@end

@implementation LuaAutocomplete {

    LuaState *_luaState;
    NSMutableArray *_keywords;
    NSMutableArray *_predefined;
    NSMutableArray *_variables;
    NSMutableArray *_operators;
    NSMutableArray *_brackets;
    NSDictionary *_globals;
}

+ (NSCharacterSet *) delimitersCharset
{
    static NSCharacterSet *charset;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        charset = [NSCharacterSet characterSetWithCharactersInString:@" +-*/%^#=~<>(){}[];:,.'\""];
    });
    return charset;
}

+ (NSSet *) luaKeywords
{
    static NSSet *luaKeywords;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        luaKeywords = [NSSet setWithArray:@[@"and", @"break", @"do", @"else", @"elseif", @"end", @"false", @"for", @"function", @"if", @"in", @"local", @"nil", @"not", @"or", @"repeat", @"return", @"then", @"true", @"until", @"while" ]];

    });
    return luaKeywords;
}

+ (NSSet *) luaTokens
{
    static NSSet *tokens;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

         tokens = [NSSet setWithArray:@[@"+", @"-", @"*", @"/", @"%", @"^", @"#", @"==", @"~=", @"<=", @"=>", @"<", @">", @"=", @"(", @")", @"{", @"}", @"[", @"]", @";", @":", @",", @".", @"..", @"...", @"'", @"\"" ]];
    });
    return tokens;
}

+ (NSArray *) luaConditionalOperators
{
    static NSArray *operators;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        operators = @[@"and", @"or", @"==", @"~=", @"<", @">", @"<=", @"=>"];
    });

    return operators;
}

+ (NSArray *) luaArithmeticOperators
{
    static NSArray *operators;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        operators = @[@"+", @"-", @"*", @"/", @"%", @"^", @".."];
    });

    return operators;
}

+ (NSSet *) luaPredefined
{
    static NSSet *predefined;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        predefined = [NSSet setWithArray:@[
                                           @"assert", @"collectgarbage", @"coroutine", @"debug", @"dofile",
                                           @"error", @"getmetatable", @"io", @"ipairs", @"load", @"loadfile",
                                           @"math", @"next", @"os", @"package", @"pairs", @"pcall", @"print",
                                           @"rawequal", @"rawget", @"rawlen", @"rawset", @"require", @"select",
                                           @"setmetatable", @"string", @"table", @"tonumber", @"tostring", @"type",
                                           @"utf8", @"xpcall"]];
    });
    return predefined;
}

- (void) addKeyword:(NSString *)value
{
    if (_keywords) {
        if (![_keywords containsObject:value]) {
            [_keywords addObject:value];
        }
    } else {
        _keywords = [NSMutableArray arrayWithObject:value];
    }
}

- (void) addPredefined:(NSString *)value
{
    if (_predefined) {
        if (![_predefined containsObject:value]) {
            [_predefined addObject:value];
        }
    } else {
        _predefined = [NSMutableArray arrayWithObject:value];
    }
}

- (void) addVariable:(NSString *)value
{
    if (_variables) {
        if (![_variables containsObject:value]) {
            [_variables addObject:value];
        }
    } else {
        _variables = [NSMutableArray arrayWithObject:value];
    }
}

- (void) addOperator:(NSString *)value
{
    if (_operators) {
        if (![_operators containsObject:value]) {
            [_operators addObject:value];
        }
    } else {
        _operators = [NSMutableArray arrayWithObject:value];
    }
}

- (void) addBracket:(NSString *)value
{
    if (_brackets) {
        if (![_brackets containsObject:value]) {
            [_brackets addObject:value];
        }
    } else {
        _brackets = [NSMutableArray arrayWithObject:value];
    }
}

+ (NSArray *) suggestionForInput:(NSString *)input
                            word:(NSString *)word
                        luaState:(LuaState *)luaState
{
    LuaAutocomplete * p = [LuaAutocomplete new];
    if (p) {
        p->_luaState = luaState;
        p->_globals = luakit_fieldsInTable(luaState.state, @"_G");
        return [p suggestionForInput:input word:word];
    }
    return nil;
}

- (NSArray *) suggestionForInput:(NSString *)input
                            word:(NSString *)word
{
    NSMutableArray *revTokens;

    if (input.length) {

        NSMutableArray *tokens = [self tokensFromInput:input];
        if (tokens) {

            revTokens = [NSMutableArray arrayWithCapacity:tokens.count];
            for (id p in tokens.reverseObjectEnumerator) {
                [revTokens addObject:p];
                if ([@"end" isEqual:p]) {
                    break; // drop before end
                }
            }
        }
    }

    if (revTokens.count) {

        // first need check for some special cases like quotes and table/userdata fields

        if (probeUnpairedToken(revTokens, @"\"")) {

            return @[@"\""];

        } else if (probeUnpairedToken(revTokens, @"'")) {

            return @[@"'"];

        } else if (revTokens.count > 1) {

            NSArray *results = [self caseOfTableOrUserdataField:revTokens word:word];
            if (results) {
                return results;
            }
        }
    }

    if (word.length) {

        [self collectForWord:word];
    }

    if (revTokens.count) {

        [self collectRevTokens:revTokens];
    }

    NSMutableArray *result = [NSMutableArray array];

    if (_variables) {
        [result addObjectsFromArray:_variables];
    }
    if (_brackets) {
        [result addObjectsFromArray:_brackets];
    }
    if (_keywords) {
        [result addObjectsFromArray:_keywords];
    }
    if (_operators) {
        [result addObjectsFromArray:_operators];
    }
    if (_predefined) {
        [result addObjectsFromArray:_predefined];
    }

    return result.count ? [result copy] : nil;
}

- (NSArray *) caseOfTableOrUserdataField:(NSArray *)revTokens
                                    word:(NSString *)word
{
    if (revTokens.count > 1) {

        id last = revTokens[0];
        id penult = revTokens[1];

        if (([last isEqual:@"."] || [last isEqual:@":"]) &&
            [penult isKindOfClass:[LuaTokenVar class]]) {

            LuaTokenVar *var = (LuaTokenVar *)penult;

            // var: or var.

            if (var.luaType == LUA_TTABLE) {

                NSDictionary *fields = luakit_fieldsInTable(_luaState.state, var.name);
                if (fields) {
                    return fields.allKeys;
                }

            } else if (var.luaType == LUA_TUSERDATA) {

                id obj = luakit_objectForUserdata(_luaState.state, var.name);
                if (obj) {

                    const BOOL isMethodCall = [last isEqual:@":"];
                    NSArray *names = luakit_luaNamesForObject(obj, isMethodCall);
                    if (names) {
                        return names;
                    }
                }
            }

        } else if (revTokens.count > 2) {

            id beforepenult = revTokens[2];

            if (([penult isEqual:@"."] || [penult isEqual:@":"]) &&
                [beforepenult isKindOfClass:[LuaTokenVar class]]) {

                // var:a or var.a

                LuaTokenVar *var = (LuaTokenVar *)beforepenult;

                if (word) {

                    NSArray *keys;

                    if (var.luaType == LUA_TTABLE) {

                        keys = luakit_fieldsInTable(_luaState.state, var.name).allKeys;

                    } else if (var.luaType == LUA_TUSERDATA) {

                        id obj = luakit_objectForUserdata(_luaState.state, var.name);
                        if (obj) {

                            const BOOL isMethodCall = [last isEqual:@":"];
                            keys = luakit_luaNamesForObject(obj, isMethodCall);
                        }
                    }

                    if (keys) {

                        NSMutableArray *ma = [NSMutableArray array];
                        for (NSString *key in keys) {

                            if (![key isEqualToString:word] &&
                                [key hasPrefix:word])
                            {
                                [ma addObject:key];
                            }
                        }
                        if (ma.count) {
                            return [ma copy];
                        }
                    }
                }

                return @[@"(", @"="];
            }
        }
    }

    return nil;
}

- (void) collectRevTokens:(NSArray *)revTokens
{
    NSString *last = revTokens.firstObject;

    if (probeUnpairedToken2(revTokens, @"(", @")")) {

        [self addBracket:@")"];

        if ([last isEqual:kAnyVar] ||
            [last isKindOfClass:[LuaTokenVar class]])
        {
            [self addOperator:@","];
        }
    }

    if (probeUnpairedToken2(revTokens, @"{", @"}")) {

        [self addBracket:@"}"];

        if ([last isEqual:kAnyVar] ||
            [last isKindOfClass:[LuaTokenVar class]])
        {
            [self addOperator:@"="];
            [self addOperator:@","];
        }
    }

    if (probeUnpairedToken2(revTokens, @"[", @"]")) {
        [self addBracket:@"]"];
    }

    if ([last isEqual:kAnyVar]) {

        if (revTokens.count > 1) {

            id penult = revTokens[1];

            if ([penult isEqual:@"function"]) {

                [self addBracket:@"("];
                [self addBracket:@"{"];

            } else if ([penult isEqual:@"if"] ||
                       [penult isEqual:@"while"] ||
                       [penult isEqual:@"until"] ||
                       [penult isEqual:@"for"])
            {
                for (NSString *s in self.class.luaConditionalOperators) {
                    [self addOperator:s];
                }

            } else  {

                [self addOperator:@"="];
                for (NSString *s in self.class.luaArithmeticOperators) {
                    [self addOperator:s];
                }
                [self addOperator:@";"];
            }

        } else {

            [self addOperator:@"="];
        }

    } else if ([last isKindOfClass:[LuaTokenVar class]]) {

        if (((LuaTokenVar *)last).luaType == LUA_TTABLE) {

            [self addOperator:@"."];
            [self addOperator:@":"];
            [self addOperator:@"["];

        } else if (((LuaTokenVar *)last).luaType == LUA_TUSERDATA) {

            [self addOperator:@"."];
            [self addOperator:@":"];
        }

    } else if ([last isEqual:@"function"]) {

        [self addBracket:@"("];
        [self addBracket:@"{"];

    } else if ([last isEqual:@"if"] ||
               [last isEqual:@"elseif"]) {

        [self addKeyword:@"not"];

    } else if ([last isEqual:@"="]) {

        [self addBracket:@"{"];
        [self addKeyword:@"function"];
    }

    ///

    if (probeRelatedToken(revTokens, @"if", @"then")) {
        [self addKeyword:@"then"];
    }

    if (probeRelatedToken(revTokens, @"then", @"else")) {
        [self addKeyword:@"else"];
    }

    if (probeRelatedToken(revTokens, @"while", @"do") ||
        probeRelatedToken(revTokens, @"for", @"do"))
    {
        [self addKeyword:@"do"];
    }

    if (probeRelatedToken(revTokens, @"repeat", @"until")) {
        [self addKeyword:@"until"];
    }

    if (probeRelatedToken(revTokens, @"function", @"return")) {
        [self addKeyword:@"return"];
    }

    if (probeRelatedToken(revTokens, @"function", @"end") ||
        probeRelatedToken(revTokens, @"do", @"end") ||
        probeRelatedToken(revTokens, @"if", @"end") ||
        probeRelatedToken(revTokens, @"elseif", @"end") ||
        probeRelatedToken(revTokens, @"while", @"end") ||
        probeRelatedToken(revTokens, @"return", @"end"))
    {
        [self addKeyword:@"end"];
    }
}

- (void) collectForWord:(NSString *)word
{
    NSNumber *t = _globals[word];

    if (t) {

        if (t.intValue == LUA_TTABLE) {

            [self addOperator:@"."];
            [self addOperator:@":"];
            [self addOperator:@"["];

        } else if (t.intValue == LUA_TFUNCTION) {

            [self addOperator:@"("];
            [self addOperator:@"{"];

        } else if (t.intValue == LUA_TNUMBER) {

            for (NSString *s in self.class.luaArithmeticOperators) {
                [self addOperator:s];
            }

        } else if (t.intValue == LUA_TBOOLEAN) {

            for (NSString *s in self.class.luaConditionalOperators) {
                [self addOperator:s];
            }

        } else if (t.intValue == LUA_TSTRING) {

            [self addOperator:@".."];

        } else if (t.intValue == LUA_TUSERDATA) {

            [self addOperator:@"."];
            [self addOperator:@":"];
        }
    }

    for (NSString *key in _globals.keyEnumerator) {

        if (![key isEqualToString:word] &&
            [key hasPrefix:word])
        {
            if ([self.class.luaPredefined containsObject:key]) {
                [self addPredefined:key];
            } else {
                [self addVariable:key];
            }
        }
    }

    for (NSString *key in self.class.luaKeywords) {

        if (![key isEqualToString:word] &&
            [key hasPrefix:word])
        {
            [self addKeyword:key];
        }
    }
}

- (NSMutableArray *) tokensFromInput:(NSString *) input
{
    NSMutableArray *ma = [NSMutableArray array];

    NSScanner *scanner = [NSScanner scannerWithString:input];

    while (!scanner.isAtEnd) {

        NSString *t;
        [scanner scanCharactersFromSet:self.class.delimitersCharset intoString:&t];
        if (t) {

            if (t.length > 1) {

                for (NSUInteger i = 0; i < t.length; ++i) {
                    const unichar ch = [t characterAtIndex:i];
                    if (ch != ' ') {
                        [ma addObject:[NSString stringWithFormat:@"%C", ch]];
                    }
                }

            } else {

                [ma addObject:t];
            }
        }

        NSString *k;
        if ([scanner scanUpToCharactersFromSet:self.class.delimitersCharset intoString:&k]) {

            if (![self.class.luaKeywords containsObject:k]) {

                id t = _globals[k];
                if (t &&
                    ([t intValue] == LUA_TTABLE ||
                     [t intValue] == LUA_TUSERDATA))
                {
                    [ma addObject:[[LuaTokenVar alloc] initWithName:k luaType:[t intValue]]];
                    k = nil;

                } else {
                    k = kAnyVar;
                }
            }

            if (k) {
                [ma addObject:k];
            }
        }
    }

    return ma.count ? ma : nil;
}

@end


text:
//  VWWeights.scala
//
//  Copyright (C) 2014 Ben Wing, The University of Texas at Austin
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
///////////////////////////////////////////////////////////////////////////////

package opennlp.textgrounder
package postprocess

import scala.util.control.Breaks._
import scala.collection.mutable

import util.argparser._
import util.collection._
import util.experiment._
import util.io._
import util.print._
import util.table.output_reverse_sorted_table

import util.debug._

class VWWeightsParameters(ap: ArgParser) {
  var readable_model = ap.option[String]("readable-model",
    "rm",
    metavar = "FILE",
    help="""File output using --readable_model argument in Vowpal Wabbit.""")

  var invert_hash = ap.option[String]("invert-hash",
    "ih",
    metavar = "FILE",
    help="""File output using --invert_hash argument in Vowpal Wabbit.""")

  var output_highest_weights = ap.option[String]("output-highest-weights",
    "ohw",
    metavar = "FILE",
    help="""File to output highest seen weight for each feature to.
There is a separate weight for each combination of feature and cell.
This outputs the highest weight seen for any cell.""")

  var output_weights = ap.option[String]("output-weights",
    "ow",
    metavar = "FILE",
    help="""File to output weights to.
There is a separate weight for each combination of feature and cell.""")

  var debug =
    ap.option[String]("d", "debug", metavar = "FLAGS",
      help = """Output debug info of the given types.  Multiple debug
parameters can be specified, indicating different types of info to output.
Separate parameters by spaces, colons or semicolons.  Params can be boolean,
if given alone, or valueful, if given as PARAM=VALUE.  Certain params are
list-valued; multiple values are specified by including the parameter
multiple times, or by separating values by a comma.
""")

  if (ap.parsedValues && debug != null)
    parse_debug_spec(debug)
}

/**
 * An application to combine the named features available from VW's
 * --invert_hash with the weights available from VW's --readable_model.
 * This is because VW's BFGS doesn't with --invert_hash, but the equivalent
 * can be gotten by running with the same parameters using SGD to get the
 * mapping between feature names and hashed bins, and combining this mapping
 * with the bin numbers and weights from --readable_model.
 */
object VWWeights extends ExperimentApp("VWWeights") {

  type TParam = VWWeightsParameters

  def create_param_object(ap: ArgParser) = new VWWeightsParameters(ap)

  def get_weights(file: String): Map[Int, Double] = {
    val fh = localfh.openr(file)
    breakable {
      while (true) {
        val line = fh.next
        if (line == ":0")
          break
      }
    }
    (for (line <- fh) yield {
      val Array(featnum, weight) = line.split(":")
      (featnum.toInt, weight.toDouble)
    }).toMap
  }

  // Mapping from feature ID to (feature-name, cell)
  def get_names(file: String): Map[Int, (String, Int)] = {
    val fh = localfh.openr(file)
    breakable {
      while (true) {
        val line = fh.next
        if (line == ":0")
          break
      }
    }
    val name_count = intmap[String]()
    (for (line <- fh) yield {
      val Array(feat, featnum, _) = line.split(":")
      // Features in the VW files normally begin with " ^"
      val name = if (feat.startsWith(" ^")) feat.drop(2) else feat
      name_count(name) += 1
      (featnum.toInt, (name, name_count(name)))
    }).toMap
  }

  def run_program(args: Array[String]) = {
    val names = get_names(params.invert_hash)
    val weights = get_weights(params.readable_model)
    val named_weights = weights map { case (featnum, weight) =>
      val (name, cell) = names.getOrElse(featnum, ("???", 0))
      val tagged_name = s"$name:cell"
      ((name, cell), weight)
    }
    val sorted_weights = named_weights.toSeq.sortWith(_._2 > _._2)
    if (params.output_highest_weights != null) {
      val highest_weight = doublemap[String]()
      sorted_weights.foreach { case ((name, cell), weight) =>
        // Under normal circumstances, the first weight we see will
        // be the highest, but not always because of negative weights
        if (weight.abs > highest_weight(name).abs)
          highest_weight(name) = weight
      }
      output_reverse_sorted_table(highest_weight,
        outfile = localfh.openw(params.output_highest_weights))
    }
    if (params.output_weights != null) {
      val weight_file = localfh.openw(params.output_weights)
      sorted_weights.foreach { case ((name, cell), weight) =>
        weight_file.println(s"$name:$cell = $weight")
      }
    }
    0
  }
}


text:
package de.tudarmstadt.lt.seg.sentence;

import java.io.IOException;
import java.io.Reader;

import de.tudarmstadt.lt.seg.Segment;
import de.tudarmstadt.lt.seg.SegmentType;
import de.tudarmstadt.lt.seg.SegmentationUtils;
import de.tudarmstadt.lt.seg.sentence.rules.RuleSet;
import de.tudarmstadt.lt.seg.token.EmptySpaceTokenizer;
import de.tudarmstadt.lt.seg.token.ITokenizer;

/**
 * @author Steffen Remus
 *
 */
public class RuleSplitter implements ISentenceSplitter{

	ITokenizer _approximate_tokenizer = new EmptySpaceTokenizer();

	RuleSet _rules = RuleSet.DEFAULT_RULESET;
	Reader _reader = null;
	int _cp = 0;
	final Segment _segment_sentence = new Segment(){{ begin = 0; end = 0; type = SegmentType.UNKNOWN; text.setLength(0);}};
	final Segment _segment_sentence_boundary = new Segment(){{ begin = 0; end = 0; type = SegmentType.UNKNOWN; text.setLength(0); }};

	private boolean getNext(){
		_segment_sentence.text.setLength(0);
		_segment_sentence.type = SegmentType.UNKNOWN;
		_segment_sentence.begin = _segment_sentence.end;

		_segment_sentence_boundary.text.setLength(0);
		_segment_sentence_boundary.type = SegmentType.UNKNOWN;
		_segment_sentence_boundary.begin = _segment_sentence.begin;

		if(_cp < 0)
			return false;

		boolean first_is_newline =  SegmentationUtils.charIsLineSeparator(_cp);
		boolean is_empty = first_is_newline;

		while(_cp > 0){
			int cp_current = _cp;
			_segment_sentence.text.appendCodePoint(cp_current);
			++_segment_sentence.end;
			is_empty &= SegmentationUtils.charIsEmptySpace(cp_current);

			if(isSentenceBoundary() && checkSentenceBoundaryLookBack() && checkSentenceBoundaryLookAhead()){
				_cp = getNextCodePoint();
				break;
			}

			_cp = getNextCodePoint();
			int cp_next = _cp;

			if(is_empty && !SegmentationUtils.charIsLineSeparator(cp_next))
				break;
		}
		_segment_sentence.type = is_empty ? SegmentType.EMPTY_SPACE : SegmentType.SENTENCE;

		return !_segment_sentence.hasZeroLength();
	}

	private boolean isSentenceBoundary(){
		String suffix = _rules._boundary_checker.getSuffixAsSentenceBoundary(_segment_sentence.text.substring((int)Math.max(_segment_sentence.text.length()-100,0)));
		if(suffix == null)
			return false;
		_segment_sentence_boundary.text.setLength(0);
		_segment_sentence_boundary.end = _segment_sentence.end;
		_segment_sentence_boundary.begin = _segment_sentence.end - suffix.length();
		_segment_sentence_boundary.text.append(_segment_sentence.text.substring(_segment_sentence.text.length() - suffix.length()));
		return true;
	}

	private boolean checkSentenceBoundaryLookAhead(){
		// get the next approximate token or sentence
		if(_cp < 0)
			return true;
		try {
			_reader.mark(1000);
			_approximate_tokenizer.init(_reader);
			if(!_approximate_tokenizer.hasNext())
				return true;
			String next_token = _approximate_tokenizer.next().asString();
			_reader.reset();
			if(!_rules._post_boundary_checker_list.isCompleteSentence(next_token))
				return false; // stop early
			return _rules._post_boundary_checker_rules.isCompleteSentence(next_token);
		} catch (IOException e) {
			System.err.format("%s: %s%n", e.getClass().getName(), e.getMessage());
		}
		return false;
	}

	private boolean checkSentenceBoundaryLookBack(){
		if(!_rules._pre_boundary_checker_list.isCompleteSentence(_segment_sentence.text.toString()))
			return false; // stop early
		return _rules._pre_boundary_checker_rules.isCompleteSentence(_segment_sentence.text.substring(0, _segment_sentence_boundary.begin - _segment_sentence.begin));
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	@Override
	public boolean hasNext() {
		return getNext();
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	@Override
	public Segment next() {
		return _segment_sentence;
	}

	public int getNextCodePoint(){
		try {
			return _reader.read();
		} catch (IOException e) {
			System.err.format("%s: %s%n", e.getClass().getName(), e.getMessage());
			return -1;
		}
	}

	public ISentenceSplitter init(Reader reader, String languagecode) {
		_rules = RuleSet.get(languagecode);
		return init(reader);
	}

	public ISentenceSplitter init(Reader reader, RuleSet rules) {
		_rules = rules;
		return init(reader);
	}

	public ISentenceSplitter init(RuleSet rules) {
		_rules = rules;
		return this;
	}

	/* (non-Javadoc)
	 * @see de.tudarmstadt.lt.seg.sentence.ISentenceSplitter#init(java.io.Reader)
	 */
	@Override
	public ISentenceSplitter init(Reader reader) {
		// TODO: if not marksupported throw error
		_reader = reader;
		_segment_sentence.begin = 0; _segment_sentence.end = 0; _segment_sentence.type = SegmentType.UNKNOWN; _segment_sentence.text.setLength(0);
		_segment_sentence_boundary.begin = 0; _segment_sentence_boundary.end = 0; _segment_sentence_boundary.type = SegmentType.UNKNOWN; _segment_sentence_boundary.text.setLength(0);
		_cp = getNextCodePoint();
		return this;
	}

}


text:
{% extends "base.html" %}
{% load static %}
{% load compress %}
{% block page_title %}GKA Dashboard{% endblock %}

{% block css_extra %}
  <link rel="stylesheet" type="text/css" href="/static/css/gka-dashboard.css" />
{% endblock %}

{% block endbody %}
  {% compress js %}

  {% endcompress %}
{% endblock %}

{% block content %}

    X

      <form class="form-base">

                  Start Date

                  <select class="month">

                  </select>
                  <select class="year">

                  </select>

                  End Date

                  <select class="month">

                  </select>
                  <select class="year">

                  </select>

Apply Date Filter

      </form>

GKA DASHBOARD

          <input type="text" placeholder="District" class="js-example-basic-single input-text full-width" id="select-district">

          <input type="text" placeholder="Block" class="js-example-basic-single input-text full-width" id="select-block">

          <input type="text" placeholder="Cluster" class="js-example-basic-single input-text full-width" id="select-cluster">

          <input type="text" placeholder="School" class="js-example-basic-single input-text full-width" id="select-school">

      SMS

SMS Users

SMS Volumes

      ASSESSMENTS

Assessment Volumes

Competency Summary

This section of the report draws data from Ek-Step Foundation for the assessments carried out on the Genie Tablet/Mobile Application.

      GP CONTESTS

Class 4 Summary

Class 5 Summary

Class 6 Summary

      SURVEYS

Respondents

Survey Volumes

              Not enough data to show survey volumes.

      COMPARISON

ASSESSMENT COMPARISON

GP CONTEST COMPARISON

This report is generated for Akshara Foundation  by KLP.

{% include 'frontend_templates/gka_dashboard.html' %}
{% endblock %}


text:
<?php

namespace Silex;

use Symfony\Component\HttpFoundation\Response;

/**
 * Converts string responses to Response objects.
 *
 * @author Igor Wiedler <igor@wiedler.ch>
 */
class StringResponseConverter
{
    /**
     * Does the conversion
     *
     * @param string $response The response string
     *
     * @return A Response object
     */
    public function convert($response)
    {
        if (!$response instanceof Response) {
            return new Response((string) $response);
        }

        return $response;
    }
}


text:
package nl.vu.cs.ajira.data.types;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;

import nl.vu.cs.ajira.actions.ActionContext;
import nl.vu.cs.ajira.utils.Consts;

/**
 *
 * This class provides the methods that are needed in order to manipulate an
 * array of int values.
 *
 */
public class TIntArray extends SimpleData {

	int[] array;

	/**
	 * Creates a new TIntArray and sets the size of its field.
	 *
	 * @param size
	 *            is the size of the array
	 */
	public TIntArray(int size) {
		array = new int[size];
	}

	/**
	 * Creates a new TIntArray and sets its field.
	 *
	 * @param array
	 *            is the new array of the object
	 */
	public TIntArray(int[] array) {
		this.array = array;
	}

	/**
	 * Creates an empty TIntArray object.
	 */
	public TIntArray() {
	}

	/**
	 *
	 * @return the field of the class
	 */
	public int[] getArray() {
		return array;
	}

	/**
	 * Sets the field of the class.
	 *
	 * @param array
	 *            is the new array of the object
	 */
	public void setArray(int[] array) {
		this.array = array;
	}

	@Override
	/**
	 * Returns the id of the class.
	 */
	public int getIdDatatype() {
		return Consts.DATATYPE_TINTARRAY;
	}

	@Override
	/**
	 * Reads from a DataInput the size of the array and then
	 * the corresponding number of boolean values.
	 */
	public void readFrom(DataInput input) throws IOException {
		int s = input.readInt();
		if (s != -1) {
			if (array == null || array.length != s) {
				array = new int[s];
			}
			for (int i = 0; i < s; ++i)
				array[i] = input.readInt();
		} else {
			array = null;
		}
	}

	@Override
	/**
	 * If the array is not null it writes in a DataOutput the size
	 * of the array and then its values. If the array is null then
	 * it writes -1.
	 */
	public void writeTo(DataOutput output) throws IOException {
		if (array == null) {
			output.writeInt(-1);
		} else {
			output.writeInt(array.length);
			for (int v : array)
				output.writeInt(v);
		}
	}

	// @Override
	// public int bytesToStore() throws IOException {
	// return (array == null) ? 4 : 4 + array.length * 4;
	// }

	@Override
	/**
	 * Copies the array of the current object in the parameters'array.
	 */
	public void copyTo(SimpleData el) {
		if (array != null) {
			((TIntArray) el).array = Arrays.copyOf(array, array.length);
		} else {
			((TIntArray) el).array = null;
		}
	}

	@Override
	/**
	 * Compares two TIntArray objects.
	 *
	 * Returns 0 in case of equality,
	 * Returns a number lower than 0 in case the current array is lower than the parameter's array,
	 * Returns a number greater than 0 in case the current array is greater than the parameter's array
	 */
	public int compareTo(SimpleData el) {
		int[] array2 = ((TIntArray) el).array;
		if (array == null) {
			if (array2 == null) {
				return 0;
			} else {
				return -1;
			}
		} else {
			if (array2 == null) {
				return 1;
			} else {
				int i = 0;
				while (i < array.length && i < array2.length) {
					int diff = array[i] - array2[i];
					if (diff != 0) {
						return diff;
					}
					++i;
				}
				return array.length - array2.length;
			}
		}
	}

	@Override
	/**
	 * Compares two TIntArray objects.
	 *
	 * It returns true if they are equal
	 * It returns false if they are not equal
	 */
	public boolean equals(SimpleData el, ActionContext context) {
		return compareTo(el) == 0;
	}
}


text:
import React from 'react';
import {
	AppRegistry,
	AsyncStorage,
	Button,
	StyleSheet,
	Text,
	View,
} from 'react-native';
import {
	NavigationActions,
	addNavigationHelpers,
	StackNavigator,
} from 'react-navigation';
import {
	Provider,
	connect,
} from 'react-redux';
import {
	createStore,
	combineReducers,
} from 'redux';
import {AppNavigator} from '../../../components/appNavigator/AppNavigator';

const initialAuthState = {isLoggedIn: false};

const initialNavState = AppNavigator.router.getStateForAction({ type: NavigationActions.INIT });

// const initialNavState = {
// 	index: 1,
// 	routes: [
// 		{key: 'InitA', routeName: 'MainTabs'},
// 		{key: 'InitB', routeName: 'Login'},
// 	],
// };

export default (state = initialNavState, action) => {
		if (action.type === 'Login') {
			return AppNavigator.router.getStateForAction(NavigationActions.back(), state);
		}
		if (action.type === 'Logout') {
			return AppNavigator.router.getStateForAction(NavigationActions.navigate({ routeName: 'Login' }), state);
		}
		return AppNavigator.router.getStateForAction(action, state);
	};


text:
from goldp import GoLDP
from base import *
from argparse import ArgumentParser
from itertools import combinations

def run(args):

    ctns = []
    for idx, name in enumerate(['g1', 'g2', 'g3', 'g4']):
        config_dir = '{0}/{1}'.format(args.dir, name)
        g = GoLDP(name, '10.10.10.{0}'.format(idx+10), config_dir)
        g.run()
        ctns.append(g)

    for idx, (i, j) in enumerate(combinations(ctns, 2)):
        for jdx, ctn in enumerate([i, j]):
            ifname = connect_ctn_to_br(ctn, 'br{0}'.format(idx))
            nw = '10.{0}.0.{1}/30'.format(idx, jdx+1)
            ctn.local('ip addr add {0} dev {1}'.format(nw, ifname))
            ctn.ospf_routes.append(nw)
            ctn.ldp_interfaces.append(ifname)

    for ctn in ctns:
        print 'start', ctn.name
        ctn.start()

def build(args):
    GoLDP.build_image(args.force, nocache=args.no_cache, from_image=args.from_image)

if __name__ == '__main__':
    parser = ArgumentParser(description='GoLDP test tool')
    parser.add_argument('-d', '--dir', default='/tmp/goldp')
    s = parser.add_subparsers()

    parser_run = s.add_parser('run', help='run')
    parser_run.set_defaults(func=run)

    parser_build = s.add_parser('build', help='prepare env')
    parser_build.add_argument('-f', '--force', action='store_true', help='build even if the container already exists')
    parser_build.add_argument('-n', '--no-cache', action='store_true')
    parser_build.add_argument('-i', '--from-image', default='golang:1.6')
    parser_build.set_defaults(func=build)

    args = parser.parse_args()
    args.func(args)


text:
TMPD=`mktemp -d`
DEST=`pwd`
echo AesCrypt ...

VERSION=1.0
TMP=$TMPD/aescrypt
mkdir -p "$TMP/cookbook"  "$TMP/pub/aescrypt" "$TMP/pub/guiedit"
cp AesCrypt/aescrypt.php "$TMP/cookbook"
cp AesCrypt/*.js "$TMP/pub/aescrypt"
cp AesCrypt/*.txt "$TMP/pub/aescrypt"
cp AesCrypt/{close.png,maskbg.png,showpass.png} "$TMP/pub/aescrypt"
cp AesCrypt/aescrypt.png "$TMP/pub/guiedit"

tar -c -v -z -f aescrypt-$VERSION.tgz -C  "$TMP/" cookbook pub

( cd  "$TMP/" ; zip -v -9 -r "$DEST/aescrypt-$VERSION.zip" cookbook pub )

echo CachedNumberOfArticles ...

VERSION=1.0
TMP=$TMPD/cachednumberofarticles
mkdir -p "$TMP/cookbook"  "$TMP/wikilib.d"
cp CachedNumberOfArticles/noa.php "$TMP/cookbook"
cp CachedNumberOfArticles/Site.NumberOfArticles "$TMP/wikilib.d"

tar -c -v -z -f noa-$VERSION.tgz -C  "$TMP/" cookbook wikilib.d

( cd  "$TMP/" ; zip -v -9 -r "$DEST/noa-$VERSION.zip" cookbook wikilib.d )


text: search_result['4717']=["topic_0000000000000B77_vars--.html","TemplateService Fields",""];