text:
package main

import (
	"bytes"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"github.com/Workiva/go-datastructures/bitarray"
	"github.com/h31/Reflection/qBT"
	"github.com/h31/Reflection/transmission"
	"github.com/ricochet2200/go-disk-usage/du"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"math"
	"mime/multipart"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"
	"time"
	"unicode"
)

var (
	verbose          = flag.Bool("verbose", false, "Enable verbose output")
	debug            = flag.Bool("debug", false, "Enable debug output")
	apiAddr          = flag.String("api-addr", "http://localhost:8080/", "qBittorrent API address")
	port             = flag.Uint("port", 9091, "Transmission RPC port")
	cacheTimeout     = flag.Uint("cache-timeout", 15, "Cache timeout (in seconds)")
	disableKeepAlive = flag.Bool("disable-keep-alive", false, "Disable HTTP Keep-Alive in requests (may be necessary for older qBittorrent versions)")
	useSync          = flag.Bool("sync", true, "Use Sync endpoint (recommended)")
)

func init() {
	flag.BoolVar(verbose, "v", false, "")
	flag.BoolVar(debug, "d", false, "")
	flag.StringVar(apiAddr, "r", "http://localhost:8080/", "")
	flag.UintVar(port, "p", 9091, "")
	flag.Parse()
}

var deprecatedFields = map[string]struct{}{
	"announceUrl":       {},
	"announceResponse":  {},
	"seeders":           {},
	"leechers":          {},
	"downloadLimitMode": {},
	"uploadLimitMode":   {},
	"nextAnnounceTime":  {},
}

type argumentValue int

const (
	ARGUMENT_NOT_SET argumentValue = iota
	ARGUMENT_TRUE    argumentValue = iota
	ARGUMENT_FALSE   argumentValue = iota
)

type additionalArguments struct {
	sequentialDownload   argumentValue
	firstLastPiecesFirst argumentValue
	skipChecking         argumentValue
}

var qBTConn qBT.Connection

func IsFieldDeprecated(field string) bool {
	_, ok := deprecatedFields[field]
	return ok
}

//func parseIDsArgument(args *json.RawMessage) []*qBT.TorrentInfo {
//	allIds := parseIDsField(args)
//	filtered := make([]qBT.ID, 0)
//	for _, id := range allIds {
//		if qBTConn.TorrentsList.ByID(id) != nil {
//			filtered = append(filtered, id)
//		}
//	}
//	return filtered
//}

func parseIDsField(args *json.RawMessage) qBT.TorrentInfoList {
	qBTConn.UpdateTorrentsList()

	if args == nil {
		log.Debug("No IDs provided")
		return qBTConn.TorrentsList.Slice()
	}

	var ids interface{}
	err := json.Unmarshal(*args, &ids)
	Check(err)

	switch ids := ids.(type) {
	case float64:
		log.Debug("Query a single ID")
		return []*qBT.TorrentInfo{qBTConn.TorrentsList.ByID(qBT.ID(ids))}
	case []interface{}:
		log.Debug("Query an ID list of length ", len(ids))
		result := make([]*qBT.TorrentInfo, len(ids))
		for i, value := range ids {
			switch id := value.(type) {
			case float64:
				result[i] = qBTConn.TorrentsList.ByID(qBT.ID(id))
			case string:
				hash := qBT.Hash(id)
				result[i] = qBTConn.TorrentsList.ByHash(hash)
			}
			if result[i] == nil {
				panic("hash not found")
			}
		}
		return result
	case string:
		if ids != "recently-active" {
			panic("Unsupported ID type: " + ids)
		}
		log.Debug("Query recently-active")
		if *useSync {
			return qBTConn.TorrentsList.GetActive()
		} else {
			return qBTConn.TorrentsList.Slice()
		}
	default:
		log.Panicf("Unknown ID type: %s", ids)
		panic("Unknown ID type")
	}
}

func parseActionArgument(args json.RawMessage) qBT.TorrentInfoList {
	var req struct {
		Ids json.RawMessage
	}
	err := json.Unmarshal(args, &req)
	Check(err)

	return parseIDsField(&req.Ids)
}

func MapTorrentList(dst JsonMap, src *qBT.TorrentInfo) {
	for key, value := range transmission.TorrentGetBase {
		dst[key] = value
	}
	dst["hashString"] = src.Hash
	convertedName := EscapeString(src.Name)
	dst["name"] = convertedName
	dst["addedDate"] = src.Added_on
	dst["startDate"] = src.Added_on // TODO
	dst["doneDate"] = src.Completion_on
	dst["sizeWhenDone"] = src.Size
	dst["totalSize"] = src.Total_size
	dst["downloadDir"] = EscapeString(src.Save_path)
	dst["rateDownload"] = src.Dlspeed
	dst["rateUpload"] = src.Upspeed
	dst["uploadRatio"] = src.Ratio
	if src.Eta >= 0 {
		dst["eta"] = src.Eta
	} else {
		dst["eta"] = -1
	}
	dst["status"] = qBTStateToTransmissionStatus(src.State)
	if dst["status"] == TR_STATUS_CHECK {
		dst["recheckProgress"] = src.Progress
	} else {
		dst["recheckProgress"] = 0
	}
	dst["error"] = qBTStateToTransmissionError(src.State)
	dst["isStalled"] = qBTStateToTransmissionStalled(src.State)
	dst["percentDone"] = src.Progress
	dst["peersGettingFromUs"] = src.Num_leechs
	dst["peersSendingToUs"] = src.Num_seeds
	dst["leftUntilDone"] = float64(src.Size) * (1 - src.Progress)
	dst["desiredAvailable"] = float64(src.Size) * (1 - src.Progress) // TODO
	dst["haveUnchecked"] = 0                                         // TODO
	if src.State == "metaDL" {
		dst["metadataPercentComplete"] = 0
	} else {
		dst["metadataPercentComplete"] = 1
	}
}

const TR_STAT_OK = 0
const TR_STATUS_LOCAL_ERROR = 3

func qBTStateToTransmissionError(state string) int {
	if state == "error" || state == "missingFiles" {
		return TR_STATUS_LOCAL_ERROR // TR_STAT_LOCAL_ERROR
	} else {
		return TR_STAT_OK // TR_STAT_OK
	}
}

func qBTStateToTransmissionStalled(state string) bool {
	switch state {
	case "stalledDL", "stalledUP":
		return true
	default:
		return false
	}
}

const TR_STATUS_STOPPED = 0
const TR_STATUS_CHECK = 2
const TR_STATUS_DOWNLOAD_WAIT = 3
const TR_STATUS_DOWNLOAD = 4
const TR_STATUS_SEED_WAIT = 5
const TR_STATUS_SEED = 6

func qBTStateToTransmissionStatus(state string) int {
	switch state {
	case "pausedUP", "pausedDL":
		return TR_STATUS_STOPPED // TR_STATUS_STOPPED
	case "checkingUP", "checkingDL":
		return TR_STATUS_CHECK // TR_STATUS_CHECK
	case "queuedDL":
		return TR_STATUS_DOWNLOAD_WAIT // TR_STATUS_DOWNLOAD_WAIT
	case "downloading", "stalledDL", "forceDL":
		return TR_STATUS_DOWNLOAD // TR_STATUS_DOWNLOAD
	case "queuedUP":
		return TR_STATUS_SEED_WAIT // TR_STATUS_SEED_WAIT
	case "uploading", "stalledUP", "forcedUP":
		return TR_STATUS_SEED // TR_STATUS_SEED
	case "error", "missingFiles":
		return TR_STATUS_STOPPED // TR_STATUS_STOPPED
	default:
		return TR_STATUS_STOPPED // TR_STATUS_STOPPED
	}
}

func MapPieceStates(dst JsonMap, pieces []byte) {
	bits := bitarray.NewSparseBitArray()

	for i, value := range pieces {
		if value == 2 {
			bits.SetBit(uint64(i))
		}
	}

	serialized, _ := bitarray.Marshal(bits)

	dst["pieces"] = base64.StdEncoding.EncodeToString(serialized)
}

func MakePiecesBitArray(total, have int) string {
	if (total < 0) || (have < 0) {
		return "" // Empty array
	}
	arrLen := uint(math.Ceil(float64(total) / 8))
	arr := make([]byte, arrLen)

	fullBytes := uint(math.Floor(float64(have) / 8))
	for i := uint(0); i < fullBytes; i++ {
		arr[i] = math.MaxUint8
	}
	for i := uint(0); i < (uint(have) - fullBytes*8); i++ {
		arr[fullBytes] |= 128 >> i
	}

	return base64.StdEncoding.EncodeToString(arr)
}

func isMn(r rune) bool {
	return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
}

type escapedString string

func (s escapedString) MarshalJSON() ([]byte, error) {
	return []byte(strconv.QuoteToASCII(string(s))), nil
}

func EscapeString(in string) escapedString {
	return escapedString(in)
}

func boolToYesNo(value bool) string {
	if value {
		return "yes"
	} else {
		return "no"
	}
}

func addPropertiesToCommentField(dst JsonMap, torrentItem *qBT.TorrentInfo, propGeneral qBT.PropertiesGeneral) {
	dst["comment"] = fmt.Sprintf("%s\n"+
		" ----- \n"+
		"Sequential download: %s\n"+
		"First and last pieces first: %s", propGeneral.Comment,
		boolToYesNo(torrentItem.Seq_dl), boolToYesNo(torrentItem.F_l_piece_prio))
}

func MapPropsGeneral(dst JsonMap, propGeneral qBT.PropertiesGeneral) {
	dst["pieceSize"] = propGeneral.Piece_size
	dst["pieceCount"] = propGeneral.Pieces_num
	dst["addedDate"] = propGeneral.Addition_date
	dst["startDate"] = propGeneral.Addition_date // TODO
	dst["dateCreated"] = propGeneral.Creation_date
	dst["creator"] = propGeneral.Created_by
	dst["doneDate"] = propGeneral.Completion_date
	dst["totalSize"] = propGeneral.Total_size
	dst["haveValid"] = propGeneral.Piece_size * propGeneral.Pieces_have
	dst["downloadedEver"] = propGeneral.Total_downloaded
	dst["uploadedEver"] = propGeneral.Total_uploaded
	dst["peersConnected"] = propGeneral.Peers
	dst["peersFrom"] = struct {
		fromCache    int
		fromDht      int
		fromIncoming int
		fromLdp      int
		fromLtep     int
		fromPex      int
		fromTracker  int
	}{
		fromTracker: propGeneral.Peers,
	}
	dst["corruptEver"] = propGeneral.Total_wasted

	if propGeneral.Up_limit >= 0 {
		dst["uploadLimited"] = true
		dst["uploadLimit"] = propGeneral.Up_limit
	} else {
		dst["uploadLimited"] = false
		dst["uploadLimit"] = 0
	}

	if propGeneral.Dl_limit >= 0 {
		dst["downloadLimited"] = true
		dst["downloadLimit"] = propGeneral.Dl_limit // TODO: Kb/s?
	} else {
		dst["downloadLimited"] = false
		dst["downloadLimit"] = 0
	}

	dst["maxConnectedPeers"] = propGeneral.Nb_connections_limit
	dst["peer-limit"] = propGeneral.Nb_connections_limit // TODO: What's it?
}

func MapPropsPeers(dst JsonMap, hash qBT.Hash) {
	url := qBTConn.MakeRequestURLWithParam("sync/torrentPeers", map[string]string{"hash": string(hash), "rid": "0"})
	torrents := qBTConn.DoGET(url)

	log.Debug(string(torrents))
	var resp struct {
		//Peers map[string]qBT.PeerInfo
		Peers map[string]qBT.PeerInfo
	}
	err := json.Unmarshal(torrents, &resp)
	Check(err)
	//var trPeers []transmission.PeerInfo
	trPeers := make([]transmission.PeerInfo, 0)

	for _, peer := range resp.Peers {
		clientName := EscapeString(peer.Client)
		country := EscapeString(peer.Country)
		trPeers = append(trPeers, transmission.PeerInfo{
			RateToPeer:   peer.Up_speed,
			RateToClient: peer.Dl_speed,
			ClientName:   clientName,
			FlagStr:      peer.Flags,
			Country:      country,
			Address:      peer.IP,
			Progress:     peer.Progress,
			Port:         peer.Port,
		})
	}

	dst["peers"] = trPeers
}

func MapPropsTrackers(dst JsonMap, trackers []qBT.PropertiesTrackers) {
	trackersList := make([]JsonMap, len(trackers))

	for i, value := range trackers {
		id := i
		trackersList[i] = make(JsonMap)
		trackersList[i]["announce"] = value.Url
		trackersList[i]["id"] = id
		trackersList[i]["scrape"] = value.Url
		trackersList[i]["tier"] = 0 // TODO
	}

	dst["trackers"] = trackersList
}

func MapPropsTrackerStats(dst JsonMap, trackers []qBT.PropertiesTrackers, torrentInfo *qBT.TorrentInfo) {
	trackerStats := make([]JsonMap, len(trackers))

	for i, value := range trackers {
		id := i

		trackerStats[i] = make(JsonMap)
		for key, value := range transmission.TrackerStatsTemplate {
			trackerStats[i][key] = value
		}
		trackerStats[i]["announce"] = value.Url
		trackerStats[i]["host"] = value.Url
		trackerStats[i]["leecherCount"] = torrentInfo.Num_incomplete
		trackerStats[i]["seederCount"] = torrentInfo.Num_complete
		trackerStats[i]["downloadCount"] = torrentInfo.Num_complete                                      // TODO: Find a more accurate source
		trackerStats[i]["lastAnnouncePeerCount"] = torrentInfo.Num_complete + torrentInfo.Num_incomplete // TODO: Is it correct?
		trackerStats[i]["lastAnnounceResult"] = decodeTrackerStatus(value.Status)
		trackerStats[i]["lastAnnounceSucceeded"] = value.Status == 2
		trackerStats[i]["hasAnnounced"] = value.Status == 2
		trackerStats[i]["id"] = id
		trackerStats[i]["scrape"] = ""
		trackerStats[i]["tier"] = 0 // TODO
	}

	dst["trackerStats"] = trackerStats
}

func decodeTrackerStatus(status int) string {
	switch status {
	case 0:
		return "Tracker is disabled"
	case 1:
		return "Tracker has not been contacted yet"
	case 2:
		return "Tracker has been contacted and is working"
	case 3:
		return "Tracker is updating"
	case 4:
		return "Tracker has been contacted, but it is not working (or doesn't send proper replies)"
	default:
		return "Unknown status"
	}
}

func MapPropsFiles(dst JsonMap, filesInfo []qBT.PropertiesFiles) {
	fileNum := len(filesInfo)
	files := make([]JsonMap, fileNum)
	fileStats := make([]JsonMap, fileNum)
	priorities := make([]int, fileNum)
	wanted := make([]int, fileNum)
	for i, value := range filesInfo {
		files[i] = make(JsonMap)
		fileStats[i] = make(JsonMap)

		files[i]["bytesCompleted"] = float64(value.Size) * value.Progress
		files[i]["length"] = value.Size
		convertedName := EscapeString(value.Name)
		files[i]["name"] = convertedName

		fileStats[i]["bytesCompleted"] = float64(value.Size) * value.Progress
		if value.Priority == 0 {
			fileStats[i]["wanted"] = false
			wanted[i] = 0
		} else {
			fileStats[i]["wanted"] = true
			wanted[i] = 1
		}
		fileStats[i]["priority"] = 0 // TODO
		priorities[i] = 0            // TODO
	}

	dst["files"] = files
	dst["fileStats"] = fileStats
	dst["priorities"] = priorities
	dst["wanted"] = wanted
}

var propsCache = Cache{Timeout: time.Duration(*cacheTimeout) * time.Second}
var trackersCache = Cache{Timeout: time.Duration(*cacheTimeout) * time.Second}

func TorrentGet(args json.RawMessage) (JsonMap, string) {
	var req transmission.GetRequest
	err := json.Unmarshal(args, &req)
	Check(err)

	torrents := parseIDsField(req.Ids)
	severalIDsRequired := len(torrents) > 1
	fields := req.Fields
	filesNeeded := false
	trackersNeeded := false
	trackerStatsNeeded := false
	peersNeeded := false
	propsGeneralNeeded := false
	piecesNeeded := false
	for _, field := range fields {
		additionalRequestsNeeded := true
		switch field {
		case "files", "fileStats", "priorities", "wanted":
			filesNeeded = true
		case "trackers":
			trackersNeeded = true
		case "trackerStats":
			trackerStatsNeeded = true
		case "peers":
			peersNeeded = true
		case "pieceSize", "pieceCount",
			"comment", "dateCreated", "creator",
			"haveValid", "downloadedEver",
			"uploadedEver", "peersConnected", "peersFrom",
			"corruptEver", "uploadLimited", "uploadLimit", "downloadLimited",
			"downloadLimit", "maxConnectedPeers", "peer-limit":
			propsGeneralNeeded = true
		case "pieces":
			piecesNeeded = true
		default:
			additionalRequestsNeeded = false
		}
		if additionalRequestsNeeded && severalIDsRequired {
			log.Info("Field which caused a full torrent scan (slow op!): " + field)
		}
	}

	resultList := make([]JsonMap, len(torrents))
	for i, torrentItem := range torrents {
		translated := make(JsonMap)

		hash := torrentItem.Hash
		id := torrentItem.Id

		MapTorrentList(translated, torrentItem) // TODO: Make it conditional too

		if propsGeneralNeeded {
			log.WithField("id", id).WithField("hash", hash).Debug("Props required")
			propsCache.GetOrFill(hash, translated, severalIDsRequired, func(dest JsonMap) {
				propGeneral := qBTConn.GetPropsGeneral(hash)
				MapPropsGeneral(dest, propGeneral)
				addPropertiesToCommentField(dest, torrentItem, propGeneral)
			})
		}
		if trackersNeeded || trackerStatsNeeded {
			log.WithField("id", id).WithField("hash", hash).Debug("Trackers required")
			trackersCache.GetOrFill(hash, translated, severalIDsRequired, func(dest JsonMap) {
				trackers := qBTConn.GetPropsTrackers(hash)
				MapPropsTrackers(dest, trackers)
				MapPropsTrackerStats(dest, trackers, torrentItem)
			})
		}
		if piecesNeeded {
			log.WithField("id", id).WithField("hash", hash).Debug("Pieces required")
			pieces := qBTConn.GetPiecesStates(hash)
			MapPieceStates(translated, pieces)
		}
		if filesNeeded {
			log.WithField("id", id).WithField("hash", hash).Debug("Files required")
			files := qBTConn.GetPropsFiles(hash)
			MapPropsFiles(translated, files)
		}
		if peersNeeded {
			log.WithField("id", id).WithField("hash", hash).Debug("Peers required")
			MapPropsPeers(translated, hash)
		}

		translated["id"] = id
		translated["queuePosition"] = i + 1
		// TODO: Check it once
		for _, field := range fields {
			if _, ok := translated[field]; !ok {
				if !IsFieldDeprecated(field) {
					log.Error("Unsupported field: ", field)
					panic("Unsupported field: " + field)
				}
			}
		}
		for translatedField := range translated {
			if !Any(fields, translatedField) {
				// Remove unneeded fields
				delete(translated, translatedField)
			}
		}
		resultList[i] = translated
	}
	response := JsonMap{"torrents": resultList}
	addRemovedList(req.Ids, response)
	return response, "success"
}

func addRemovedList(idsField *json.RawMessage, resp JsonMap) {
	if idsField == nil {
		return
	}
	var ids interface{}
	err := json.Unmarshal(*idsField, &ids)
	Check(err)

	switch ids.(type) {
	case string:
		resp["removed"] = qBTConn.TorrentsList.GetRemoved()
	}
}

func qBTEncryptionToTR(enc int) (res string) {
	switch enc {
	case 0:
		return "preferred"
	case 1:
		return "required"
	default:
		return "tolerated"
	}
}

func SessionGet() (JsonMap, string) {
	session := make(JsonMap)
	for key, value := range transmission.SessionGetBase {
		session[key] = value
	}

	prefs := qBTConn.GetPreferences()
	session["download-dir"] = prefs.Save_path
	session["speed-limit-down"] = prefs.Dl_limit / 1024
	session["speed-limit-up"] = prefs.Up_limit / 1024
	if prefs.Dl_limit == -1 {
		session["speed-limit-down-enabled"] = false
	} else {
		session["speed-limit-down-enabled"] = true
	}

	if prefs.Up_limit == -1 {
		session["speed-limit-up-enabled"] = false
	} else {
		session["speed-limit-up-enabled"] = true
	}

	session["peer-limit-global"] = prefs.Max_connec
	session["peer-limit-per-torrent"] = prefs.Max_connec_per_torrent
	session["peer-port"] = prefs.Listen_port
	session["seedRatioLimit"] = prefs.Max_ratio
	session["seedRatioLimited"] = prefs.Max_ratio_enabled
	session["peer-port-random-on-start"] = prefs.Random_port
	session["port-forwarding-enabled"] = prefs.Upnp
	session["utp-enabled"] = prefs.Enable_utp
	session["dht-enabled"] = prefs.Dht
	session["incomplete-dir"] = prefs.Temp_path
	session["incomplete-dir-enabled"] = prefs.Temp_path_enabled
	session["lpd-enabled"] = prefs.Lsd
	session["pex-enabled"] = prefs.Pex
	session["encryption"] = qBTEncryptionToTR(prefs.Encryption)
	session["download-queue-size"] = prefs.Max_active_downloads
	session["seed-queue-size"] = prefs.Max_active_uploads
	session["download-queue-enabled"] = prefs.Queueing_enabled
	session["seed-queue-enabled"] = prefs.Queueing_enabled
	session["download-dir"] = prefs.Save_path

	version := qBTConn.GetVersion()
	session["version"] = "2.94 (really qBT " + string(version) + ")"
	return session, "success"
}

func FreeSpace(args json.RawMessage) (JsonMap, string) {
	req := struct {
		Path string
	}{}
	err := json.Unmarshal(args, &req)
	Check(err)

	diskUsage := du.NewDiskUsage(req.Path)
	freeSpace := diskUsage.Available()

	log.WithField("path", req.Path).WithField("free space", freeSpace).Debug("Free space")

	return JsonMap{
		"path":       req.Path,
		"size-bytes": freeSpace,
	}, "success"
}

func SessionStats() (JsonMap, string) {
	session := make(JsonMap)
	for key, value := range transmission.SessionStatsTemplate {
		session[key] = value
	}

	torrentList := qBTConn.TorrentsList.AllItems()

	paused := 0
	active := 0
	all := len(torrentList)
	timeElapsed := 0

	for _, torrent := range torrentList {
		if qBTStateToTransmissionStatus(torrent.State) == TR_STATUS_STOPPED {
			paused++
		} else {
			active++
		}
	}

	info := qBTConn.GetTransferInfo()
	session["activeTorrentCount"] = active
	session["pausedTorrentCount"] = paused
	session["torrentCount"] = all
	session["downloadSpeed"] = info.Dl_info_speed
	session["uploadSpeed"] = info.Up_info_speed
	session["current-stats"].(map[string]int64)["downloadedBytes"] = info.Dl_info_data
	session["current-stats"].(map[string]int64)["uploadedBytes"] = info.Up_info_data
	session["current-stats"].(map[string]int64)["secondsActive"] = int64(timeElapsed)
	session["cumulative-stats"] = session["current-stats"]
	return session, "success"
}

func TorrentPause(args json.RawMessage) (JsonMap, string) {
	torrents := parseActionArgument(args)
	log.WithField("hashes", torrents.Hashes()).Debug("Stopping torrents")
	qBTConn.PostWithHashes("torrents/pause", torrents)
	return JsonMap{}, "success"
}

func TorrentResume(args json.RawMessage) (JsonMap, string) {
	torrents := parseActionArgument(args)
	log.WithField("hashes", torrents.Hashes()).Debug("Starting torrents")

	qBTConn.PostWithHashes("torrents/resume", torrents)
	return JsonMap{}, "success"
}

func TorrentRecheck(args json.RawMessage) (JsonMap, string) {
	torrents := parseActionArgument(args)
	log.WithField("hashes", torrents.Hashes()).Debug("Verifying torrents")

	qBTConn.PostWithHashes("torrents/recheck", torrents)
	return JsonMap{}, "success"
}

func TorrentDelete(args json.RawMessage) (JsonMap, string) {
	var req struct {
		Ids             json.RawMessage
		DeleteLocalData interface{} `json:"delete-local-data"`
	}
	err := json.Unmarshal(args, &req)
	Check(err)

	torrents := parseIDsField(&req.Ids)
	log.WithField("hashes", torrents.Hashes()).Warn("Going to remove torrents")

	joinedHashes := torrents.ConcatenateHashes()

	deleteFiles := parseDeleteFilesField(req.DeleteLocalData)

	params := map[string]string{"hashes": joinedHashes}

	if deleteFiles {
		log.Info("Going to remove torrents with files: ", joinedHashes)
		params["deleteFiles"] = "true"
	} else {
		log.Info("Going to remove torrents: ", joinedHashes)
		params["deleteFiles"] = "false"
	}
	url := qBTConn.MakeRequestURLWithParam("torrents/delete", params)
	qBTConn.DoGET(url)

	return JsonMap{}, "success"
}

func parseDeleteFilesField(deleteLocalData interface{}) bool {
	switch val := deleteLocalData.(type) {
	case bool:
		return val
	case float64:
		return val != 0
	default:
		return false // Default value
	}
}

func PutMIMEField(mime *multipart.Writer, fieldName string, value string) {
	urlsWriter, err := mime.CreateFormField(fieldName)
	Check(err)
	_, err = urlsWriter.Write([]byte(value))
	Check(err)
}

func AdditionalArgumentToString(value argumentValue) string {
	switch value {
	case ARGUMENT_NOT_SET:
		return "" // TODO
	case ARGUMENT_TRUE:
		return "true"
	case ARGUMENT_FALSE:
		return "false"
	default:
		return ""
	}
}

func UploadTorrent(metainfo *[]byte, urls *string, req *transmission.TorrentAddRequest, paused bool) {
	var buffer bytes.Buffer
	mime := multipart.NewWriter(&buffer)

	if metainfo != nil {
		mimeWriter, err := mime.CreateFormFile("torrents", "example.torrent")
		Check(err)
		mimeWriter.Write(*metainfo)
	}

	if urls != nil {
		PutMIMEField(mime, "urls", *urls)
	}

	if req.Download_dir != nil {
		extraArgs, strippedLocation, err := parseAdditionalLocationArguments(*req.Download_dir)
		Check(err)
		log.Debug("Stripped location is ", strippedLocation)

		if extraArgs.sequentialDownload != ARGUMENT_NOT_SET {
			log.Debug("Sequential download: ", AdditionalArgumentToString(extraArgs.sequentialDownload))
			PutMIMEField(mime, "sequentialDownload",
				AdditionalArgumentToString(extraArgs.sequentialDownload))
		}

		if extraArgs.firstLastPiecesFirst != ARGUMENT_NOT_SET {
			log.Debug("FirstLastPiecePrio: ", AdditionalArgumentToString(extraArgs.firstLastPiecesFirst))
			PutMIMEField(mime, "firstLastPiecePrio",
				AdditionalArgumentToString(extraArgs.firstLastPiecesFirst))
		}

		if extraArgs.skipChecking != ARGUMENT_NOT_SET {
			log.Debug("Skip checking: ", AdditionalArgumentToString(extraArgs.skipChecking))
			PutMIMEField(mime, "skip_checking",
				AdditionalArgumentToString(extraArgs.skipChecking))
		}

		PutMIMEField(mime, "savepath", strippedLocation)
	}

	pausedWriter, err := mime.CreateFormField("paused")
	Check(err)
	if paused {
		pausedWriter.Write([]byte("true"))
	} else {
		pausedWriter.Write([]byte("false"))
	}
	mime.CreateFormField("cookie")
	mime.CreateFormField("label")

	mime.Close()

	qBTConn.DoPOST(qBTConn.MakeRequestURL("torrents/add"), mime.FormDataContentType(), &buffer)
	log.Debug("Torrent uploaded")
}

func ParseMagnetLink(link string) (newHash qBT.Hash, newName string) {
	path := strings.TrimPrefix(link, "magnet:?")
	params, err := url.ParseQuery(path)
	Check(err)
	log.WithFields(log.Fields{
		"params": params,
	}).Debug("Params decoded")
	trimmed := strings.TrimPrefix(params["xt"][0], "urn:btih:")
	newHash = qBT.Hash(strings.ToLower(trimmed))
	name, nameProvided := params["dn"]
	if nameProvided {
		newName = name[0]
	} else {
		newName = "Torrent name"
	}
	return
}

func ParseMetainfo(metainfo []byte) (newHash qBT.Hash, newName string) {
	var parsedMetaInfo MetaInfo
	parsedMetaInfo.ReadTorrentMetaInfoFile(bytes.NewBuffer(metainfo))

	log.WithFields(log.Fields{
		"len":  len(metainfo),
		"sha1": fmt.Sprintf("%x\n", sha1.Sum(metainfo)),
	}).Debug("Decoded metainfo")

	newHash = qBT.Hash(fmt.Sprintf("%x", parsedMetaInfo.InfoHash))
	newName = parsedMetaInfo.Info.Name
	return
}

func TorrentAdd(args json.RawMessage) (JsonMap, string) {
	var req transmission.TorrentAddRequest
	err := json.Unmarshal(args, &req)
	Check(err)

	qBTConn.UpdateTorrentsList()

	var newHash qBT.Hash
	var newName string

	paused := false
	if req.Paused != nil {
		if value, ok := (*req.Paused).(float64); ok {
			// Workaround: Transmission Remote GUI uses a number instead of a boolean
			log.Debug("Apply Transmission Remote GUI workaround")
			paused = value != 0
		}
		if value, ok := (*req.Paused).(bool); ok {
			paused = value
		}
	}

	if req.Metainfo != nil {
		log.Debug("Upload torrent from metainfo")
		metainfo, err := base64.StdEncoding.DecodeString(*req.Metainfo)
		Check(err)
		newHash, newName = ParseMetainfo(metainfo)
		UploadTorrent(&metainfo, nil, &req, paused)
	} else if req.Filename != nil {
		path := *req.Filename
		if strings.HasPrefix(path, "magnet:?") {
			newHash, newName = ParseMagnetLink(path)

			UploadTorrent(nil, &path, &req, paused)
		} else if strings.HasPrefix(path, "http") {
			metainfo := DoGetWithCookies(path, req.Cookies)

			newHash, newName = ParseMetainfo(metainfo)
			UploadTorrent(&metainfo, nil, &req, paused)
		}
	}

	log.WithFields(log.Fields{
		"hash": newHash,
		"name": newName,
	}).Debug("Attempting to add torrent")

	if torrent := qBTConn.TorrentsList.ByHash(newHash); torrent != nil {
		return JsonMap{
			"torrent-duplicate": JsonMap{
				"id":         torrent.Id,
				"name":       newName,
				"hashString": newHash,
			},
		}, "success"
	}

	var torrent *qBT.TorrentInfo
	for retries := 0; retries < 100; retries++ {
		time.Sleep(50 * time.Millisecond)
		qBTConn.UpdateTorrentsList()
		torrent = qBTConn.TorrentsList.ByHash(newHash)
		if torrent != nil {
			log.Debug("Found ID ", torrent.Id)
			break
		}

		log.Debug("Nothing was found, waiting...")
	}

	if torrent == nil {
		return JsonMap{}, "Torrent-add timeout"
	}

	log.WithFields(log.Fields{
		"hash": newHash,
		"id":   torrent.Id,
		"name": newName,
	}).Debug("New torrent")

	return JsonMap{
		"torrent-added": JsonMap{
			"id":         torrent.Id,
			"name":       newName,
			"hashString": newHash,
		},
	}, "success"
}

func TorrentSet(args json.RawMessage) (JsonMap, string) {
	var req struct {
		Ids            *json.RawMessage
		Files_wanted   *[]int `json:"files-wanted"`
		Files_unwanted *[]int `json:"files-unwanted"`
	}
	err := json.Unmarshal(args, &req)
	Check(err)

	if req.Files_wanted != nil || req.Files_unwanted != nil {
		torrents := parseIDsField(req.Ids)
		if len(torrents) != 1 {
			log.Error("Unsupported torrent-set request")
			return JsonMap{}, "Unsupported torrent-set request"
		}
		torrent := torrents[0]

		newFilesPriorities := make(map[int]int)
		if req.Files_wanted != nil {
			wanted := *req.Files_wanted
			for _, fileId := range wanted {
				newFilesPriorities[fileId] = 1 // Normal priority
			}
		}
		if req.Files_unwanted != nil {
			unwanted := *req.Files_unwanted
			for _, fileId := range unwanted {
				newFilesPriorities[fileId] = 0 // Do not download
			}
		}
		log.WithFields(log.Fields{
			"priorities": newFilesPriorities,
		}).Debug("New files priorities")

		for fileId, priority := range newFilesPriorities {
			params := url.Values{
				"hash":     {string(torrent.Hash)},
				"id":       {strconv.Itoa(fileId)},
				"priority": {strconv.Itoa(priority)},
			}
			qBTConn.PostForm(qBTConn.MakeRequestURL("torrents/filePrio"), params)
		}
	}

	return JsonMap{}, "success" // TODO
}

var additionalArgumentsRegexp = regexp.MustCompile("([+\\-])([sfh]+)$")

func parseAdditionalLocationArguments(originalLocation string) (args additionalArguments, strippedLocation string, err error) {
	strippedLocation = additionalArgumentsRegexp.ReplaceAllLiteralString(originalLocation, "")
	submatches := additionalArgumentsRegexp.FindStringSubmatch(originalLocation)
	if len(submatches) == 0 {
		return
	}
	for _, c := range submatches[2] {
		flagValue := ARGUMENT_NOT_SET
		switch submatches[1] {
		case "+":
			flagValue = ARGUMENT_TRUE
		case "-":
			flagValue = ARGUMENT_FALSE
		default:
			err = errors.New("Unknown value: " + submatches[1])
			return
		}
		switch c {
		case 's':
			args.sequentialDownload = flagValue
		case 'f':
			args.firstLastPiecesFirst = flagValue
		case 'h':
			args.skipChecking = flagValue
		default:
			err = errors.New("Unknown value: " + submatches[1])
			return
		}
	}
	return
}

func TorrentSetLocation(args json.RawMessage) (JsonMap, string) {
	var req struct {
		Ids      *json.RawMessage
		Location *string     `json:"location"`
		Move     interface{} `json:"move"`
	}
	err := json.Unmarshal(args, &req)
	Check(err)

	log.Debug("New location: ", *req.Location)
	if req.Location == nil {
		return JsonMap{}, "Absent location field"
	}

	torrents := parseIDsField(req.Ids)

	/*var move bool // TODO: Move to a function
	switch val := req.Move.(type) {
	case bool:
		move = val
	case float64:
		move = (val != 0)
	}*/

	extraArgs, strippedLocation, err := parseAdditionalLocationArguments(*req.Location)
	Check(err)

	if extraArgs.firstLastPiecesFirst != ARGUMENT_NOT_SET {
		for _, torrent := range torrents {
			qBTConn.SetFirstLastPieceFirst(torrent.Hash, extraArgs.firstLastPiecesFirst == ARGUMENT_TRUE)
		}
	}

	if extraArgs.sequentialDownload != ARGUMENT_NOT_SET {
		for _, torrent := range torrents {
			qBTConn.SetSequentialDownload(torrent.Hash, extraArgs.sequentialDownload == ARGUMENT_TRUE)
		}
	}

	params := url.Values{
		"hashes":   {torrents.ConcatenateHashes()},
		"location": {strippedLocation},
	}
	qBTConn.PostForm(qBTConn.MakeRequestURL("torrents/setLocation"), params)

	return JsonMap{}, "success"
}

func handler(w http.ResponseWriter, r *http.Request) {
	var req transmission.RPCRequest
	reqBody, err := ioutil.ReadAll(r.Body)
	log.Debug("Got request ", string(reqBody))
	err = json.Unmarshal(reqBody, &req)
	Check(err)

	if !qBTConn.IsLoggedIn() {
		var authOK = false
		username, password, present := r.BasicAuth()
		if present {
			authOK = qBTConn.Login(username, password)
		} else {
			authOK = qBTConn.Login("", "")
		}
		if !authOK {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
	}

	var resp JsonMap
	var result string
	switch req.Method {
	case "session-get":
		resp, result = SessionGet()
	case "free-space":
		resp, result = FreeSpace(req.Arguments)
	case "torrent-get":
		resp, result = TorrentGet(req.Arguments)
	case "session-stats":
		resp, result = SessionStats()
	case "torrent-stop":
		resp, result = TorrentPause(req.Arguments)
	case "torrent-start":
		resp, result = TorrentResume(req.Arguments)
	case "torrent-start-now":
		resp, result = TorrentResume(req.Arguments)
	case "torrent-verify":
		resp, result = TorrentRecheck(req.Arguments)
	case "torrent-remove":
		resp, result = TorrentDelete(req.Arguments)
	case "torrent-add":
		resp, result = TorrentAdd(req.Arguments)
	case "torrent-set":
		resp, result = TorrentSet(req.Arguments)
	case "torrent-set-location":
		resp, result = TorrentSetLocation(req.Arguments)
	default:
		log.Error("Unknown method: ", req.Method)
	}
	response := JsonMap{
		"result":    result,
		"arguments": resp,
	}
	if req.Tag != nil {
		response["tag"] = req.Tag
	}
	respBody, err := json.Marshal(response)
	Check(err)
	log.Debug("respBody: ", string(respBody))
	w.Header().Set("Content-Length", strconv.Itoa(len(respBody)))
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	_, err = w.Write(respBody) // TODO: Check whether it's necessary to evaluate written bytes number
	Check(err)
}

func main() {
	switch {
	case *debug:
		log.SetLevel(log.DebugLevel)
	case *verbose:
		log.SetLevel(log.InfoLevel)
	default:
		log.SetLevel(log.WarnLevel)
	}
	var cl *http.Client
	if *disableKeepAlive {
		log.Info("Disabled HTTP keep-alive")
		tr := &http.Transport{
			DisableKeepAlives: true,
		}
		cl = &http.Client{Transport: tr}
	} else {
		cl = &http.Client{}
	}
	qBTConn.Init(*apiAddr, cl, *useSync)

	http.HandleFunc("/transmission/rpc", handler)
	http.HandleFunc("/rpc", handler)
	http.Handle("/", http.FileServer(http.Dir("web/")))
	err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
	Check(err)
}


text:
<?php

namespace Finite\Exception;

/**
 * A exception throws from a factory.
 *
 * @author Yohan Giarelli <yohan@giarel.li>
 */
class FactoryException extends Exception
{
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.lucene.analysis.charfilter;

import org.apache.lucene.analysis.charfilter.HTMLStripCharFilter;
import org.apache.lucene.analysis.util.CharFilterFactory;

import java.io.Reader;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Factory for {@link HTMLStripCharFilter}.
 *

 * <fieldType name="text_html" class="solr.TextField" positionIncrementGap="100">
 *   <analyzer>
 *     <charFilter class="solr.HTMLStripCharFilterFactory" escapedTags="a, title" />
 *     <tokenizer class="solr.WhitespaceTokenizerFactory"/>
 *   </analyzer>
 * </fieldType>

 *
 */
 public class HTMLStripCharFilterFactory extends CharFilterFactory {

  Set<String> escapedTags = null;
  Pattern TAG_NAME_PATTERN = Pattern.compile("[^\\s,]+");

  public HTMLStripCharFilter create(Reader input) {
    HTMLStripCharFilter charFilter;
    if (null == escapedTags) {
      charFilter = new HTMLStripCharFilter(input);
    } else {
      charFilter = new HTMLStripCharFilter(input, escapedTags);
    }
    return charFilter;
  }

  @Override
  public void init(Map<String,String> args) {
    super.init(args);
    String escapedTagsArg = args.get("escapedTags");
    if (null != escapedTagsArg) {
      Matcher matcher = TAG_NAME_PATTERN.matcher(escapedTagsArg);
      while (matcher.find()) {
        if (null == escapedTags) {
          escapedTags = new HashSet<String>();
        }
        escapedTags.add(matcher.group(0));
      }
    }
  }
}


text:
{% load staticfiles %}
{% load theme_meta_data_tags %}

<!DOCTYPE html>

	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

	{% meta_data meta_data_locals %}

	<link rel="icon" href="{% static 'image/favicon.png' %}">

    <title>{% theme_title title %}</title>

    {% include 'theme-head-css.html' %}

		{% block head_css %}
		{% endblock %}

		{% include 'theme-head-javascript.html' %}

		{% include 'theme-navbar.html' %}

			{% block content %}
			{% endblock %}

	{% include 'theme-footer.html' %}

	{% block page_javascript %}
	{% endblock %}

	{% micro_data %}


text:
@extends('admin.master')

@section('title')
@parent
Onsite Support List - Maintenance Support - E Inboisu
@stop

@section('breadcrumb')
@parent

Maintenance Support

Onsite Support List

@stop

@section('page_title_icon')
building
@stop

@section('sub_navigation')
	@include('admin.navigation-maintenance')
@stop

@section('page_title')
Onsite Support List
@stop

@section('page_title_right')

@stop

@section('modals')

@stop

@section('content')

		@if($errors->count() > 0)

				@foreach($errors->all() as $error)

{{$error}}

				@endforeach

		@endif

List of Onsite Support

									Company
									 Hours Spent
									 Onsite Date

								@foreach($onsitesupports as $onsitesupport)

									maintenance_id))}}" title="Edit" >{{$onsitesupport->maintenance->client->name}}
									{{$onsitesupport->hours_spent}}
									{{$onsitesupport->onsite_date}}

								@endforeach

@stop

@section('page_scripts')
{{HTML::script("/assets/js/plugin/datatables/jquery.dataTables.min.js");}}
{{HTML::script("/assets/js/plugin/datatables/dataTables.colVis.min.js");}}
{{HTML::script("/assets/js/plugin/datatables/dataTables.tableTools.min.js");}}
{{HTML::script("/assets/js/plugin/datatables/dataTables.bootstrap.min.js");}}
{{HTML::script("/assets/js/plugin/datatable-responsive/datatables.responsive.min.js");}}
@stop

@section('document_ready')
var responsiveHelper_dt_basic = undefined;
var responsiveHelper_datatable_fixed_column = undefined;
var responsiveHelper_datatable_col_reorder = undefined;
var responsiveHelper_datatable_tabletools = undefined;

var breakpointDefinition = {
tablet : 1024,
phone : 480
};

$('#dt_basic').dataTable({
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"iDisplayLength" : 25,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_dt_basic) {
responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_dt_basic.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_dt_basic.respond();
}
});
/* END BASIC */

/* COLUMN FILTER  */
var otable = $('#datatable_fixed_column').DataTable({
//"bFilter": false,
//"bInfo": false,
//"bLengthChange": false
//"bAutoWidth": false,
//"bPaginate": false,
//"bStateSave": true // saves sort state using localStorage
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6 hidden-xs'f><'col-sm-6 col-xs-12 hidden-xs'<'toolbar'>>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_fixed_column) {
responsiveHelper_datatable_fixed_column = new ResponsiveDatatablesHelper($('#datatable_fixed_column'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_fixed_column.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_fixed_column.respond();
}

});

// custom toolbar
$("div.toolbar").html('

');

// Apply the filter
$("#datatable_fixed_column thead th input[type=text]").on( 'keyup change', function () {

otable
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();

} );
/* END COLUMN FILTER */

/* COLUMN SHOW - HIDE */
$('#datatable_col_reorder').dataTable({
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-6 hidden-xs'C>r>"+
"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"autoWidth" : true,
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_col_reorder) {
responsiveHelper_datatable_col_reorder = new ResponsiveDatatablesHelper($('#datatable_col_reorder'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_col_reorder.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_col_reorder.respond();
}
});

/* END COLUMN SHOW - HIDE */
@stop

@section('javascript')

@stop


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Tobias Gödderz
/// @author Michael Hackstein
/// @author Heiko Kernbach
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#pragma once

#include "Aql/AqlItemBlockInputRange.h"
#include "Aql/ExecutionBlock.h"
#include "Aql/ExecutionState.h"
#include "Aql/InputAqlItemRow.h"
#include "Aql/ShadowAqlItemRow.h"
#include "Aql/types.h"

#include <memory>

namespace arangodb::aql {

class AqlItemBlock;
template <BlockPassthrough>
class DependencyProxy;
class SkipResult;

/**
 * @brief Interface for all AqlExecutors that do only need one
 *        row at a time in order to make progress.
 */
template <BlockPassthrough blockPassthrough>
class SingleRowFetcher {
 public:
  explicit SingleRowFetcher(DependencyProxy<blockPassthrough>& executionBlock);
  TEST_VIRTUAL ~SingleRowFetcher() = default;

  using DataRange = AqlItemBlockInputRange;

 protected:
  // only for testing! Does not initialize _dependencyProxy!
  SingleRowFetcher();

 public:
  /**
   * @brief Execute the given call stack
   *
   * @param stack Call stack, on top of stack there is current subquery, bottom is the main query.
   * @return std::tuple<ExecutionState, size_t, DataRange>
   *   ExecutionState => DONE, all queries are done, there will be no more
   *   ExecutionState => HASMORE, there are more results for queries, might be on other subqueries
   *   ExecutionState => WAITING, we need to do I/O to solve the request, save local state and return WAITING to caller immediately
   *
   *   size_t => Amount of documents skipped
   *   DataRange => Resulting data
   */
  std::tuple<ExecutionState, SkipResult, DataRange> execute(AqlCallStack& stack);

  void setDistributeId(std::string const& id);

 private:
  DependencyProxy<blockPassthrough>* _dependencyProxy;

};
}  // namespace arangodb::aql


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/background_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/message_card_margin_small"
        android:layout_marginLeft="@dimen/message_card_margin_medium"
        android:layout_marginTop="@dimen/message_card_margin_small"
        app:cardBackgroundColor="@color/susi_message_bg"
        app:contentPadding="@dimen/standard_content_padding">

        <LinearLayout
            android:layout_width="@dimen/message_layout_max_width"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <org.fossasia.susi.ai.ChatBubbleLayout
                android:id="@+id/chat_bubble_item_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="1">

                <TextView
                    android:id="@+id/text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="start|left"
                    android:autoLink="all"
                    android:maxWidth="@dimen/message_layout_max_width"
                    android:paddingBottom="@dimen/message_textview_bottom_padding"
                    android:text="@string/hello_world"
                    android:textColor="@color/message_text_color"
                    android:textSize="@dimen/message_text_size" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_gravity="end|right|bottom"
                    android:gravity="bottom"
                    android:paddingLeft="8dp">

                    <TextView
                        android:id="@+id/timestamp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="bottom"
                        android:text="9:00 AM"
                        android:textSize="@dimen/timestamp_size" />

                </LinearLayout>
            </org.fossasia.susi.ai.ChatBubbleLayout>

            <LinearLayout
                android:id="@+id/web_preview_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/web_link_preview_image"
                    android:layout_width="@dimen/webpreview_layout_height"
                    android:layout_height="@dimen/webpreview_layout_height"
                    android:layout_marginTop="@dimen/margin_small"
                    android:layout_weight="0.2"
                    android:background="#aaffffff"
                    app:srcCompat="@drawable/ic_user" />

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/preview_layout_height"
                    android:layout_marginTop="@dimen/message_layout_margin"
                    android:layout_weight="0.8"
                    android:background="@color/susi_message_link_preview_bg"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/web_link_preview_title"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/webpreview_headline_height"
                        android:background="@color/susi_message_link_preview_bg"
                        android:maxLines="1"
                        android:padding="@dimen/standard_content_padding"
                        android:textColor="@color/md_grey_800"
                        tools:text="@string/sample_website_headline" />

                    <TextView
                        android:id="@+id/web_link_preview_description"
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/webpreview_content_height"
                        android:layout_gravity="bottom"
                        android:gravity="center_vertical"
                        android:maxLines="2"
                        android:padding="@dimen/standard_content_padding"
                        android:textColor="@color/md_grey_600"
                        tools:text="@string/sample_website_description" />

                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>


text:
<?php declare(strict_types = 1);

use Oops\TotpAuthenticator\Security\TotpAuthenticator;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';

$seed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$timeProvider = Mockery::mock('Oops\TotpAuthenticator\Utils\TimeProvider')
	->shouldReceive('getMicroTime')->andReturn(1415778000)->getMock();

$googleAuthenticator = (new TotpAuthenticator($timeProvider))->setTimeWindow(0);
Assert::false($googleAuthenticator->verifyCode('209170', $seed)); // offset = -2
Assert::false($googleAuthenticator->verifyCode('101895', $seed)); // offset = -1
Assert::true($googleAuthenticator->verifyCode('292224', $seed)); // offset = 0
Assert::false($googleAuthenticator->verifyCode('800413', $seed)); // offset = +1
Assert::false($googleAuthenticator->verifyCode('223013', $seed)); // offset = +2

$googleAuthenticator = (new TotpAuthenticator($timeProvider))->setTimeWindow(1);
Assert::false($googleAuthenticator->verifyCode('209170', $seed)); // offset = -2
Assert::true($googleAuthenticator->verifyCode('101895', $seed)); // offset = -1
Assert::true($googleAuthenticator->verifyCode('292224', $seed)); // offset = 0
Assert::true($googleAuthenticator->verifyCode('800413', $seed)); // offset = +1
Assert::false($googleAuthenticator->verifyCode('223013', $seed)); // offset = +2

$googleAuthenticator = (new TotpAuthenticator($timeProvider))->setTimeWindow(2);
Assert::true($googleAuthenticator->verifyCode('209170', $seed)); // offset = -2
Assert::true($googleAuthenticator->verifyCode('101895', $seed)); // offset = -1
Assert::true($googleAuthenticator->verifyCode('292224', $seed)); // offset = 0
Assert::true($googleAuthenticator->verifyCode('800413', $seed)); // offset = +1
Assert::true($googleAuthenticator->verifyCode('223013', $seed)); // offset = +2

Mockery::close();


text:
package com.airhacks.headlands.sync;

import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 *
 * @author airhacks.com
 */
public class CacheService {

    private Client client;
    private String resource = "/headlands/resources/caches";

    @PostConstruct
    public void initialize() {
        this.client = ClientBuilder.newClient();
    }

    public void sync(Consumer<String> progressListener, String fromHost, String toHost) {
        Set<String> cacheNames = getCacheNames(fromHost);
        progressListener.accept(cacheNames.size() + " caches found!");
        cacheNames.forEach(name -> copy(progressListener, name, fromHost, toHost));

    }

    Set<String> getCacheNames(String host) {
        WebTarget target = getTarget(host);
        Response response = target.request(MediaType.APPLICATION_JSON).get();
        JsonArray cacheNames = response.readEntity(JsonArray.class);
        List<JsonObject> jsonStringList = cacheNames.getValuesAs(JsonObject.class);
        return jsonStringList.stream().map(j -> j.getString("name")).collect(Collectors.toSet());
    }

    WebTarget getTarget(String host) {
        return this.client.target(host + resource);
    }

    void copy(Consumer<String> progressListener, String cacheName, String fromHost, String toHost) {
        final WebTarget toTarget = getTarget(toHost);
        createCache(toTarget, cacheName);
        JsonObject dump = toTarget.path(cacheName).path("entries").
                request(MediaType.APPLICATION_JSON).
                get(JsonObject.class);
        progressListener.accept("Dump with " + dump.size() + " downloaded!");
        dump.keySet().forEach(key -> createEntry(toTarget, cacheName, key, dump.getString(key)));
        progressListener.accept("Content synced");

    }

    public static Response createEntry(WebTarget caches, String cache, String key, String value) {
        return caches.path(cache).path("entries").path(key).request().put(Entity.text(value));
    }

    public static Response createCache(WebTarget target, String cacheName) {
        JsonObject configuration = Json.createObjectBuilder().build();
        return target.path(cacheName).request().put(Entity.json(configuration));
    }

}


text:
class AddKewordsToCategories < ActiveRecord::Migration[4.2]
  def change
    add_column :categories, :keywords_de, :text
    add_column :categories, :keywords_en, :text
    add_column :categories, :keywords_ar, :text
    add_column :categories, :keywords_fa, :text
  end
end


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./src/ng2-helloworld.component'));
__export(require('./src/ng2-helloworld.module'));
//# sourceMappingURL=ng2-helloworld.js.map


text:
package compression

import (
	"compress/gzip"
	"io"
)

type GzipCompressor struct{}

func (c *GzipCompressor) AcceptEncoding() string {
	return "gzip"
}

func (c *GzipCompressor) ContentEncoding() string {
	return "gzip"
}

func (c *GzipCompressor) NewReader(r io.Reader) (io.ReadCloser, error) {
	return gzip.NewReader(r)
}

func (c *GzipCompressor) NewWriter(w io.Writer) (io.WriteCloser, error) {
	return gzip.NewWriter(w), nil
}

func NewGzipCompressor() *GzipCompressor {
	return &GzipCompressor{}
}


text:
package regolic.asts.theories.number

import regolic.asts.core.Trees._
import regolic.asts.fol.Trees.Constant
import regolic.asts.fol.{Trees => FolT}
import regolic.asts.theories.int.{Trees => IntT}
import regolic.asts.theories.real.{Trees => RealT}
import regolic.algebra.Rational

/*
 * An attempt to make it easy to extract int or real
 * in a generic way, however cannot build any tree
 * from one or the other, so this makes the whole thing
 * pretty pointless
 */

object Trees {

  object NumberSort {
    def unapply(sort: Sort): Boolean = sort match {
      case Sort("Real", List()) => true
      case Sort("Int", List()) => true
      case _ => false
    }
  }

  object EqualsSymbol {
    def unapply(s: PredicateSymbol): Boolean = s match {
      case FolT.EqualsSymbol(NumberSort()) => true
      case _ => false
    }
  }
  object Equals {
    def unapply(pApply: PredicateApplication): Option[(Term, Term)] = pApply match {
      case PredicateApplication(EqualsSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object LessThanSymbol {
    def unapply(symb: PredicateSymbol): Boolean = symb match {
      case PredicateSymbol("<", List(NumberSort(), NumberSort())) => true
      case _ => false
    }
  }
  object LessThan {
    def unapply(appli: PredicateApplication): Option[(Term, Term)] = appli match {
      case PredicateApplication(LessThanSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object LessEqualSymbol {
    def unapply(symb: PredicateSymbol): Boolean = symb match {
      case PredicateSymbol("<=", List(NumberSort(), NumberSort())) => true
      case _ => false
    }
  }
  object LessEqual {
    def unapply(appli: PredicateApplication): Option[(Term, Term)] = appli match {
      case PredicateApplication(LessEqualSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object GreaterThanSymbol {
    def unapply(symb: PredicateSymbol): Boolean = symb match {
      case PredicateSymbol(">", List(NumberSort(), NumberSort())) => true
      case _ => false
    }
  }
  object GreaterThan {
    def unapply(appli: PredicateApplication): Option[(Term, Term)] = appli match {
      case PredicateApplication(GreaterThanSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object GreaterEqualSymbol {
    def unapply(symb: PredicateSymbol): Boolean = symb match {
      case PredicateSymbol(">=", List(NumberSort(), NumberSort())) => true
      case _ => false
    }
  }
  object GreaterEqual {
    def unapply(appli: PredicateApplication): Option[(Term, Term)] = appli match {
      case PredicateApplication(GreaterEqualSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object Var {
    def unapply(v: Variable): Option[String] = v match {
      case Variable(name, NumberSort()) => Some(name)
      case _ => None
    }
  }

  object Num {
    def unapply(appli: FunctionApplication): Option[Rational] = appli match {
      case IntT.Num(i) => Some(Rational(i))
      case RealT.Num(r) => Some(r)
      case _ => None
    }
  }

  object Zero {
    def unapply(appli: FunctionApplication): Boolean = appli match {
      case Num(r) => r.isZero
      case _ => false
    }
  }
  object One {
    def unapply(appli: FunctionApplication): Boolean = appli match {
      case Num(r) => r.isOne
      case _ => false
    }
  }

  object AddSymbol {
    def unapply(symb: FunctionSymbol): Option[Int] = symb match {
      case FunctionSymbol("+", argsSort, NumberSort()) if
        argsSort.forall{
          case NumberSort() => true
          case _ => false
        } => Some(argsSort.size)
      case _ => None
    }
  }
  object Add {
    def unapply(appli: FunctionApplication): Option[List[Term]] = appli match {
      case FunctionApplication(AddSymbol(_), ts) => Some(ts)
      case _ => None
    }
  }

  object SubSymbol {
    def unapply(symb: FunctionSymbol): Boolean = symb match {
      case FunctionSymbol("-", List(NumberSort(), NumberSort()), NumberSort()) => true
      case _ => false
    }
  }
  object Sub {
    def unapply(appli: FunctionApplication): Option[(Term, Term)] = appli match {
      case FunctionApplication(SubSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object MulSymbol {
    def unapply(symb: FunctionSymbol): Option[Int] = symb match {
      case FunctionSymbol("*", argsSort, NumberSort()) if
        argsSort.forall{
          case NumberSort() => true
          case _ => false
        } => Some(argsSort.size)
      case _ => None
    }
  }
  object Mul {
    def unapply(appli: FunctionApplication): Option[List[Term]] = appli match {
      case FunctionApplication(MulSymbol(_), ts) => Some(ts)
      case _ => None
    }
  }

  object DivSymbol {
    def unapply(symb: FunctionSymbol): Boolean = symb match {
      case FunctionSymbol("/", List(NumberSort(), NumberSort()), NumberSort()) => true
      case _ => false
    }
  }
  object Div {
    def unapply(appli: FunctionApplication): Option[(Term, Term)] = appli match {
      case FunctionApplication(DivSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }

  object NegSymbol {
    def unapply(symb: FunctionSymbol): Boolean = symb match {
        case FunctionSymbol("-", List(NumberSort()), NumberSort()) => true
        case _ => false
    }
  }
  object Neg {
    def unapply(appli: FunctionApplication): Option[Term] = appli match {
      case FunctionApplication(NegSymbol(), List(t)) => Some(t)
      case _ => None
    }
  }

  object PowSymbol {
    def unapply(symb: FunctionSymbol): Boolean = symb match {
      case FunctionSymbol("^", List(NumberSort(), NumberSort()), NumberSort()) => true
      case _ => false
    }
  }
  object Pow {
    def unapply(appli: FunctionApplication): Option[(Term, Term)] = appli match {
      case FunctionApplication(PowSymbol(), List(t1, t2)) => Some((t1, t2))
      case _ => None
    }
  }
}


text:
package com.delormeloic.generator.view.slidesforms;

import com.delormeloic.generator.model.slides.Header;
import com.delormeloic.generator.view.converters.FontStringConverter;
import com.delormeloic.generator.view.helpers.FontsHelper;
import com.delormeloic.generator.view.helpers.FormBuilderHelper;
import com.delormeloic.generator.view.helpers.TextHelper;

import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.text.Font;

/**
 * This class represents an header form.
 *
 * @author DELORME Loïc
 * @since 1.0.0
 */
public class HeaderForm implements IFormable
{
	/**
	 * The header.
	 */
	private final Header header;

	/**
	 * Create an header form.
	 *
	 * @param header
	 *            The header.
	 */
	public HeaderForm(Header header)
	{
		this.header = header;
	}

	/**
	 * @see com.delormeloic.generator.view.slidesforms.IFormable#toForm()
	 */
	@Override
	public Node toForm()
	{
		final TextField middleTextTextField = new TextField();
		middleTextTextField.textProperty().bindBidirectional(this.header.getMiddleTextProperty());

		final ComboBox<Font> middleTextFontComboBox = new ComboBox<Font>(FontsHelper.getAllAvailableFonts());
		middleTextFontComboBox.setConverter(new FontStringConverter());
		middleTextFontComboBox.valueProperty().bindBidirectional(this.header.getMiddleTextFontProperty());

		final TitledPane middleTextTitledPane = new TitledPane(TextHelper.getText("headerFormMiddleTextTitledPane"), new HBox(middleTextTextField));
		middleTextTitledPane.setCollapsible(false);
		HBox.setHgrow(middleTextTextField, Priority.ALWAYS);
		final TitledPane middleTextFontTitledPane = new TitledPane(TextHelper.getText("headerFormMiddleTextFontTitledPane"), new HBox(middleTextFontComboBox));
		middleTextFontTitledPane.setCollapsible(false);

		final TitledPane middleTitledPane = FormBuilderHelper.buildTitledPane(TextHelper.getText("headerFormMiddleTitledPane"), new TitledPane[] { middleTextTitledPane, middleTextFontTitledPane });

		return FormBuilderHelper.buildTitledPane(TextHelper.getText("slideFormDataTitledPane"), new TitledPane[] { middleTitledPane });
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString()
	{
		return "Header";
	}
}


text:
build:
	docker build -t fgrehm/sbc-article-latex .

hack:
	docker run -ti --rm --user="$$(id -u):$$(id -g)" -v `pwd`/sample:/workspace -w /workspace fgrehm/sbc-article-latex bash


text:
package jj.http.server.websocket;

import org.slf4j.Logger;

import jj.ServerLogger;
import jj.logging.LoggedEvent;

/**
 *
 * @author jason
 *
 */
@ServerLogger
public class WebSocketClientConnected extends LoggedEvent {

	private final WebSocketConnection connection;

	WebSocketClientConnected(WebSocketConnection connection) {
		this.connection = connection;
	}

	@Override
	public void describeTo(Logger logger) {
		logger.info("New {}", connection);
	}

}


text:
Template rendering: {! exampledata !}

There are a lot more features (loops, Ifs, etc) but nice and simple


text:
module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    assemble: {
      options: {partials: 'css/*.css'},
      templates: {
        src: 'templates/**/*.html',
        dest: 'build/downloads',
        cwd: './'
      },
      docsDev: {
        src: 'docs/examples/*.html',
        dest: 'build/docs',
        cwd: './'
      },
      docsDeploy: {
        src: 'docs/examples/*.html',
        dest: 'build',
        cwd: './'
      }
    },
    shell: {
      makeStage: {
        command: [
          'rm -rf build',
          'mkdir build',
          'mkdir build/downloads',
          'mkdir build/downloads/templates',
          'mkdir build/downloads/framework',
          'mkdir build/docs',
        ].join('&&')
      },
      zipTemplates: {
        command: [
          'cd build/downloads/templates/base',
          'cp * ../',
          'cd ../',
          'rm -rf base',
          'zip all-templates.zip *.html',
          'for i in *.html; do zip "${i%}.zip" "$i"; done',
          'cd ../../../'
        ].join('&&')
      },
      zipFramework: {
        command: [
          'cp css/ink.css build/downloads/framework/ink.css',
          'cp templates/boilerplate.html build/downloads/framework/boilerplate.html',
          'cp -r build/downloads/templates/examples build/downloads/framework/examples',
          'cd build/downloads/framework',
          'zip -r ink-<%= pkg.version %>.zip *',
          'cd ../../../',
        ].join('&&')
      },
      linkFramework: {
        command: [
          'cd build/downloads',
          'echo \'<?php $download_file = \"framework/ink-<%= pkg.version %>.zip\" ?>\' > latest.php',
          'cd ../../',
        ].join('&&')
      },
      deployDownloads: {
        command: [
          'cd build/downloads',
          'rsync -r . ink@zurb.com:/var/www/ink/shared/downloads',
          'cd ../../'
        ].join('&&')
      },
      testDocs: {
        command: [
          'cp -r docs/test/* build/docs',
          'cp -r docs/components build/docs/components',
          'cp docs/docs.php build/docs/docs.php',
        ].join('&&')
      },
      deployDocs: {
        command: [
          'rsync -r docs build --exclude test --exclude examples',
          'cd build/docs',
          'rsync -r . ink@zurb.com:/var/www/ink/shared/docs',
          'cd ../../'
        ].join('&&')
      },
      cleanUp: {
        command: [
          'rm -rf build',
          'echo "Deploy Completed"'
        ].join('&&')
      },
    },
    watch: {
      docs: {
        files: ['docs/docs.php', 'docs/**/*.php', 'docs/**/*.html', 'css/*.css'],
        tasks: ['shell:makeStage', 'assemble:docsDev', 'shell:testDocs'],
        options: {
          livereload: true,
        },
      },
      sassTest: {
        files: ['scss/*.scss', 'scss/ink/*.scss', 'scss/ink/components/*.scss'],
        tasks: ['sass:test', 'exec:sassTestDiff'],
      },
      sassWatch: {
        files: ['scss/*.scss', 'scss/ink/*.scss', 'scss/ink/components/*.scss'],
        tasks: ['sass:test', 'copy:sassTest2Dist', 'exec:sassTestDiff'],
      }
    },

    clean: {
      sassCss: ["css"],
      sassTest: ["test/results"],
    },
    copy: {
      sassDeploy: {
        src: 'scss/**',
        dest: 'build/downloads/framework/',
      },
      sassTest2Dist: {
        src: 'test/results/ink.css',
        dest: 'css/ink.css',
      },

    },
    sass: {
      options: {
        style: 'expanded',
        precision: 6
      },
      dist: {
        files: {
          'css/ink.css': 'scss/ink.scss'
        },
      },
      dev: {
        files: {
          'css/ink.css': 'scss/ink.scss'
        },
      },
      test: {
        files: {
          'test/results/ink.css': 'scss/ink.scss',
        },
      },
      testTarget: {
        files: {
          'test/results/target.css': 'test/fixtures/ink.css'
        },
      },
    },
    "regex-replace": {
      sassPrepTestTarget: {
        src: ['test/results/target.css'],
        actions: [
          {
            name: 'Remove annoying linebreak difference',
            search: /(table\[class="body"\] td\.offset\-by\-)(\w+)\s*?(,?\s*)(?=\1\w+)/g,
            replace: '$1$2, ',
          },
          {
            name: 'Change filename of sourcemap to \'ink\' to pass the diff test',
            search: /(\/\*# sourceMappingURL=)(\w+)(\.css\.map)/,
            replace: '$1ink$3',
          },
        ],
      }
    },
    exec: {
      sassTestDiff: {
        command: [
         'diff -bB --brief test/results/target.css test/results/ink.css',
          ';',
          'diff -bB test/results/target.css test/results/ink.css > test/results/diff.txt',
          ';',
         'diff -bBs test/results/target.css test/results/ink.css',
          '&&',
          'rm test/results/diff.txt',
        ].join(''),
        exitCode: [0],
      },
    },
  });

  require('load-grunt-tasks')(grunt, {pattern: ['grunt-*', 'assemble']});

  grunt.registerTask('make:templates', ['assemble:templates', 'shell:zipTemplates']);
  grunt.registerTask('deploy:downloads', ['shell:makeStage', 'assemble:templates', 'shell:zipTemplates', 'shell:zipFramework', 'shell:linkFramework', 'shell:deployDownloads', 'shell:cleanUp']);
  grunt.registerTask('make:docs', ['shell:makeStage', 'assemble:docsDev', 'shell:testDocs']);
  grunt.registerTask('deploy:docs', ['shell:makeStage', 'assemble:docsDeploy', 'shell:deployDocs', 'shell:cleanUp']);
  grunt.registerTask('default', ['make:docs', 'watch:docs']);

  grunt.registerTask('sassy:clean', ['clean:sassCss', 'clean:sassTest']);
  grunt.registerTask('sassy:test:clean', ['clean:sassTest']);
  grunt.registerTask('sassy:test:target', ['newer:sass:testTarget']);
  grunt.registerTask('sassy:test:init', ['sassy:test:clean', 'sassy:test:target']);
  grunt.registerTask('sassy:test:sass', ['sass:test', 'regex-replace:sassPrepTestTarget', 'exec:sassTestDiff']);
  grunt.registerTask('sassy:test', ['sassy:test:target', 'sassy:test:sass']);
  grunt.registerTask('sassy:test:watch', ['sassy:test', 'watch:sassTest']);
  grunt.registerTask('sassy:make', ['sass:dev']);
  grunt.registerTask('sassy', ['sassy:clean', 'sassy:test', 'copy:sassTest2Dist', 'watch:sassWatch']);

  grunt.registerTask('sassy:make:templates', ['sass:dist', 'make:templates']);
  grunt.registerTask('sassy:deploy:downloads', ['shell:makeStage', 'sass:dist', 'copy:sassDeploy', 'assemble:templates', 'shell:zipTemplates', 'shell:zipFramework', 'shell:linkFramework', 'shell:deployDownloads', 'shell:cleanUp']);
  grunt.registerTask('sassy:make:docs', ['sass:dist', 'make:docs']);
  grunt.registerTask('sassy:deploy:docs', ['sass:dist', 'deploy:docs']);
  grunt.registerTask('sassy:default', ['sass:dist', 'default']);

};


text:
import MarcEditorConstants from '../constants/marc-editor-constants';
import {dispatch, register} from '../dispatchers/marc-editor-dispatcher';

export default {
  changeMode(mode, records) {
    dispatch({
      actionType: MarcEditorConstants.CHANGE_MODE, mode, records
    })
  }
}


text:
/* global describe, it */
describe('tabs', function () {
  var tabs = $.require('tabs')

  it('should handle tab switching', function () {
    var tab1 = $('
')
    var tab2 = $('
')
    var tabsElement = $('
').append(tab1).append(tab2)
    tabs({
      tabs: tabsElement
    })
    tab2.click()
    tab1.is('.active').should.equal(false)
    $('#test-tab1').is('.active').should.equal(false)
    tab2.is('.active').should.equal(true)
    $('#test-tab2').is('.active').should.equal(true)
  })
})


text:
layout: page
title: Christensen 50th Anniversary
date: 2016-05-24
author: Shirley Trujillo
tags: weekly links, java
status: published
summary: Quisque rhoncus eget est at interdum. Vestibulum.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 12/24/2019
  endDate: 12/28/2019
  ctyhocn: SEANPHX
  groupCode: C5A
published: true
---
Sed volutpat commodo lorem et euismod. Integer egestas posuere turpis. Curabitur sagittis risus justo, et facilisis elit tincidunt sit amet. Praesent consectetur ornare sem, eget suscipit nulla eleifend non. Pellentesque a venenatis neque. Quisque in justo pellentesque, volutpat diam vitae, fermentum mi. Nam nibh risus, dignissim non massa sodales, bibendum venenatis nisi. Mauris bibendum ullamcorper dolor, in feugiat arcu. Integer et dui consectetur lectus tempor lobortis vel imperdiet neque. Nunc vitae mauris feugiat sapien rhoncus rhoncus. Donec lacinia mattis purus, eu egestas sem euismod id. Maecenas nec tristique nisi, sit amet fringilla nulla. In id turpis tempor, tristique metus eget, posuere nulla.
Vivamus hendrerit ullamcorper massa sit amet condimentum. Pellentesque non placerat eros. Duis tempor molestie velit ut placerat. Integer pellentesque lacus non elit rutrum commodo. Donec convallis at ipsum quis efficitur. Vestibulum fermentum purus metus, eu consequat est interdum sit amet. Nam sit amet eleifend dui, et suscipit nulla. Donec nec tincidunt velit. Suspendisse hendrerit ac justo ut consequat. Phasellus id convallis sapien. Fusce neque quam, venenatis nec feugiat quis, eleifend ac lectus. Aenean tincidunt lectus ut orci vestibulum, eget feugiat magna interdum. Vestibulum feugiat augue congue, cursus lacus ac, rhoncus sapien. Nam ac diam risus.

1 Suspendisse vitae justo ultricies, faucibus dui mattis, aliquam metus
1 Nulla eget tortor eget nibh finibus condimentum elementum non augue
1 Praesent vitae ex quis enim finibus rhoncus congue ac ante
1 Etiam nec turpis non arcu sollicitudin sollicitudin ac id justo.

Sed mollis aliquam dapibus. Proin viverra nibh et felis facilisis eleifend. Ut vel malesuada erat, sit amet molestie nibh. Donec sit amet venenatis augue. Vestibulum gravida justo nec nunc aliquam, in mollis tellus efficitur. In id risus quis tellus auctor sollicitudin sed in elit. In porttitor vel erat sed ultricies.


text:
System.register([], function (_export) {
  "use strict";

  var _prototypeProperties, Welcome, UpperValueConverter;
  return {
    setters: [],
    execute: function () {
      _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };

      Welcome = _export("Welcome", (function () {
        function Welcome() {
          this.heading = "Welcome to the Aurelia Navigation App!";
          this.firstName = "John";
          this.lastName = "Doe";
        }

        _prototypeProperties(Welcome, null, {
          fullName: {
            get: function () {
              return "" + this.firstName + " " + this.lastName;
            },
            configurable: true
          },
          welcome: {
            value: function welcome() {
              alert("Welcome, " + this.fullName + "!");
            },
            writable: true,
            configurable: true
          }
        });

        return Welcome;
      })());
      UpperValueConverter = _export("UpperValueConverter", (function () {
        function UpperValueConverter() {}

        _prototypeProperties(UpperValueConverter, null, {
          toView: {
            value: function toView(value) {
              return value && value.toUpperCase();
            },
            writable: true,
            configurable: true
          }
        });

        return UpperValueConverter;
      })());
    }
  };
});


text:
import Vue from 'vue';
import {Question as QuestionModel} from '../question';
import {Component, Prop} from 'vue-property-decorator';

@Component
export default class Question<T extends QuestionModel> extends Vue {
    @Prop
    question: T
    @Prop
    isEditMode: Boolean
    @Prop
    css: any
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>MCL (Java Machine Learning Library 0.1.7)</title>
<meta name="date" content="2012-07-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.javaml.clustering.mcl

Class MCL

java.lang.Object

net.sf.javaml.clustering.mcl.MCL

All Implemented Interfaces:

Clusterer

public class MCL
extends java.lang.Object
implements Clusterer

Constructor Summary

Constructors

Constructor and Description

MCL(DistanceMeasure dm)

XXX doc

MCL(DistanceMeasure dm,
   double maxResidual,
   double pGamma,
   double loopGain,
   double maxZero)

XXX doc

Method Summary

Methods

Modifier and Type
Method and Description

Dataset[]
cluster(Dataset data)

This method will execute the clustering algorithm on a particular
 data set.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MCL

public MCL(DistanceMeasure dm)

XXX doc

Parameters:

dm -

MCL

public MCL(DistanceMeasure dm,
   double maxResidual,
   double pGamma,
   double loopGain,
   double maxZero)

XXX doc

Parameters:

dm -

maxResidual -

gamma -

loopGain -

maxZero -

Method Detail

cluster

public Dataset[] cluster(Dataset data)

Description copied from interface: Clusterer

This method will execute the clustering algorithm on a particular
 data set. The result will be an array of Dataset where each data set is a
 cluster.

Specified by:

cluster in interface Clusterer

Parameters:

data - the data set on which to execute the clustering.

Returns:

the different clusters obtained by this clustering algorithm.
         Each cluster is represented as a separate data set.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

			Copyright © 2006-2012 - Thomas Abeel - All Rights Reserved.


text:
ZRotation::ZRotation() {
    setAngle(0.0);
}

ZRotation::~ZRotation(void){}

GLfloat ZRotation::getAngle(void)
{
  return angle;
}

void ZRotation::setAngle(GLfloat angle)
{
  this->angle = angle;
}

void ZRotation::display(OpenGL &aOpenGL){
  aOpenGL.display(this);
}


text:
package org.camunda.bpm.example.invoice;

import static org.camunda.bpm.engine.variable.Variables.fileValue;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.IdentityLink;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineTestCase;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;

public class InvoiceTestCase extends ProcessEngineTestCase {

  @Deployment(resources= {"invoice.bpmn", "assign-approver-groups.dmn"})
  public void testHappyPath() {
    InputStream invoiceInputStream = InvoiceProcessApplication.class.getClassLoader().getResourceAsStream("invoice.pdf");
    VariableMap variables = Variables.createVariables()
      .putValue("creditor", "Great Pizza for Everyone Inc.")
      .putValue("amount", 300.0d)
      .putValue("invoiceCategory", "Travel Expenses")
      .putValue("invoiceNumber", "GPFE-23232323")
      .putValue("invoiceDocument", fileValue("invoice.pdf")
        .file(invoiceInputStream)
        .mimeType("application/pdf")
        .create());

    ProcessInstance pi = runtimeService.startProcessInstanceByKey("invoice", variables);

    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("approveInvoice", task.getTaskDefinitionKey());

    List<IdentityLink> links = taskService.getIdentityLinksForTask(task.getId());
    Set<String> approverGroups = new HashSet<String>();
    for (IdentityLink link : links) {
      approverGroups.add(link.getGroupId());
    }
    assertEquals(2, approverGroups.size());
    assertTrue(approverGroups.contains("accounting"));
    assertTrue(approverGroups.contains("sales"));

    variables.clear();
    variables.put("approved", Boolean.TRUE);
    taskService.complete(task.getId(), variables);

    task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();

    assertEquals("prepareBankTransfer", task.getTaskDefinitionKey());
    taskService.complete(task.getId());

    Job archiveInvoiceJob = managementService.createJobQuery().singleResult();
    assertNotNull(archiveInvoiceJob);
    managementService.executeJob(archiveInvoiceJob.getId());

    assertProcessEnded(pi.getId());
  }

  @Deployment(resources= {"invoice.bpmn", "assign-approver-groups.dmn"})
  public void testApproveInvoiceAssignment() {
    InputStream invoiceInputStream = InvoiceProcessApplication.class.getClassLoader().getResourceAsStream("invoice.pdf");

    VariableMap variables = Variables.createVariables()
      .putValue("creditor", "Great Pizza for Everyone Inc.")
      .putValue("amount", 300.0d)
      .putValue("invoiceCategory", "Travel Expenses")
      .putValue("invoiceNumber", "GPFE-23232323")
      .putValue("invoiceDocument", fileValue("invoice.pdf")
        .file(invoiceInputStream)
        .mimeType("application/pdf")
        .create())
      .putValue("approverGroups", Arrays.asList("sales", "accounting"));

    ProcessInstance pi = runtimeService.createProcessInstanceByKey("invoice")
      .setVariables(variables)
      .startBeforeActivity("approveInvoice")
      .execute();

    // givent that the process instance is waiting at task "approveInvoice"
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    assertEquals("approveInvoice", task.getTaskDefinitionKey());

    // and task has candidate groups
    List<IdentityLink> links = taskService.getIdentityLinksForTask(task.getId());
    Set<String> approverGroups = new HashSet<String>();
    for (IdentityLink link : links) {
      approverGroups.add(link.getGroupId());
    }
    assertEquals(2, approverGroups.size());
    assertTrue(approverGroups.contains("accounting"));
    assertTrue(approverGroups.contains("sales"));

    // and variable approver is null
    assertNull(taskService.getVariable(task.getId(), "approver"));

    // if mary claims the task
    taskService.claim(task.getId(), "mary");

    // then the variable "approver" exists and is set to mary
    assertEquals("mary", taskService.getVariable(task.getId(), "approver"));

  }

}


text:
import copy

from datetime import datetime
from django.core.management.color import no_style
from django.core.management.sql import sql_create, sql_delete, sql_indexes
from django.db import connection, transaction, settings, models
from django.db.backends.util import truncate_name
from django.db.models.loading import cache

from django_evolution import signature
from django_evolution.tests import models as evo_test
from django_evolution.utils import write_sql, execute_sql

from django.contrib.contenttypes import models as contenttypes

DEFAULT_TEST_ATTRIBUTE_VALUES = {
    models.CharField: 'TestCharField',
    models.IntegerField: '123',
    models.AutoField: None,
    models.DateTimeField: datetime.now(),
    models.PositiveIntegerField: '42'
}

def register_models(*models):
    app_cache = {}
    for name, model in models:
        if model._meta.module_name in cache.app_models['django_evolution']:
            del cache.app_models['django_evolution'][model._meta.module_name]

            if model._meta.db_table.startswith("%s_%s" % (model._meta.app_label,
                                                          model._meta.module_name)):
                model._meta.db_table = 'tests_%s' % name.lower()

            model._meta.app_label = 'tests'
            model._meta.object_name = name
            model._meta.module_name = name.lower()

            cache.app_models.setdefault('tests', {})[name.lower()] = model

        app_cache[name.lower()] = model

    return app_cache

def test_proj_sig(*models, **kwargs):
    "Generate a dummy project signature based around a single model"
    version = kwargs.get('version',1)
    proj_sig = {
        'tests': {},
        '__version__': version,
    }

    # Compute the project siguature
    for full_name,model in models:
        parts = full_name.split('.')
        if len(parts) == 1:
            name = parts[0]
            app = 'tests'
        else:
            app,name = parts
        proj_sig.setdefault(app,{})[name] = signature.create_model_sig(model)

    return proj_sig

def execute_transaction(sql, output=False):
    "A transaction wrapper for executing a list of SQL statements"
    try:
        # Begin Transaction
        transaction.enter_transaction_management()
        transaction.managed(True)
        cursor = connection.cursor()

        # Perform the SQL
        if output:
            write_sql(sql)
        execute_sql(cursor, sql)

        transaction.commit()
        transaction.leave_transaction_management()
    except Exception, ex:
        transaction.rollback()
        raise ex

def execute_test_sql(start, end, sql, debug=False):
    """
    Execute a test SQL sequence. This method also creates and destroys the
    database tables required by the models registered against the test application.

    start and end are the start- and end-point states of the application cache.

    sql is the list of sql statements to execute.

    cleanup is a list of extra sql statements required to clean up. This is
    primarily for any extra m2m tables that were added during a test that won't
    be cleaned up by Django's sql_delete() implementation.

    debug is a helper flag. It displays the ALL the SQL that would be executed,
    (including setup and teardown SQL), and executes the Django-derived setup/teardown
    SQL.
    """
    # Set up the initial state of the app cache
    cache.app_models['tests'] = copy.deepcopy(start)

    # Install the initial tables and indicies
    style = no_style()
    execute_transaction(sql_create(evo_test, style), output=debug)
    execute_transaction(sql_indexes(evo_test, style), output=debug)
    create_test_data(models.get_models(evo_test))

    # Set the app cache to the end state
    cache.app_models['tests'] = copy.deepcopy(end)

    try:
        # Execute the test sql
        if debug:
            write_sql(sql)
        else:
            execute_transaction(sql, output=True)
    finally:
        # Cleanup the apps.
        if debug:
            print sql_delete(evo_test, style)
        else:
            execute_transaction(sql_delete(evo_test, style), output=debug)

def create_test_data(app_models):
    deferred_models = []
    deferred_fields = {}
    for model in app_models:
        params = {}
        deferred = False
        for field in model._meta.fields:
            if not deferred:
                if type(field) == models.ForeignKey or type(field) == models.ManyToManyField:
                    related_model = field.rel.to
                    if related_model.objects.count():
                        related_instance = related_model.objects.all()[0]
                    else:
                        if field.null == False:
                            # Field cannot be null yet the related object hasn't been created yet
                            # Defer the creation of this model
                            deferred = True
                            deferred_models.append(model)
                        else:
                            # Field cannot be set yet but null is acceptable for the moment
                            deferred_fields[type(model)] = deferred_fields.get(type(model), []).append(field)
                            related_instance = None
                    if not deferred:
                        if type(field) == models.ForeignKey:
                            params[field.name] = related_instance
                        else:
                            params[field.name] = [related_instance]
                else:
                    params[field.name] = DEFAULT_TEST_ATTRIBUTE_VALUES[type(field)]

        if not deferred:
            model(**params).save()

    # Create all deferred models.
    if deferred_models:
        create_test_data(deferred_models)

    # All models should be created (Not all deferred fields have been populated yet)
    # Populate deferred fields that we know about.
    # Here lies untested code!
    if deferred_fields:
        for model, field_list in deferred_fields.items():
            for field in field_list:
                related_model = field.rel.to
                related_instance = related_model.objects.all()[0]
                if type(field) == models.ForeignKey:
                    setattr(model, field.name, related_instance)
                else:
                    getattr(model, field.name).add(related_instance)
            model.save()

def test_sql_mapping(test_field_name):
    engine = settings.DATABASE_ENGINE
    sql_for_engine = __import__('django_evolution.tests.db.%s' % (settings.DATABASE_ENGINE), {}, {}, [''])
    return getattr(sql_for_engine, test_field_name)

def deregister_models():
    "Clear the test section of the app cache"
    del cache.app_models['tests']


text:
var sass = require('node-sass'),
    fs = require('fs'),
    url = require('url'),
    dirname = require('path').dirname,
    mkdirp = require('mkdirp'),
    join = require('path').join;

var imports = {};

/**
 * Return Connect middleware with the given `options`.
 *
 * Options:
 *
 *    `force`       Always re-compile
 *    `debug`       Output debugging information
 *    `src`         Source directory used to find .scss files
 *    `dest`        Destination directory used to output .css files
 *                  when undefined defaults to `src`.
 *    `outputStyle` Sass output style (nested,expanded, compact or compressed)
 *    `response`    Always write output directly to response
 *
 * Examples:
 *
 * Pass the middleware to Connect, grabbing .scss files from this directory
 * and saving .css files to _./public_.
 *
 * Following that we have a `staticProvider` layer setup to serve the .css
 * files generated by Sass.
 *
 *      var server = connect.createServer(
 *          sass.middleware({
 *              src: __dirname
 *            , dest: __dirname + '/public'
 *          })
 *        , connect.static(__dirname + '/public')
 *      );
 *
 * @param {Object} options
 * @return {Function}
 * @api public
 */

module.exports = function(options){
  options = options || {};

  // Accept src/dest dir
  if ('string' == typeof options) {
    options = { src: options };
  }

  // Force compilation
  var force = options.force || options.response;

  // Debug option
  var debug = options.debug;

  // Source dir required
  var src = options.src;
  if (!src) { throw new Error('sass.middleware() requires "src" directory'); }

  // Default dest dir to source
  var dest = options.dest
    ? options.dest
    : src;

  var root = options.root || null;

  // Default compile callback
  options.compile = options.compile || function(){
    return sass;
  };

  // Middleware
  return function sass(req, res, next){
    if ('GET' != req.method && 'HEAD' != req.method) { return next(); }
    var path = url.parse(req.url).pathname;
    if (options.prefix && 0 === path.indexOf(options.prefix)) {
      path = path.substring(options.prefix.length);
    }
    if (/\.css$/.test(path)) {
      var cssPath = join(dest, path),
          sassPath = join(src, path.replace('.css', '.scss')),
          sassDir = dirname(sassPath);

      if (root) {
        cssPath = join(root, dest, path.replace(dest, ''));
        sassPath = join(root, src, path
            .replace(dest, '')
            .replace('.css', '.scss'));
        sassDir = dirname(sassPath);
      }

      if (debug) {
        log('source', sassPath);
        log('dest', options.response ? '<response>' : cssPath);
      }

      // Ignore ENOENT to fall through as 404
      var error = function(err) {
        next('ENOENT' == err.code
          ? null
          : err);
      };

      // Compile to cssPath
      var compile = function() {
        if (debug) { log('read', cssPath); }
        fs.readFile(sassPath, 'utf8', function(err, str){
          if (err) { return error(err); }
          var style = options.compile();
          var paths = [];
          delete imports[sassPath];
          style.render(str, function(err, css){
            if (err) { return next(err); }
            if (debug) { log('render', options.response ? '<response>' : sassPath); }
            imports[sassPath] = paths;

            // If response is falsey, also write to file
            if (!options.response) {
                mkdirp(dirname(cssPath), 0700, function(err){
                    if (err) return error(err);
                    fs.writeFile(cssPath, css, 'utf8', function(err) {
                        if (err) return error(err);
                    });
                });
            }

            res.writeHead(200, {
                'Content-Type': 'text/css',
                'Cache-Control': 'max-age=0'
            });
            res.end(css);

          }, {
            include_paths: [ sassDir ].concat(options.include_paths || options.includePaths || []),
            image_path: options.image_path || options.imagePath,
            output_style: options.output_style || options.outputStyle
          });
        });
      };

      // Force
      if (force) { return compile(); }

      // Re-compile on server restart, disregarding
      // mtimes since we need to map imports
      if (!imports[sassPath]) { return compile(); }

      // Compare mtimes
      fs.stat(sassPath, function(err, sassStats){
        if (err) { return error(err); }
        fs.stat(cssPath, function(err, cssStats){
          // CSS has not been compiled, compile it!
          if (err) {
            if ('ENOENT' == err.code) {
              if (debug) { log('not found', cssPath); }
              compile();
            } else {
              next(err);
            }
          } else {
            // Source has changed, compile it
            if (sassStats.mtime > cssStats.mtime) {
              if (debug) { log('modified', cssPath); }
              compile();
            // Already compiled, check imports
            } else {
              checkImports(sassPath, function(changed){
                if (debug && changed && changed.length) {
                  changed.forEach(function(path) {
                    log('modified import %s', path);
                  });
                }
                changed && changed.length ? compile() : next();
              });
            }
          }
        });
      });
    } else {
      next();
    }
  };
};

/**
 * Check `path`'s imports to see if they have been altered.
 *
 * @param {String} path
 * @param {Function} fn
 * @api private
 */

function checkImports(path, fn) {
  var nodes = imports[path];
  if (!nodes) { return fn(); }
  if (!nodes.length) { return fn(); }

  var pending = nodes.length,
      changed = [];

  nodes.forEach(function(imported){
    fs.stat(imported.path, function(err, stat){
      // error or newer mtime
      if (err || !imported.mtime || stat.mtime > imported.mtime) {
        changed.push(imported.path);
      }
      --pending || fn(changed);
    });
  });
}

/**
 * Log a message.
 *
 * @api private
 */

function log(key, val) {
  console.error('  \033[90m%s :\033[0m \033[36m%s\033[0m', key, val);
}