text:
// Code generated by transpiler. DO NOT EDIT.

/**
 * Go Video Downloader
 *
 *    Copyright 2019 Tenta, LLC
 *
 * 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.
 *
 * For any questions, please contact developer@tenta.io
 *
 * rtp/module.go: transpiled from https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/rtp.py
 */

package rtp

import (
	Ωcommon "github.com/tenta-browser/go-video-downloader/gen/youtube_dl/extractor/common"
	Ωutils "github.com/tenta-browser/go-video-downloader/gen/youtube_dl/utils"
	λ "github.com/tenta-browser/go-video-downloader/runtime"
)

var (
	InfoExtractor  λ.Object
	RTPIE          λ.Object
	ϒdetermine_ext λ.Object
	ϒjs_to_json    λ.Object
)

func init() {
	λ.InitModule(func() {
		InfoExtractor = Ωcommon.InfoExtractor
		ϒdetermine_ext = Ωutils.ϒdetermine_ext
		ϒjs_to_json = Ωutils.ϒjs_to_json
		RTPIE = λ.Cal(λ.TypeType, λ.NewStr("RTPIE"), λ.NewTuple(InfoExtractor), func() λ.Dict {
			var (
				RTPIE__VALID_URL    λ.Object
				RTPIE__real_extract λ.Object
			)
			RTPIE__VALID_URL = λ.NewStr("https?://(?:www\\.)?rtp\\.pt/play/p(?P<program_id>[0-9]+)/(?P<id>[^/?#]+)/?")
			RTPIE__real_extract = λ.NewFunction("_real_extract",
				[]λ.Param{
					{Name: "self"},
					{Name: "url"},
				},
				0, false, false,
				func(λargs []λ.Object) λ.Object {
					var (
						ϒconfig   λ.Object
						ϒext      λ.Object
						ϒf        λ.Object
						ϒfile_key λ.Object
						ϒfile_url λ.Object
						ϒformats  λ.Object
						ϒself     = λargs[0]
						ϒtitle    λ.Object
						ϒurl      = λargs[1]
						ϒvideo_id λ.Object
						ϒwebpage  λ.Object
						τmp0      λ.Object
						τmp1      λ.Object
					)
					ϒvideo_id = λ.Cal(λ.GetAttr(ϒself, "_match_id", nil), ϒurl)
					ϒwebpage = λ.Cal(λ.GetAttr(ϒself, "_download_webpage", nil), ϒurl, ϒvideo_id)
					ϒtitle = λ.Call(λ.GetAttr(ϒself, "_html_search_meta", nil), λ.NewArgs(
						λ.NewStr("twitter:title"),
						ϒwebpage,
					), λ.KWArgs{
						{Name: "display_name", Value: λ.NewStr("title")},
						{Name: "fatal", Value: λ.True},
					})
					ϒconfig = λ.Cal(λ.GetAttr(ϒself, "_parse_json", nil), λ.Cal(λ.GetAttr(ϒself, "_search_regex", nil), λ.NewStr("(?s)RTPPlayer\\(({.+?})\\);"), ϒwebpage, λ.NewStr("player config")), ϒvideo_id, ϒjs_to_json)
					ϒfile_url = λ.GetItem(ϒconfig, λ.NewStr("file"))
					ϒext = λ.Cal(ϒdetermine_ext, ϒfile_url)
					if λ.IsTrue(λ.Eq(ϒext, λ.NewStr("m3u8"))) {
						ϒfile_key = λ.Cal(λ.GetAttr(ϒconfig, "get", nil), λ.NewStr("fileKey"))
						ϒformats = λ.Call(λ.GetAttr(ϒself, "_extract_m3u8_formats", nil), λ.NewArgs(
							ϒfile_url,
							ϒvideo_id,
							λ.NewStr("mp4"),
							λ.NewStr("m3u8_native"),
						), λ.KWArgs{
							{Name: "m3u8_id", Value: λ.NewStr("hls")},
							{Name: "fatal", Value: ϒfile_key},
						})
						if λ.IsTrue(ϒfile_key) {
							λ.Cal(λ.GetAttr(ϒformats, "append", nil), λ.NewDictWithTable(map[λ.Object]λ.Object{
								λ.NewStr("url"):        λ.Add(λ.NewStr("https://cdn-ondemand.rtp.pt"), ϒfile_key),
								λ.NewStr("preference"): λ.NewInt(1),
							}))
						}
						λ.Cal(λ.GetAttr(ϒself, "_sort_formats", nil), ϒformats)
					} else {
						ϒformats = λ.NewList(λ.NewDictWithTable(map[λ.Object]λ.Object{
							λ.NewStr("url"): ϒfile_url,
							λ.NewStr("ext"): ϒext,
						}))
					}
					if λ.IsTrue(λ.Eq(λ.Cal(λ.GetAttr(ϒconfig, "get", nil), λ.NewStr("mediaType")), λ.NewStr("audio"))) {
						τmp0 = λ.Cal(λ.BuiltinIter, ϒformats)
						for {
							if τmp1 = λ.NextDefault(τmp0, λ.AfterLast); τmp1 == λ.AfterLast {
								break
							}
							ϒf = τmp1
							λ.SetItem(ϒf, λ.NewStr("vcodec"), λ.NewStr("none"))
						}
					}
					return λ.NewDictWithTable(map[λ.Object]λ.Object{
						λ.NewStr("id"):      ϒvideo_id,
						λ.NewStr("title"):   ϒtitle,
						λ.NewStr("formats"): ϒformats,
						λ.NewStr("description"): λ.Cal(λ.GetAttr(ϒself, "_html_search_meta", nil), λ.NewList(
							λ.NewStr("description"),
							λ.NewStr("twitter:description"),
						), ϒwebpage),
						λ.NewStr("thumbnail"): func() λ.Object {
							if λv := λ.Cal(λ.GetAttr(ϒconfig, "get", nil), λ.NewStr("poster")); λ.IsTrue(λv) {
								return λv
							} else {
								return λ.Cal(λ.GetAttr(ϒself, "_og_search_thumbnail", nil), ϒwebpage)
							}
						}(),
					})
				})
			return λ.NewDictWithTable(map[λ.Object]λ.Object{
				λ.NewStr("_VALID_URL"):    RTPIE__VALID_URL,
				λ.NewStr("_real_extract"): RTPIE__real_extract,
			})
		}())
	})
}

repository: cgpllx/go-video-downloader

repo_name: cgpllx/go-video-downloader


text:
SUMMARY = "Bletchley board type checker"
DESCRIPTION = "Bletchley board type checker to probe i2c device with correct driver in user-space"
PR = "r1"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/files/common-licenses/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

inherit allarch systemd obmc-phosphor-systemd

RDEPENDS:${PN} += " bash i2c-tools"

SRC_URI = " file://board-type-checker-fpb \
            file://board-type-checker-fpb.service \
          "

SYSTEMD_PACKAGES = "${PN}"
SYSTEMD_SERVICE:${PN}:append = " board-type-checker-fpb.service"

do_install() {
    install -d ${D}${libexecdir}
    install -m 0755 ${WORKDIR}/board-type-checker-fpb ${D}${libexecdir}/
}

repository: openbmc/openbmc

license_type: permissive

repo_name: openbmc/openbmc

branch_name: refs/heads/master

gha_license_id: NOASSERTION

gha_language: Python

extension: bb


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

package grope

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"github.com/aberic/gnomon"
	"github.com/aberic/gnomon/grope/tune"
	"github.com/golang/protobuf/proto"
	"github.com/vmihailenco/msgpack"
	"gopkg.in/yaml.v3"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
)

// Context grope 请求处理上下文
type Context struct {
	// writer 原生 net/http 结构
	writer http.ResponseWriter
	// request 原生 net/http 结构
	request *http.Request
	// sameSite 原生 net/http 结构, SameSite允许服务器定义cookie属性，使得浏览器不可能将此cookie与跨站点请求一起发送。
	sameSite http.SameSite
	// valueMap 如果需要，这里是与url请求中对应的参数集合，如“/demo/:id/”，则通过 valueMap[id] 获取url中的值
	valueMap map[string]string
	// paramMap 如果需要，这里是请求params
	paramMap map[string]string
	// responded 已经处理过
	responded bool
}

func (c *Context) requestHeader(key string) string {
	return c.request.Header.Get(key)
}

// Request 获取 *http.Request
func (c *Context) Request() *http.Request {
	return c.request
}

// HeaderSet 设置请求头中指定key的值
func (c *Context) HeaderSet(key, value string) {
	if value == "" {
		c.writer.Header().Del(key)
		return
	}
	c.writer.Header().Set(key, value)
}

// HeaderGet 返回请求头中指定key的值
func (c *Context) HeaderGet(key string) string {
	return c.requestHeader(key)
}

// SetSameSite with cookie
func (c *Context) SetSameSite(sameSite http.SameSite) {
	c.sameSite = sameSite
}

// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
// The provided cookie must have a valid Name. Invalid cookies may be
// silently dropped.
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
	if path == "" {
		path = "/"
	}
	http.SetCookie(c.writer, &http.Cookie{
		Name:     name,
		Value:    url.QueryEscape(value),
		MaxAge:   maxAge,
		Path:     path,
		Domain:   domain,
		SameSite: c.sameSite,
		Secure:   secure,
		HttpOnly: httpOnly,
	})
}

// Cookie returns the named cookie provided in the request or
// ErrNoCookie if not found. And return the named cookie is unescaped.
// If multiple cookies match the given name, only one cookie will
// be returned.
func (c *Context) Cookie(name string) (string, error) {
	cookie, err := c.request.Cookie(name)
	if err != nil {
		return "", err
	}
	val, _ := url.QueryUnescape(cookie.Value)
	return val, nil
}

// ClientIP 尝试获取客户端IP
func (c *Context) ClientIP() string {
	return gnomon.IPGet(c.request)
}

func filterFlags(content string) string {
	for i, char := range content {
		if char == ' ' || char == ';' {
			return content[:i]
		}
	}
	return content
}

// ContentType 返回请求的内容类型头
func (c *Context) ContentType() string {
	return filterFlags(c.requestHeader("Content-Type"))
}

// IsWebsocket 如果请求头指示客户端正在发起websocket握手，则IsWebsocket返回true
func (c *Context) IsWebsocket() bool {
	if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
		strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
		return true
	}
	return false
}

// Status 用提供的状态码发送一个HTTP响应头
func (c *Context) Status(code int) {
	c.writer.WriteHeader(code)
}

// Values 获取URI中自定义的参数集合
func (c *Context) Values() map[string]string {
	return c.valueMap
}

// Params 获取Params中自定义的参数集合
func (c *Context) Params() map[string]string {
	return c.paramMap
}

// Value 获取URI中自定义的参数集合中指定Key的值
func (c *Context) Value(key string) string {
	return c.valueMap[key]
}

// Param 获取Params中自定义的参数集合中指定Key的值
func (c *Context) Param(key string) string {
	return c.paramMap[key]
}

// ReceiveJSON 接收一个"application/json"请求
func (c *Context) ReceiveJSON(model interface{}) error {
	if err := tune.ParseJSON(c.request, model); nil != err {
		return err
	}
	return nil
}

// ReceiveXML 接收一个"application/xml"请求
func (c *Context) ReceiveXML(model interface{}) error {
	if err := tune.ParseXML(c.request, model); nil != err {
		return err
	}
	return nil
}

// ReceiveYaml 接收一个"application/x-yaml"请求
func (c *Context) ReceiveYaml(model interface{}) error {
	if err := tune.ParseYaml(c.request, model); nil != err {
		return err
	}
	return nil
}

// ReceiveMsgPack 接收一个"application/x-msgpack"请求
func (c *Context) ReceiveMsgPack(model interface{}) error {
	if err := tune.ParseMsgPack(c.request, model); nil != err {
		return err
	}
	return nil
}

// ReceiveProtoBuf 接收一个"application/x-protobuf"请求
func (c *Context) ReceiveProtoBuf(pm proto.Message) error {
	if err := tune.ParseProtoBuf(c.request, pm); nil != err {
		return err
	}
	return nil
}

// ReceiveForm 接收一个"application/x-www-form-urlencoded"请求
func (c *Context) ReceiveForm() (map[string]interface{}, error) {
	return tune.ParseForm(c.request)
}

// ReceiveMultipartForm 接收一个"multipart/form-data"请求
func (c *Context) ReceiveMultipartForm() (*tune.MultipartForm, error) {
	return tune.ParseMultipartForm(c.request)
}

// GetRawData 返回Body中流数据.
func (c *Context) GetRawData() ([]byte, error) {
	return ioutil.ReadAll(c.request.Body)
}

func (c *Context) response(bytes []byte) error {
	if _, err := c.writer.Write(bytes); nil != err {
		return err
	}
	return nil
}

// ResponseJSON 返回一个"application/json"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseJSON(statusCode int, model interface{}) error {
	if err := tune.ValidateStruct(model); nil != err {
		return err
	}
	c.responded = true
	c.HeaderSet("Content-Type", tune.ContentTypeJSON)
	c.Status(statusCode)
	bytes, err := json.Marshal(model)
	if nil != err {
		return err
	}
	return c.response(bytes)
}

// ResponseXML 返回一个"application/xml"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseXML(statusCode int, model interface{}) error {
	if err := tune.ValidateStruct(model); nil != err {
		return err
	}
	c.responded = true
	c.HeaderSet("Content-Type", tune.ContentTypeXML)
	c.Status(statusCode)
	bytes, err := xml.Marshal(model)
	if nil != err {
		return err
	}
	return c.response(bytes)
}

// ResponseYaml 返回一个"application/x-yaml"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseYaml(statusCode int, model interface{}) error {
	if err := tune.ValidateStruct(model); nil != err {
		return err
	}
	c.responded = true
	c.HeaderSet("Content-Type", tune.ContentTypeYaml)
	c.Status(statusCode)
	bytes, err := yaml.Marshal(model)
	if nil != err {
		return err
	}
	return c.response(bytes)
}

// ResponseMsgPack 返回一个"application/x-msgpack"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseMsgPack(statusCode int, model interface{}) error {
	if err := tune.ValidateStruct(model); nil != err {
		return err
	}
	c.responded = true
	c.HeaderSet("Content-Type", tune.ContentTypeMsgPack)
	c.Status(statusCode)
	bytes, err := msgpack.Marshal(model)
	if nil != err {
		return err
	}
	return c.response(bytes)
}

// ResponseProtoBuf 返回一个"application/x-protobuf"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseProtoBuf(statusCode int, pm proto.Message) error {
	c.responded = true
	c.HeaderSet("Content-Type", tune.ContentTypeProtoBuf)
	c.Status(statusCode)
	bytes, err := proto.Marshal(pm)
	if nil != err {
		return err
	}
	return c.response(bytes)
}

// ResponseText 返回一个"text/plain"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseText(statusCode int, text string) error {
	c.responded = true
	c.HeaderSet("Content-Type", tune.ContentTypePlain)
	c.Status(statusCode)
	return c.response([]byte(text))
}

// ResponseFile 返回一个"application/octet-stream"
//
// statusCode eg:http.StatusOK
func (c *Context) ResponseFile(statusCode int, filename, filepath string) error {
	var (
		file     *os.File
		fileInfo os.FileInfo
		err      error
	)
	c.responded = true
	if file, err = os.Open(filepath); nil != err {
		return err
	}
	defer func() { _ = file.Close() }()
	fileHeader := make([]byte, 512)
	if _, err = file.Read(fileHeader); nil != err {
		return err
	}
	if fileInfo, err = file.Stat(); nil != err {
		return err
	}
	c.HeaderSet("Content-Disposition", "attachment; filename="+filename)
	c.HeaderSet("Content-Type", http.DetectContentType(fileHeader))
	c.HeaderSet("Content-Length", strconv.FormatInt(fileInfo.Size(), 10))
	c.Status(statusCode)

	if _, err := file.Seek(0, 0); nil != err {
		return err
	}
	_, err = io.Copy(c.writer, file)
	return err
}

// Redirect 将http请求重定向到新的地址并写入重定向响应
func (c *Context) Redirect(statusCode int, addr string) error {
	if (statusCode < 300 || statusCode > 308) && statusCode != 201 {
		return fmt.Errorf("cannot redirect with status code %d", statusCode)
	}
	http.Redirect(c.writer, c.request, addr, statusCode)
	return nil
}

repository: aberic/gnomon

repo_name: aberic/gnomon

gha_language: Go

extension: go


text:
SUMMARY = "Python bindings and utilities for GeoJSON"
HOMEPAGE = "https://pypi.org/project/geojson/"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENSE.rst;md5=f48972abe5cddee79e301574742ed745"

SRC_URI[md5sum] = "14753ed28678828b1de73f68b04e2324"
SRC_URI[sha256sum] = "6e4bb7ace4226a45d9c8c8b1348b3fc43540658359f93c3f7e03efa9f15f658a"

inherit pypi setuptools3

RDEPENDS_${PN} += "python3-simplejson python3-math"

BBCLASSEXTEND = "native nativesdk"

gha_license_id: MIT


text:
package models

import "github.com/colinlet/mini_cloud/entity"

var Goods = &goodsModel{}

type goodsModel struct{}

func (*goodsModel) GetList(pageNum int, pageSize int, maps interface{}) (list []entity.Goods) {
	db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&list)
	return
}

func (*goodsModel) GetTotal(maps interface{}) (count int) {
	db.Model(&entity.Goods{}).Where(maps).Count(&count)
	return
}

func (*goodsModel) Get(maps interface{}) (data entity.Goods) {
	db.Where(maps).Find(&data)
	return
}

license: MIT

repository: colinlet/Mini-Cloud

repo_name: colinlet/Mini-Cloud


text:
#include "render-system.h"

RenderSystem::RenderSystem(entt::registry& registry) : ISystem(registry)
{
}

RenderSystem::~RenderSystem()
{
}

/////////////////////////////////////////////////////////////////////////////
////////////////////////////// PUBLIC METHODS ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////

void RenderSystem::update() {

}

repository: guillaume-haerinck/roll-goal

repo_name: guillaume-haerinck/roll-goal

extension: cpp


text:
package flux

import (
	"fmt"
	"net/http"
	"sort"
	"strings"
	"time"

	"github.com/pkg/errors"
)

const (
	ServiceSpecAll  = ServiceSpec("<all>")
	ImageSpecLatest = ImageSpec("<all latest>")
	ImageSpecNone   = ImageSpec("<no updates>")
	PolicyNone      = Policy("")
	PolicyLocked    = Policy("locked")
	PolicyAutomated = Policy("automated")
)

var (
	ErrInvalidServiceID   = errors.New("invalid service ID")
	ErrInvalidReleaseKind = errors.New("invalid release kind")
)

type Token string

func (t Token) Set(req *http.Request) {
	if string(t) != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Scope-Probe token=%s", t))
	}
}

type InstanceID string

const InstanceIDHeaderKey = "X-Scope-OrgID"

const DefaultInstanceID = "<default-instance-id>"

type ServiceID string // "default/helloworld"

func (id ServiceID) String() string {
	return string(id)
}

func ParseServiceID(s string) (ServiceID, error) {
	toks := strings.SplitN(s, "/", 2)
	if len(toks) != 2 {
		return "", ErrInvalidServiceID
	}
	return ServiceID(s), nil
}

func MakeServiceID(namespace, service string) ServiceID {
	return ServiceID(namespace + "/" + service)
}

func (id ServiceID) Components() (namespace, service string) {
	toks := strings.SplitN(string(id), "/", 2)
	if len(toks) != 2 {
		panic("invalid service spec")
	}
	return toks[0], toks[1]
}

type ServiceIDSet map[ServiceID]struct{}

func (s ServiceIDSet) String() string {
	var ids []string
	for id, _ := range s {
		ids = append(ids, string(id))
	}
	return "{" + strings.Join(ids, ", ") + "}"
}

func (s ServiceIDSet) Add(ids []ServiceID) {
	for _, id := range ids {
		s[id] = struct{}{}
	}
}

func (s ServiceIDSet) Without(others ServiceIDSet) ServiceIDSet {
	if s == nil || len(s) == 0 || others == nil || len(others) == 0 {
		return s
	}
	res := ServiceIDSet{}
	for id := range s {
		if !others.Contains(id) {
			res[id] = struct{}{}
		}
	}
	return res
}

func (s ServiceIDSet) Contains(id ServiceID) bool {
	if s == nil {
		return false
	}
	_, ok := s[id]
	return ok
}

func (s ServiceIDSet) Intersection(others ServiceIDSet) ServiceIDSet {
	if s == nil {
		return others
	}
	if others == nil {
		return s
	}
	result := ServiceIDSet{}
	for id := range s {
		if _, ok := others[id]; ok {
			result[id] = struct{}{}
		}
	}
	return result
}

type ServiceIDs []ServiceID

func (p ServiceIDs) Len() int           { return len(p) }
func (p ServiceIDs) Less(i, j int) bool { return string(p[i]) < string(p[j]) }
func (p ServiceIDs) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p ServiceIDs) Sort()              { sort.Sort(p) }

func (ids ServiceIDs) Without(others ServiceIDSet) (res ServiceIDs) {
	for _, id := range ids {
		if !others.Contains(id) {
			res = append(res, id)
		}
	}
	return res
}

func (ids ServiceIDs) Contains(id ServiceID) bool {
	set := ServiceIDSet{}
	set.Add(ids)
	return set.Contains(id)
}

func (ids ServiceIDs) Intersection(others ServiceIDSet) ServiceIDSet {
	set := ServiceIDSet{}
	set.Add(ids)
	return set.Intersection(others)
}

type ServiceSpec string // ServiceID or "<all>"

func ParseServiceSpec(s string) (ServiceSpec, error) {
	if s == string(ServiceSpecAll) {
		return ServiceSpecAll, nil
	}
	id, err := ParseServiceID(s)
	if err != nil {
		return "", errors.Wrap(err, "invalid service spec")
	}
	return ServiceSpec(id), nil
}

func (s ServiceSpec) AsID() (ServiceID, error) {
	return ParseServiceID(string(s))
}

func (s ServiceSpec) String() string {
	return string(s)
}

// ImageSpec is an ImageID, or "<all latest>" (update all containers
// to the latest available), or "<no updates>" (do not update any
// images)
type ImageSpec string

func ParseImageSpec(s string) (ImageSpec, error) {
	if s == string(ImageSpecLatest) || s == string(ImageSpecNone) {
		return ImageSpec(s), nil
	}

	parts := strings.Split(s, ":")
	if len(parts) != 2 || parts[1] == "" {
		return "", errors.Wrap(ErrInvalidImageID, "blank tag (if you want latest, explicitly state the tag :latest)")
	}

	id, err := ParseImageID(s)
	return ImageSpec(id.String()), err
}

func (s ImageSpec) String() string {
	return string(s)
}

func (s ImageSpec) AsID() (ImageID, error) {
	return ParseImageID(s.String())
}

func ImageSpecFromID(id ImageID) ImageSpec {
	return ImageSpec(id.String())
}

type ImageStatus struct {
	ID         ServiceID
	Containers []Container
}

// Policy is an string, denoting the current deployment policy of a service,
// e.g. automated, or locked.
type Policy string

func ParsePolicy(s string) Policy {
	for _, p := range []Policy{
		PolicyLocked,
		PolicyAutomated,
	} {
		if s == string(p) {
			return p
		}
	}
	return PolicyNone
}

type ServiceStatus struct {
	ID         ServiceID
	Containers []Container
	Status     string
	Automated  bool
	Locked     bool
}

func (s ServiceStatus) Policies() string {
	var ps []string
	if s.Automated {
		ps = append(ps, string(PolicyAutomated))
	}
	if s.Locked {
		ps = append(ps, string(PolicyLocked))
	}
	sort.Strings(ps)
	return strings.Join(ps, ",")
}

type Container struct {
	Name      string
	Current   ImageDescription
	Available []ImageDescription
}

type ImageDescription struct {
	ID        ImageID
	CreatedAt *time.Time `json:",omitempty"`
}

// Ask me for more details.
type HistoryEntry struct {
	Stamp *time.Time `json:",omitempty"`
	Type  string
	Data  string
	Event Event
}

// TODO: How similar should this be to the `get-config` result?
type Status struct {
	Fluxsvc FluxsvcStatus `json:"fluxsvc" yaml:"fluxsvc"`
	Fluxd   FluxdStatus   `json:"fluxd" yaml:"fluxd"`
	Git     GitStatus     `json:"git" yaml:"git"`
}

type FluxsvcStatus struct {
	Version string `json:"version,omitempty" yaml:"version,omitempty"`
}

type FluxdStatus struct {
	Connected bool   `json:"connected" yaml:"connected"`
	Version   string `json:"version,omitempty" yaml:"version,omitempty"`
}

type GitStatus struct {
	Configured bool   `json:"configured" yaml:"configured"`
	Error      string `json:"error,omitempty" yaml:"error,omitempty"`
}

repository: lukemarsden/flux

repo_name: lukemarsden/flux


text:
package model

// Choice between an amount or number of units or percentage.
type UnitsOrAmountOrPercentage1Choice struct {

	// Cash amount.
	Amount *ActiveCurrencyAndAmount `xml:"Amt"`

	// Number of units.
	Unit *DecimalNumber `xml:"Unit"`

	// Percentage of cash amount.
	Percentage *PercentageRate `xml:"Pctg"`
}

func (u *UnitsOrAmountOrPercentage1Choice) SetAmount(value, currency string) {
	u.Amount = NewActiveCurrencyAndAmount(value, currency)
}

func (u *UnitsOrAmountOrPercentage1Choice) SetUnit(value string) {
	u.Unit = (*DecimalNumber)(&value)
}

func (u *UnitsOrAmountOrPercentage1Choice) SetPercentage(value string) {
	u.Percentage = (*PercentageRate)(&value)
}


text:
require dpkg.inc
PR = "r5"
DEPENDS += "zlib bzip2"
SRC_URI += "file://noman.patch;patch=1"

EXTRA_OECONF = "--without-static-progs \
		--without-dselect \
		--with-start-stop-daemon \
		--with-zlib \
		--with-bz2lib \
		--without-sgml-doc \
		PERL=/usr/bin/perl"


text:
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***

package v1

import (
	"context"
	"reflect"

	metav1 "github.com/pulumi/pulumi-kubernetes/sdk/v2/go/kubernetes/meta/v1"
	"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)

// QiskitPlayground is the Schema for the qiskitplaygrounds API
type QiskitPlaygroundType struct {
	ApiVersion *string            `pulumi:"apiVersion"`
	Kind       *string            `pulumi:"kind"`
	Metadata   *metav1.ObjectMeta `pulumi:"metadata"`
	// QiskitPlaygroundSpec defines the desired state of QiskitPlayground
	Spec map[string]interface{} `pulumi:"spec"`
	// QiskitPlaygroundStatus defines the observed state of QiskitPlayground
	Status map[string]interface{} `pulumi:"status"`
}

// QiskitPlaygroundTypeInput is an input type that accepts QiskitPlaygroundTypeArgs and QiskitPlaygroundTypeOutput values.
// You can construct a concrete instance of `QiskitPlaygroundTypeInput` via:
//
//          QiskitPlaygroundTypeArgs{...}
type QiskitPlaygroundTypeInput interface {
	pulumi.Input

	ToQiskitPlaygroundTypeOutput() QiskitPlaygroundTypeOutput
	ToQiskitPlaygroundTypeOutputWithContext(context.Context) QiskitPlaygroundTypeOutput
}

// QiskitPlayground is the Schema for the qiskitplaygrounds API
type QiskitPlaygroundTypeArgs struct {
	ApiVersion pulumi.StringPtrInput     `pulumi:"apiVersion"`
	Kind       pulumi.StringPtrInput     `pulumi:"kind"`
	Metadata   metav1.ObjectMetaPtrInput `pulumi:"metadata"`
	// QiskitPlaygroundSpec defines the desired state of QiskitPlayground
	Spec pulumi.MapInput `pulumi:"spec"`
	// QiskitPlaygroundStatus defines the observed state of QiskitPlayground
	Status pulumi.MapInput `pulumi:"status"`
}

func (QiskitPlaygroundTypeArgs) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundType)(nil)).Elem()
}

func (i QiskitPlaygroundTypeArgs) ToQiskitPlaygroundTypeOutput() QiskitPlaygroundTypeOutput {
	return i.ToQiskitPlaygroundTypeOutputWithContext(context.Background())
}

func (i QiskitPlaygroundTypeArgs) ToQiskitPlaygroundTypeOutputWithContext(ctx context.Context) QiskitPlaygroundTypeOutput {
	return pulumi.ToOutputWithContext(ctx, i).(QiskitPlaygroundTypeOutput)
}

// QiskitPlayground is the Schema for the qiskitplaygrounds API
type QiskitPlaygroundTypeOutput struct{ *pulumi.OutputState }

func (QiskitPlaygroundTypeOutput) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundType)(nil)).Elem()
}

func (o QiskitPlaygroundTypeOutput) ToQiskitPlaygroundTypeOutput() QiskitPlaygroundTypeOutput {
	return o
}

func (o QiskitPlaygroundTypeOutput) ToQiskitPlaygroundTypeOutputWithContext(ctx context.Context) QiskitPlaygroundTypeOutput {
	return o
}

func (o QiskitPlaygroundTypeOutput) ApiVersion() pulumi.StringPtrOutput {
	return o.ApplyT(func(v QiskitPlaygroundType) *string { return v.ApiVersion }).(pulumi.StringPtrOutput)
}

func (o QiskitPlaygroundTypeOutput) Kind() pulumi.StringPtrOutput {
	return o.ApplyT(func(v QiskitPlaygroundType) *string { return v.Kind }).(pulumi.StringPtrOutput)
}

func (o QiskitPlaygroundTypeOutput) Metadata() metav1.ObjectMetaPtrOutput {
	return o.ApplyT(func(v QiskitPlaygroundType) *metav1.ObjectMeta { return v.Metadata }).(metav1.ObjectMetaPtrOutput)
}

// QiskitPlaygroundSpec defines the desired state of QiskitPlayground
func (o QiskitPlaygroundTypeOutput) Spec() pulumi.MapOutput {
	return o.ApplyT(func(v QiskitPlaygroundType) map[string]interface{} { return v.Spec }).(pulumi.MapOutput)
}

// QiskitPlaygroundStatus defines the observed state of QiskitPlayground
func (o QiskitPlaygroundTypeOutput) Status() pulumi.MapOutput {
	return o.ApplyT(func(v QiskitPlaygroundType) map[string]interface{} { return v.Status }).(pulumi.MapOutput)
}

type QiskitPlaygroundMetadata struct {
}

// QiskitPlaygroundMetadataInput is an input type that accepts QiskitPlaygroundMetadataArgs and QiskitPlaygroundMetadataOutput values.
// You can construct a concrete instance of `QiskitPlaygroundMetadataInput` via:
//
//          QiskitPlaygroundMetadataArgs{...}
type QiskitPlaygroundMetadataInput interface {
	pulumi.Input

	ToQiskitPlaygroundMetadataOutput() QiskitPlaygroundMetadataOutput
	ToQiskitPlaygroundMetadataOutputWithContext(context.Context) QiskitPlaygroundMetadataOutput
}

type QiskitPlaygroundMetadataArgs struct {
}

func (QiskitPlaygroundMetadataArgs) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundMetadata)(nil)).Elem()
}

func (i QiskitPlaygroundMetadataArgs) ToQiskitPlaygroundMetadataOutput() QiskitPlaygroundMetadataOutput {
	return i.ToQiskitPlaygroundMetadataOutputWithContext(context.Background())
}

func (i QiskitPlaygroundMetadataArgs) ToQiskitPlaygroundMetadataOutputWithContext(ctx context.Context) QiskitPlaygroundMetadataOutput {
	return pulumi.ToOutputWithContext(ctx, i).(QiskitPlaygroundMetadataOutput)
}

type QiskitPlaygroundMetadataOutput struct{ *pulumi.OutputState }

func (QiskitPlaygroundMetadataOutput) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundMetadata)(nil)).Elem()
}

func (o QiskitPlaygroundMetadataOutput) ToQiskitPlaygroundMetadataOutput() QiskitPlaygroundMetadataOutput {
	return o
}

func (o QiskitPlaygroundMetadataOutput) ToQiskitPlaygroundMetadataOutputWithContext(ctx context.Context) QiskitPlaygroundMetadataOutput {
	return o
}

// QiskitPlaygroundSpec defines the desired state of QiskitPlayground
type QiskitPlaygroundSpec struct {
}

// QiskitPlaygroundSpecInput is an input type that accepts QiskitPlaygroundSpecArgs and QiskitPlaygroundSpecOutput values.
// You can construct a concrete instance of `QiskitPlaygroundSpecInput` via:
//
//          QiskitPlaygroundSpecArgs{...}
type QiskitPlaygroundSpecInput interface {
	pulumi.Input

	ToQiskitPlaygroundSpecOutput() QiskitPlaygroundSpecOutput
	ToQiskitPlaygroundSpecOutputWithContext(context.Context) QiskitPlaygroundSpecOutput
}

// QiskitPlaygroundSpec defines the desired state of QiskitPlayground
type QiskitPlaygroundSpecArgs struct {
}

func (QiskitPlaygroundSpecArgs) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundSpec)(nil)).Elem()
}

func (i QiskitPlaygroundSpecArgs) ToQiskitPlaygroundSpecOutput() QiskitPlaygroundSpecOutput {
	return i.ToQiskitPlaygroundSpecOutputWithContext(context.Background())
}

func (i QiskitPlaygroundSpecArgs) ToQiskitPlaygroundSpecOutputWithContext(ctx context.Context) QiskitPlaygroundSpecOutput {
	return pulumi.ToOutputWithContext(ctx, i).(QiskitPlaygroundSpecOutput)
}

// QiskitPlaygroundSpec defines the desired state of QiskitPlayground
type QiskitPlaygroundSpecOutput struct{ *pulumi.OutputState }

func (QiskitPlaygroundSpecOutput) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundSpec)(nil)).Elem()
}

func (o QiskitPlaygroundSpecOutput) ToQiskitPlaygroundSpecOutput() QiskitPlaygroundSpecOutput {
	return o
}

func (o QiskitPlaygroundSpecOutput) ToQiskitPlaygroundSpecOutputWithContext(ctx context.Context) QiskitPlaygroundSpecOutput {
	return o
}

// QiskitPlaygroundStatus defines the observed state of QiskitPlayground
type QiskitPlaygroundStatus struct {
}

// QiskitPlaygroundStatusInput is an input type that accepts QiskitPlaygroundStatusArgs and QiskitPlaygroundStatusOutput values.
// You can construct a concrete instance of `QiskitPlaygroundStatusInput` via:
//
//          QiskitPlaygroundStatusArgs{...}
type QiskitPlaygroundStatusInput interface {
	pulumi.Input

	ToQiskitPlaygroundStatusOutput() QiskitPlaygroundStatusOutput
	ToQiskitPlaygroundStatusOutputWithContext(context.Context) QiskitPlaygroundStatusOutput
}

// QiskitPlaygroundStatus defines the observed state of QiskitPlayground
type QiskitPlaygroundStatusArgs struct {
}

func (QiskitPlaygroundStatusArgs) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundStatus)(nil)).Elem()
}

func (i QiskitPlaygroundStatusArgs) ToQiskitPlaygroundStatusOutput() QiskitPlaygroundStatusOutput {
	return i.ToQiskitPlaygroundStatusOutputWithContext(context.Background())
}

func (i QiskitPlaygroundStatusArgs) ToQiskitPlaygroundStatusOutputWithContext(ctx context.Context) QiskitPlaygroundStatusOutput {
	return pulumi.ToOutputWithContext(ctx, i).(QiskitPlaygroundStatusOutput)
}

// QiskitPlaygroundStatus defines the observed state of QiskitPlayground
type QiskitPlaygroundStatusOutput struct{ *pulumi.OutputState }

func (QiskitPlaygroundStatusOutput) ElementType() reflect.Type {
	return reflect.TypeOf((*QiskitPlaygroundStatus)(nil)).Elem()
}

func (o QiskitPlaygroundStatusOutput) ToQiskitPlaygroundStatusOutput() QiskitPlaygroundStatusOutput {
	return o
}

func (o QiskitPlaygroundStatusOutput) ToQiskitPlaygroundStatusOutputWithContext(ctx context.Context) QiskitPlaygroundStatusOutput {
	return o
}

func init() {
	pulumi.RegisterOutputType(QiskitPlaygroundTypeOutput{})
	pulumi.RegisterOutputType(QiskitPlaygroundMetadataOutput{})
	pulumi.RegisterOutputType(QiskitPlaygroundSpecOutput{})
	pulumi.RegisterOutputType(QiskitPlaygroundStatusOutput{})
}


text:
package mario

var res = make([][]int, 0)
var temp = make([]int, 0)

func combinationSum3(k int, n int) [][]int {
	// for lc
	{
		res = make([][]int, 0)
		temp = make([]int, 0)
	}

	if !hasSolution(n, k) {
		return res
	}

	dfs(0, k, n)

	return res
}

func hasSolution(n, k int) bool {
	max, min := 0, 0
	for i := 1; i <= k; i++ {
		min += i
	}
	for i := 9; i > 9-k; i-- {
		max += i
	}

	return min <= n && n <= max
}

func dfs(used, k, n int) {
	if k == 0 {
		if n == 0 {
			res = append(res, append(make([]int, 0), temp...))
		}
		return
	}

	for i := used + 1; i <= 9; i++ {
		temp = append(temp, i)
		dfs(i, k-1, n-i)
		temp = temp[:len(temp)-1]
	}

	return
}

license: Unlicense


text:
SUMMARY = "Client for PPP+SSL VPN tunnel services"
LICENSE = "GPL-3.0-or-later"
LIC_FILES_CHKSUM = "file://LICENSE;md5=3d575262a651a6f1a17210ce41bf907d"

SRC_URI = "git://github.com/adrienverge/openfortivpn.git;protocol=https;branch=master"
SRCREV = "1ccb8ee682af255ae85fecd5fcbab6497ccb6b38"

DEPENDS = "openssl"

PACKAGECONFIG ??= "${@bb.utils.filter('DISTRO_FEATURES', 'systemd', d)}"

PACKAGECONFIG[resolvconf] = "--with-resolvconf=${base_sbindir}/resolvconf --enable-resolvconf,--with-resolvconf=DISABLED,,"
PACKAGECONFIG[systemd] = "--with-systemdsystemunitdir=${systemd_system_unitdir},--without-systemdsystemunitdir,,"

S = "${WORKDIR}/git"

inherit autotools pkgconfig systemd

EXTRA_OECONF = " \
    --with-pppd=${sbindir}/pppd \
    --disable-proc \
"

SYSTEMD_SERVICE:${PN} = "openfortivpn@.service"

RDEPENDS:${PN} = "ppp"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake


text:
package watcher

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/fsnotify/fsnotify"
)

// A Watcher watches a directory for changes and waits a delay until triggering an output event.
type Watcher struct {
	ctx      context.Context
	log      *logrus.Entry
	inputDir string
	delay    time.Duration
	watcher  *fsnotify.Watcher
	timer    *time.Timer

	Trigger chan struct{}
}

// New creates a new filesystem watcher. Need to call Start() to actually start watching.
func New(ctx context.Context, logger *logrus.Logger, inputDir string, delay time.Duration) (*Watcher, error) {
	watch, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, fmt.Errorf("error creating watcher: %s", err)
	}

	if err := watch.Add(inputDir); err != nil {
		return nil, fmt.Errorf("error adding watch for input: %s", err)
	}

	return &Watcher{
		ctx:      ctx,
		log:      logger.WithField("component", "watcher"),
		inputDir: inputDir,
		delay:    delay,
		watcher:  watch,
		timer:    time.NewTimer(delay),
		Trigger:  make(chan struct{}),
	}, nil
}

func (w *Watcher) resetTimer() {
	if !w.timer.Stop() {
		<-w.timer.C
	}
	w.timer.Reset(w.delay)
}

// Start starts the background routine which watches for filesystem events.
// The waitgroup is used for tracking the shutdown.
func (w *Watcher) Start(wg *sync.WaitGroup) {
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			select {
			case <-w.ctx.Done():
				w.log.Info("Stopping.")
				if err := w.watcher.Close(); err != nil {
					w.log.Errorf("Error closing watcher: %s", err)
				}
				return
			case <-w.watcher.Events:
				w.timer.Reset(w.delay)
			case <-w.timer.C:
				w.Trigger <- struct{}{}
			}
		}
	}()
}

repository: xperimental/autoocr

repo_name: xperimental/autoocr


text:
/**
 * \file shuffler.cpp
 * \brief Shuffler class implementation.
 */

#include <algorithm>
#include <cmath>
#include <sstream>

#include "curl.h"
#include "wa_ipc.h"
#include "nde/NDE.h"

#include "gen_museek.h"
#include "logger.h"
#include "shuffler.h"
#include "track.h"
#include "utils.h"

using namespace std;

Shuffler* Shuffler::instance = NULL;

// Extern variables
extern winampGeneralPurposePlugin   plugin;
extern DWORD                        WA_MENUITEM_SHUFFLE_ON_LIBRARY;
extern DWORD                        WA_MENUITEM_SHUFFLE_ON_PLAYLIST;
extern DWORD                        WA_MENUITEM_RESCAN_LIBRARY;

/// \brief Default constructor.
Shuffler::Shuffler() :
        configDirectory(),
        playingTrack(NULL),
        localNextTrack(NULL),
        remoteNextTrack(NULL),
        remoteScale(pow(5, 1./16.)),
        remoteConstant(0.3),
        remoteBound(sqrt(32.)/2.),
        remoteRadius(0),
        paused(false),
        playlistLength(0),
        playlistPosition(0),
        winampVersion(0),
        mode(OFF),
        menu_item_position_file(0),
        menu_item_position_option(0),
		startTime(0),
		endTime(0),
		pauseStartTime(0),
		pauseEndTime(0),
        libraryScan(this),
        mapLoad(this),
        nextTrackPreparation(this) {
    		map = Map::getInstance();
    		map->setParent(this); // KLUDGE

    		// Initialize curl
    		curl_global_init(CURL_GLOBAL_WIN32);
}

/// \brief Destructor.
Shuffler::~Shuffler() {

    curl_global_cleanup();
}

/// \return Unique instance of Shuffler class.
Shuffler* Shuffler::getInstance() {
    if (instance == NULL)
        instance = new Shuffler;

    return instance;
}

/// \brief Delete the unique instance of Shuffler class.
void Shuffler::kill() {
    if (instance != NULL) {
        delete instance;
        instance = NULL;
    }
}

/**
 * \brief Compute squared distance between 2 tracks of the map.
 *
 * \param track1 First track.
 * \param track2 Second track.
 * \return Squared distance between given tracks.
 */
ANNdist Shuffler::distanceBetween(const Track* track1, const Track* track2) {
    Map* map(Map::getInstance());

    ANNpoint
        point1(map->getPoint(track1->getId())),
        point2(map->getPoint(track2->getId()));

    return sqrt(annDist(map->getDimensions(), point1, point2));
}

/// \return The directory where the plugin is allowed to write config files.
string Shuffler::getConfigDirectory() {
    if (configDirectory.empty()) {
        if (!checkWinampVersion(0x2900))    exit(1);    // TODO: exit with an error

        //  Find path to config directory
        string path((char*)SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_GETINIDIRECTORY));

        path = path + "\\Plugins\\";
        configDirectory = path;
    }

    return configDirectory;
}

/// \return
/*WNDPROC Shuffler::getLpWndProcOld() const {
    return lpWndProcOld;
}*/

///
int Shuffler::getListLength() {
    if (!checkWinampVersion(0x2000))    exit(1); // TODO: exit with an error
    return SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_GETLISTLENGTH);
}

///
int Shuffler::getListPosition() {
    if (!checkWinampVersion(0x2050))    exit(1); // TODO: exit with an error
    return SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_GETLISTPOS);
}

///
const Track* Shuffler::getLocalNextTrack() const {
    return localNextTrack;
}

///
const Track* Shuffler::getRemoteNextTrack() const {
    return remoteNextTrack;
}

///
Track* Shuffler::getPlayingTrack() const {
    Map* map(Map::getInstance());
    return map->getTrack(playingTrack->getId());
}

///
bool Shuffler::databaseAvailable() {
    // Winamp is in "offline" mode
    if (checkWinampVersion(0x2050) && !SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_INETAVAILABLE))
        return false;

    // TODO: test connection to database
    return true;
}

/// \return True if a track is being played (even if paused), false otherwise.
bool Shuffler::isPlaying() const {
    if (SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_ISPLAYING))
        return true;

    return false;
}

void Shuffler::setListPosition(unsigned int newPosition) {
    if (!checkWinampVersion(0x2000))    exit(1);
    SendMessage(plugin.hwndParent, WM_WA_IPC, newPosition, IPC_SETPLAYLISTPOS);
}

///
void Shuffler::appendToPlaylist(const Track* track) {
    enqueueFileWithMetaStruct nextItem = {0};
    Map* map(Map::getInstance());

    // Don't know why, but using path.c_str() doesn't work...
    string path = track->getPath();
    char*  path_ = new char[path.size() + 1];
    strcpy(path_, path.c_str());

    nextItem.filename  = path_;
    nextItem.length    = 0;     // 0 = we don't know (Winamp doesn't care)
    /*if (!map->getTrack(i)->getTitle().empty())
        nextItem.title = map->getTrack(i)->getTitle().c_str();*/
    nextItem.title = "Random"; // TODO: improve this (although this might never appear)

    if (!checkWinampVersion(0x2900))    exit(1);
    SendMessage(plugin.hwndParent, WM_WA_IPC, (WPARAM)&nextItem, IPC_ENQUEUEFILE);
}

///
bool Shuffler::checkWinampVersion(int version) {
    if (!winampVersion)
	    winampVersion = SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_GETVERSION);

    if (version > winampVersion)    return false;
    return true;
}

///
void Shuffler::createMenuEntries() {
    // TODO: add an entry to trigger a library scan
    if (!checkWinampVersion(0x2900))    return;     // TODO: exit with an error

    windowsMenu = (HMENU)SendMessage(plugin.hwndParent, WM_WA_IPC, (WPARAM)2, IPC_GET_HMENU);
	altMenu     = (HMENU)SendMessage(plugin.hwndParent, WM_WA_IPC, (WPARAM)0, IPC_GET_HMENU);

    if (windowsMenu) {
        WA_MENUITEM_SHUFFLE_ON_LIBRARY  = SendMessage(plugin.hwndParent, WM_WA_IPC, (WPARAM)&"museek_database", IPC_REGISTER_WINAMP_IPCMESSAGE);
		WA_MENUITEM_SHUFFLE_ON_PLAYLIST = SendMessage(plugin.hwndParent, WM_WA_IPC, (WPARAM)&"museek_playlist", IPC_REGISTER_WINAMP_IPCMESSAGE);
        WA_MENUITEM_RESCAN_LIBRARY      = SendMessage(plugin.hwndParent, WM_WA_IPC, (WPARAM)&"museek_rescan", IPC_REGISTER_WINAMP_IPCMESSAGE);

		int c = 0;
		while (c < GetMenuItemCount(windowsMenu)) {
			if (GetMenuItemID(windowsMenu, c) == 40023) // TODO: use a constant here !
				menu_item_position_file = c + 1;

			c++;
		}

		menu_item_position_option = 1;

        // Entry "Smart shuffle on whole library"
		MENUITEMINFO i = {sizeof(i), MIIM_ID | MIIM_STATE | MIIM_TYPE, MFT_STRING, 0, WA_MENUITEM_SHUFFLE_ON_LIBRARY};
		i.dwTypeData = L"Smart shuffle"; // TODO: use gettext
		InsertMenuItem(windowsMenu, menu_item_position_file, TRUE, &i);
		InsertMenuItem(altMenu, menu_item_position_option, TRUE, &i);

        // TODO: first implement smart shuffle on current playlist
        // Entry "Smart shuffle on current playlist"
		/*MENUITEMINFO j = {sizeof(j), MIIM_ID | MIIM_STATE | MIIM_TYPE, MFT_STRING, 0, WA_MENUITEM_SHUFFLE_ON_PLAYLIST};
		j.dwTypeData = L"Smart shuffle on current playlist";
		InsertMenuItem(windowsMenu, (menu_item_position_file + 1), TRUE, &j);
		InsertMenuItem(altMenu, (menu_item_position_option + 1), TRUE, &j);*/

        // Entry "Rescan library"
        MENUITEMINFO k = {sizeof(i), MIIM_ID | MIIM_STATE | MIIM_TYPE, MFT_STRING, 0, WA_MENUITEM_RESCAN_LIBRARY};
		k.dwTypeData = L"Rescan library for smart shuffle";
		InsertMenuItem(windowsMenu, menu_item_position_file + 1, TRUE, &k);
		InsertMenuItem(altMenu, menu_item_position_option + 1, TRUE, &k);

        // Disable menu items until map has been loaded
        disable();
	}
}

/**
 * \brief Stop smart shuffler and disable menu entries.
 * \return Nothing.
 */
void Shuffler::disable() {
    mode = OFF;

    EnableMenuItem(windowsMenu, WA_MENUITEM_SHUFFLE_ON_LIBRARY, MF_GRAYED);
    EnableMenuItem(altMenu,     WA_MENUITEM_SHUFFLE_ON_LIBRARY, MF_GRAYED);
    EnableMenuItem(windowsMenu, WA_MENUITEM_RESCAN_LIBRARY,     MF_GRAYED);
    EnableMenuItem(altMenu,     WA_MENUITEM_RESCAN_LIBRARY,     MF_GRAYED);
}

/**
 * \brief Enable menu entries.
 * \return Nothing.
 */
void Shuffler::enable() {
    EnableMenuItem(windowsMenu, WA_MENUITEM_SHUFFLE_ON_LIBRARY, MF_ENABLED);
    EnableMenuItem(altMenu,     WA_MENUITEM_SHUFFLE_ON_LIBRARY, MF_ENABLED);
    EnableMenuItem(windowsMenu, WA_MENUITEM_RESCAN_LIBRARY,     MF_ENABLED);
    EnableMenuItem(altMenu,     WA_MENUITEM_RESCAN_LIBRARY,     MF_ENABLED);
}

///
bool Shuffler::loadConfig(string filename) {
    Logger* logger(Logger::getInstance());

    // Open config file
    string      path(getConfigDirectory() + filename);
    ifstream    file(path.c_str(), ios::in);

    // Unable to open file
    if (!file) {
        logger->log("[WARNING] Unable to open config file (" + path + ").\n\n");
        return false;
    }

    // Read line by line
    string          buffer;
    string          parameter;
    unsigned int    intBuffer;
    double          doubleBuffer;
    string          stringBuffer;

    while (!file.eof()) {
        getline(file, buffer);
        stringstream line(buffer);
        line >> parameter;

        // Extract dimensions
        if (parameter == "DIMENSIONS") {
            line >> intBuffer;
            map->setDimensions(intBuffer);

            logger->log("[CONFIG] Dimensions set to ");
            logger->log(intBuffer);
            logger->log("\n");
        }

        // Extract number of tracks per HTTP query
        else if (parameter == "TRACKS_PER_QUERY") {
            line >> intBuffer;
            map->setTracksPerQuery(intBuffer);

            logger->log("[CONFIG] Tracks per query set to ");
            logger->log(intBuffer);
            logger->log("\n");
        }

        // Extract nearest neighbor error bound
        else if (parameter == "ERROR_BOUND") {
            line >> doubleBuffer;
            map->setNearestNeighborErrorBound(doubleBuffer);

            logger->log("[CONFIG] Nearest neighbor error bound set to ");
            logger->log(doubleBuffer);
            logger->log("\n");
        }

        // Extract remote scale factor
        else if (parameter == "REMOTE_SCALE") {
            line >> doubleBuffer;
            remoteScale = doubleBuffer;

            logger->log("[CONFIG] Remote scale factor set to ");
            logger->log(doubleBuffer);
            logger->log("\n");
        }

        // Extract remote constant factor
        else if (parameter == "REMOTE_CONSTANT") {
            line >> doubleBuffer;
            remoteConstant = doubleBuffer;

            logger->log("[CONFIG] Remote constant factor set to ");
            logger->log(doubleBuffer);
            logger->log("\n");
        }

        // Extract remote bound
        else if (parameter == "REMOTE_BOUND") {
            line >> doubleBuffer;
            remoteBound = doubleBuffer;

            logger->log("[CONFIG] Remote bound set to ");
            logger->log(doubleBuffer);
            logger->log("\n");
        }

        // Extract database host
        else if (parameter == "DATABASE_HOST") {
            line >> stringBuffer;
            // TODO

            logger->log("[CONFIG] Database host set to " + stringBuffer + "\n");
        }

        // Extract database script path
        else if (parameter == "DATABASE_SCRIPT_PATH") {
            line >> stringBuffer;
            // TODO

            logger->log("[CONFIG] Database script path set to " + stringBuffer + "\n");
        }
    }

    file.close();

    return true;
}

///
void Shuffler::loadMap(string filename) {
    mapLoad.start();
}

///
void Shuffler::prepareNextTrack() {
    nextTrackPreparation.start();
}

///
bool Shuffler::retrievePlayingTrack() {
    Map* map(Map::getInstance());

    // Check if Winamp is playing
    if (!isPlaying())   return false;

    wstring filename((wchar_t*)SendMessage(
        plugin.hwndParent,
        WM_WA_IPC,
        0,
        IPC_GET_PLAYING_FILENAME
    ));
    wstring title((wchar_t*)SendMessage(
        plugin.hwndParent,
        WM_WA_IPC,
        0,
        IPC_GET_PLAYING_TITLE
    ));
    int trackLength = SendMessage(
        plugin.hwndParent,
        WM_WA_IPC,
        1,
        IPC_GETOUTPUTTIME
    );

    /*if (playingTrack) {
        if (playingTrack->getPath().compare(narrow(filename)))// */
            playingTrack = map->findTrack(title, filename);
    //}

    playlistPosition = getListPosition();
    playlistLength   = getListLength();

    return true;
}

///
void Shuffler::scanLibrary() {
    libraryScan.start();
}

///
// TODO: improve this function.
void Shuffler::setMenuItem(ShuffleMode newMode, bool newState) {
    // Invalid input
    if (newMode == OFF)     return;

    // Pre-processing
    long    state(0);
    DWORD   menuItem(WA_MENUITEM_SHUFFLE_ON_LIBRARY);
    wstring text(L"Smart shuffle");
    int     positionFile(menu_item_position_file);
    int     positionOption(menu_item_position_option);

    if (newState)
        state = MFS_CHECKED;
    if (newMode == ON_PLAYLIST) {
        menuItem    = WA_MENUITEM_SHUFFLE_ON_PLAYLIST;
        text        = L"Smart shuffle on current playlist";
        positionFile++;
        positionOption++;
    }

    // Update menu item
    MENUITEMINFO k = {sizeof(k), MIIM_ID | MIIM_STATE | MIIM_TYPE, MFT_STRING, state, menuItem};
    k.dwTypeData = (LPWSTR)text.c_str();
	SetMenuItemInfo(windowsMenu, (positionFile), TRUE, &k);
	SetMenuItemInfo(altMenu, (positionOption), TRUE, &k);
}

void Shuffler::toggleMode(ShuffleMode toggledMode) {
    // Invalid input
    if (toggledMode == OFF) {
        mode = toggledMode;
        return;
    }

    // Pre-processing
    ShuffleMode otherMode(ON_LIBRARY);
    if (toggledMode == ON_LIBRARY)  otherMode = ON_PLAYLIST;

    // Update menu items accordingly
    if (mode == toggledMode) {
        setMenuItem(toggledMode, false);
        mode = OFF;

        #ifdef DEBUG
        Logger* logger = Logger::getInstance();
        logger->log("[MODE] Smart shuffle off.\n\n");
        #endif
    } else if (mode == otherMode) {
        // TODO: wait for library scan to end
        setMenuItem(toggledMode, true);
        setMenuItem(otherMode, false);
        mode = toggledMode;

        #ifdef DEBUG
        Logger* logger = Logger::getInstance();
        if      (mode == ON_LIBRARY)    logger->log("[MODE] Smart shuffle on library.\n\n");
        else                            logger->log("[MODE] Smart shuffle on playlist.\n\n");
        #endif
    } else {
        setMenuItem(toggledMode, true);
        mode = toggledMode;

        onStart();
    }
}

///
void Shuffler::toggleMode() {
    if (mode == ON_LIBRARY) mode = ON_PLAYLIST;
    else                    mode = ON_LIBRARY;
}

void Shuffler::onEndTrack() {
    // Check for mode
    if (mode == OFF)    return;

    #ifdef DEBUG
    Logger* logger = Logger::getInstance();
    logger->log("[END] Total listening time: ");
    logger->log((endTime - startTime) - (pauseEndTime - pauseStartTime));
    logger->log("s\n\n");
    #endif

	// Last track of playlist => switch to next local track
    if (playlistPosition == playlistLength - 1) {    // playlistPosition starts from 0
        appendToPlaylist(localNextTrack);

        if (playingTrack->hasCoordinates() && localNextTrack->hasCoordinates())
            remoteRadius = distanceBetween(playingTrack, localNextTrack);

        setListPosition(playlistPosition + 1);
        SendMessage(plugin.hwndParent, WM_COMMAND, MAKEWPARAM(WINAMP_BUTTON2, 0), 0);
    }

}

///
void Shuffler::onNextTrack() {
    // Check for mode
    if (mode == OFF)    return;

	#ifdef DEBUG
    Logger* logger = Logger::getInstance();
	logger->log(endTime - startTime);
	logger->log("s\n");
	logger->log(pauseEndTime - pauseStartTime);
	logger->log("s\n");
	#endif

	if ((pauseEndTime - pauseStartTime) > (endTime - startTime))
		pauseEndTime = pauseStartTime = 0;

	#ifdef DEBUG
    logger->log("[NEXT] Total Listening Time: ");
	logger->log((endTime - startTime) - (pauseEndTime - pauseStartTime));
	logger->log("s\n\n");
    #endif

    nextTrackPreparation.wait();

	// Calculating Song Played Ratio
	float timePlayed = (endTime - startTime) - (pauseEndTime - pauseStartTime);
	float playedRatio = timePlayed / (float)playingTrack->getLength();

    // Last track of playlist => switch to next remote track
    if (playlistPosition == playlistLength - 1) {    // playlistPosition starts from 0
		if (playedRatio < 0.5)
	        appendToPlaylist(remoteNextTrack);
		else
			appendToPlaylist(localNextTrack);
        setListPosition(playlistPosition + 1);
        SendMessage(plugin.hwndParent, WM_COMMAND, MAKEWPARAM(WINAMP_BUTTON2, 0), 0);
    }

	// Testing playedRatio
	#ifdef DEBUG
	logger->log("Played Ratio: ");
	logger->log(playedRatio);
	logger->log("s\n\n");
	#endif

}

///
void Shuffler::onPausePlaying() {
    // Check for mode
    if (mode == OFF)    return;

	paused = true;

	// Update chronometers
	GetSystemTime(&psTime);
	SystemTimeToFileTime(&psTime,&pstTime);

	uli.LowPart  = pstTime.dwLowDateTime;
	uli.HighPart = pstTime.dwHighDateTime;

	pauseStartTime = (uli.QuadPart/10000000);

	#ifdef DEBUG
	Logger* logger = Logger::getInstance();
	logger->log("[PAUSE]\n\n");
	#endif
}

void Shuffler::onPreviousTrack() {
    // Check for mode
    if (mode == OFF)    return;

    #ifdef DEBUG
    Logger* logger = Logger::getInstance();
    logger->log("[PREVIOUS]\n\n");
    #endif

	startTime = endTime = pauseStartTime = pauseEndTime = 0;

}

void Shuffler::onRescanLibrary() {
    #ifdef DEBUG
    Logger* logger(Logger::getInstance());
    logger->log("Rescanning library... ");
    #endif

    // Database unreachable
    if (!databaseAvailable()) {
        string feedback;
        feedback = "Scanning library needs access to internet.\n\n";
        feedback += "Please ensure that Winamp is not in offline mode, ";
        feedback += "and that your internet connection is working.";

        MessageBoxA(plugin.hwndParent, feedback.c_str(), "Need internet connection", MB_OK | MB_ICONWARNING);
        return;
    }

    string question;
        question += "Scanning may take several minutes for big collections; ";
        question += "it is done in background, so that you can keep using ";
        question += "Winamp during this operation. ";
        question += "You will be warned when the scan is complete.\n\n";
        question += "Would you like to do it now ?\n\n";

    int answer(MessageBoxA(
        plugin.hwndParent,
        question.c_str(),
        "Are you sure ?",
        MB_YESNO | MB_ICONQUESTION
    ));

    if (answer == IDYES)
        scanLibrary();
}

void Shuffler::onResumePlaying() {
    // Check for mode
    if (mode == OFF)    return;

    if (paused) {
        paused = false;

        // Update chronometers
        GetSystemTime(&peTime);
        SystemTimeToFileTime(&peTime,&penTime);

        uli.LowPart  = penTime.dwLowDateTime;
        uli.HighPart = penTime.dwHighDateTime;

        pauseEndTime = (uli.QuadPart/10000000);

        // Debug logging
        #ifdef DEBUG
        Logger* logger = Logger::getInstance();
        logger->log("[RESUME]\n\n");
        #endif
    }
}

///
void Shuffler::onStart() {
    srand(time(NULL));

    #ifdef DEBUG
    Logger* logger = Logger::getInstance();
    if      (mode == ON_LIBRARY)    logger->log("[MODE] Smart shuffle on library.\n\n");
    else                            logger->log("[MODE] Smart shuffle on playlist.\n\n");
    #endif

    // Get playing track
    mapLoad.wait();
    if (!retrievePlayingTrack()) {
        playingTrack = map->getTrack(rand() % map->getSize());
    }

    // Flush playlist
    SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_DELETE);
    appendToPlaylist(playingTrack);
    SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_STARTPLAY);
}

///
void Shuffler::onStartPlaying() {
    // Check for mode
    if (mode == OFF)    return;

    // Retrieve information about playing track
    retrievePlayingTrack();

    // Manage history
    lastPlayedTracks.push_back(playingTrack);
    playingTrack->setAlreadyPlayed(true);

    if (lastPlayedTracks.size() > log((double)map->getSize()) + 1) {
        lastPlayedTracks.front()->setAlreadyPlayed(false);
        lastPlayedTracks.pop_front();
    }

    // Prepare next track
    prepareNextTrack();

    int trackLength = SendMessage(plugin.hwndParent, WM_WA_IPC, 1, IPC_GETOUTPUTTIME);

    // Update chronometers
	GetSystemTime(&sTime);
	SystemTimeToFileTime(&sTime,&stTime);

	uli.LowPart  = stTime.dwLowDateTime;
	uli.HighPart = stTime.dwHighDateTime;

	startTime = (uli.QuadPart/10000000);

    // Debug logging
    #ifdef DEBUG
    Logger* logger = Logger::getInstance();
    logger->log("[PLAYING] [");
    logger->log(playingTrack->getId());
    logger->log("] (");
    logger->log(playingTrack->getLength());
    logger->log("s)\nSize of history: ");
    logger->log(lastPlayedTracks.size());
    logger->log("\nCurrent position = ");
    logger->log(playlistPosition);
    logger->log("\nPlaylist length = ");
    logger->log(playlistLength);
    logger->log("\n\n");
	#endif
}

///
void Shuffler::onStopPlaying() {
    // Check for mode
    if (mode == OFF)    return;

    GetSystemTime(&eTime);
	SystemTimeToFileTime(&eTime, &enTime);

	uli.LowPart  = enTime.dwLowDateTime;
	uli.HighPart = enTime.dwHighDateTime;

	endTime = (uli.QuadPart/10000000);

    /*
     * End of the track reached => play nearest neighbor
     * Contrary to what is suggested in the documentation
     * this will NOT be triggered when the user presses
     * "next track" button.
     */
    if (SendMessage(plugin.hwndParent, WM_WA_IPC, 0, IPC_ISFULLSTOP)) {
        onEndTrack();
    } else {
        #ifdef DEBUG
        Logger* logger = Logger::getInstance();
        logger->log("[FULL STOP]\n\n");
        #endif
    }
}

///
Shuffler::LibraryScan::LibraryScan(Shuffler* newParent) : parent(newParent) {
}

///
Shuffler::LibraryScan::~LibraryScan() {
    wait();
}

/**
 * \brief Scans the whole media library and download coordinates for all tracks.
 */
void Shuffler::LibraryScan::run() {
    Logger* logger(Logger::getInstance());
    logger->log("Scanning library...\n");

    // Disable shuffler
    parent->disable();

    //  Build path to Media Library files
    string directory = parent->getConfigDirectory();
    char*  pathToDat = new char[directory.size() + 12];
    char*  pathToIdx = new char[directory.size() + 12];

    strcpy(pathToDat, directory.c_str());
    strcpy(pathToIdx, directory.c_str());
    strcat(pathToDat, "ml\\main.dat");      // SENSITIVE: may depend on Winamp version !
    strcat(pathToIdx, "ml\\main.idx");      // SENSITIVE: may depend on Winamp version !

    //  Pre-processing
    Database        db;
	Table*          table(db.OpenTable(pathToDat, pathToIdx, false, false)); // Do not create table either index
    Map*            map(Map::getInstance());
    Scanner         *scanner = table->NewScanner(0);
    unsigned long   i(0);

    map->clear();
    map->setSize(table->GetRecordsCount()); // ANN cannot allocate dynamically

	//  A scanner lets us iterate through the records
	for (scanner->First(); !scanner->Eof(); scanner->Next()) {
		//time_t time; // time_t -> char * conversion routines require a pointer, so we'll allocate on the stack

		/*
		Scanner::GetFieldByName(char *) returns a "Field *"
		we have to cast it to the appropriate subclass of Field * and hope for the best
		using dynamic_cast<> and making sure it doesn't cast to 0 would be better
		*/
		FilenameField*  fileName    = (FilenameField*)scanner->GetFieldByName("filename");
		StringField*    title       = (StringField*)scanner->GetFieldByName("title");
		StringField*    artist      = (StringField*)scanner->GetFieldByName("artist");
		StringField*    album       = (StringField*)scanner->GetFieldByName("album");
		IntegerField*   year        = (IntegerField*)scanner->GetFieldByName("year");
		StringField*    genre       = (StringField*)scanner->GetFieldByName("genre");
        IntegerField*   length      = (IntegerField*)scanner->GetFieldByName("length");
		IntegerField*   lastPlay    = (IntegerField*)scanner->GetFieldByName("lastplay"); // time_t
		IntegerField*   rating      = (IntegerField*)scanner->GetFieldByName("rating");
		IntegerField*   playCount   = (IntegerField*)scanner->GetFieldByName("playCount");

		/*
		sometimes Scanner::GetFieldByName() returns 0 (usually if the field isn't present for this record)
		so we need to check.
		*/

        Track newTrack(i);
		if (fileName && fileName->GetString())
			newTrack.setPath(fileName->GetString());
        if (title && title->GetString())
			newTrack.setTitle(title->GetString());
        if (artist && artist->GetString())
			newTrack.setArtist(artist->GetString());
		if (album && album->GetString())
			newTrack.setAlbum(album->GetString());
		if (year)
            newTrack.setYear(year->GetValue());
        if (genre && genre->GetString())
            newTrack.setGenre(genre->GetString());
        if (length)
            newTrack.setLength(length->GetValue());

        // TODO: implement the following
		/*if (lastPlay) {
			newTrack.setLastPlay(lastPlay->GetValue());
			cout << "lastPlay="<<  asctime(localtime(&lastPlay->GetValue()));
		}
		if (rating)
			cout << "rating="<< rating->GetValue() << endl;
		if (playCount)
			cout << "playCount="<< playCount->GetValue() << endl; // */

        map->insert(newTrack);
	}

    // Download coordinates and save them
    map->downloadMissingCoordinates();
    map->save();

	//  Cleanup
	table->DeleteScanner(scanner);
	db.CloseTable(table);
    parent->enable();

    // Notify user
    MessageBoxA(
        plugin.hwndParent,
        "The library has been scanned successfully, you can now use smart shuffle.",
        "Scan complete",
        MB_OK
    );

    logger->log("Library successfully scanned.\n\n");
}

///
Shuffler::MapLoad::MapLoad(Shuffler* newParent, string newFilename) :
        parent(newParent),
        filename(newFilename) {
}

///
Shuffler::MapLoad::~MapLoad() {
    wait();
}

/**
 * \brief Load map from file.
 */
void Shuffler::MapLoad::run() {
    // Disable shuffler first
    parent->disable();

    Map* map(Map::getInstance());
    if (map->load(filename)) {
        parent->enable();
        return;
    }

    // Unable to load map from file
    //  => propose to scan library, if database is reachable
    if (!parent->databaseAvailable())     return;

    string question;
        question += "In order to use smart shuffle, ";
        question += "you must first scan the media library.";

        question += "Scanning may take several minutes for big collections; ";
        question += "it is done in background, so that you can keep using ";
        question += "Winamp during this operation. ";
        question += "You will be warned when the scan is complete.\n\n";

        question += "Would you like to do it now ?\n\n";

        question += "If you don't, you can do it later via the ";
        question += "\"Play\" menu entry.";

    int answer(MessageBoxA(
        plugin.hwndParent,
        question.c_str(),
        "Scan library now ?",
        MB_YESNO | MB_ICONQUESTION
    ));

    if (answer == IDYES)
        parent->scanLibrary();
}

///
Shuffler::NextTrackPreparation::NextTrackPreparation(Shuffler* newParent) :
        parent(newParent) {
}

///
Shuffler::NextTrackPreparation::~NextTrackPreparation() {
    wait();
}

///
void Shuffler::NextTrackPreparation::run() {
    Map* map(Map::getInstance());
    srand(time(NULL));

    unsigned int n(parent->lastPlayedTracks.size());

    // Current track has no coordinate => next is random
    if (!parent->playingTrack->hasCoordinates()) {
        parent->localNextTrack  = map->getTrack(rand() % map->getSize());
        parent->remoteNextTrack = parent->localNextTrack;

        // Debug logging
        #ifdef DEBUG
        Logger* logger = Logger::getInstance();
        logger->log("Local next track : [");
        logger->log(parent->localNextTrack->getId());
        logger->log("]");
        if (parent->playingTrack->hasCoordinates()) {
            logger->log(" (distance = ");
            logger->log(parent->distanceBetween(parent->playingTrack, parent->localNextTrack));
            logger->log(")");
        }
        logger->log("\nRemote next track : [");
        logger->log(parent->remoteNextTrack->getId());
        logger->log("]");
        if (parent->playingTrack->hasCoordinates() && parent->remoteNextTrack->hasCoordinates()) {
            logger->log(" (distance = ");
            logger->log(parent->distanceBetween(parent->playingTrack, parent->remoteNextTrack));
            logger->log(")");
        }
        logger->log("\n");
        #endif DEBUG

        return;
    }

    // Next track within local area
    const ANNidxArray   nearestTracks(map->findNearestNeighbors(parent->playingTrack, n+1));
    unsigned long       i(1);

    while (i < n+1) {
        if (!map->getTrack(nearestTracks[i])->isAlreadyPlayed()) {
            parent->localNextTrack = map->getTrack(nearestTracks[i]);
            break;
        }

        i++;
    }

    // No reference to compute distance => next remote is random
    if ((n > 1 && !parent->lastPlayedTracks[n-2]->hasCoordinates())
    ||  !parent->playingTrack->hasCoordinates()) {
        parent->remoteNextTrack = map->getTrack(rand() % map->getSize());

        // Debug logging
        #ifdef DEBUG
        Logger* logger = Logger::getInstance();
        logger->log("Local next track : [");
        logger->log(parent->localNextTrack->getId());
        logger->log("]");
        if (parent->playingTrack->hasCoordinates()) {
            logger->log(" (distance = ");
            logger->log(parent->distanceBetween(parent->playingTrack, parent->localNextTrack));
            logger->log(")");
        }
        logger->log("\nRemote next track : [");
        logger->log(parent->remoteNextTrack->getId());
        logger->log("]");
        if (parent->playingTrack->hasCoordinates() && parent->remoteNextTrack->hasCoordinates()) {
            logger->log(" (distance = ");
            logger->log(parent->distanceBetween(parent->playingTrack, parent->remoteNextTrack));
            logger->log(")");
        }
        logger->log("\n");
        #endif DEBUG

        return;
    }

    // Increase distance to next remote
    if (n > 1) {
        parent->remoteRadius = parent->remoteScale * parent->remoteRadius;
        parent->remoteRadius = parent->remoteConstant + parent->remoteRadius;
        parent->remoteRadius = min(parent->remoteRadius, parent->remoteBound);
    } else {
        parent->remoteRadius = parent->remoteScale * parent->remoteRadius;
        parent->remoteRadius = parent->remoteConstant + parent->remoteRadius;
        parent->remoteRadius = min(parent->remoteRadius, parent->remoteBound);
    }

    ANNpoint            remotePoint(randomPointOnSphere(map->getDimensions(), parent->remoteRadius));
    const ANNidxArray   results(map->findNearestNeighbors(remotePoint, 3));
    unsigned int        j(1);

    if (results[j] == parent->playingTrack->getId())    j = 2;

    parent->remoteNextTrack = map->getTrack(results[j]);

    // Debug logging
    #ifdef DEBUG
    Logger* logger = Logger::getInstance();
    logger->log("Local next track : [");
    logger->log(parent->localNextTrack->getId());
    logger->log("]");
    if (parent->playingTrack->hasCoordinates()) {
        logger->log(" (distance = ");
        logger->log(parent->distanceBetween(parent->playingTrack, parent->localNextTrack));
        logger->log(")");
    }
    logger->log("\nRemote next track : [");
    logger->log(parent->remoteNextTrack->getId());
    logger->log("]");
    if (parent->playingTrack->hasCoordinates()) {
        logger->log(" (distance = ");
        //logger->log(parent->distanceBetween(parent->playingTrack, parent->remoteNextTrack));
        logger->log(parent->remoteRadius);
        logger->log(")");
    }
    logger->log("\n");
    #endif DEBUG
}


text:
#pragma once

#include "block.h"

#include <array>

#define PYR_ROWS 8
#define PYR_COLS 13

struct ALLEGRO_BITMAP;

template <typename T>
using pyr_arr_rc = std::array<std::array<T, PYR_COLS>, PYR_ROWS>;

class Pyramid
{
public:
    Pyramid();

    void draw();

    BlockType get_block_at(int col, int row);
    bool invert_block_at(int col, int row, double time);

    void update(double dt);

    ALLEGRO_BITMAP *block_img;
    ALLEGRO_BITMAP *block_in_img;
    ALLEGRO_BITMAP *ladder_img;
    ALLEGRO_BITMAP *snake_img;

    pyr_arr_rc<BlockType> blocks;
    pyr_arr_rc<double> inverted_block;
};

repository: karjonas/Pyramid-Schemist

repo_name: karjonas/Pyramid-Schemist

extension: h


text:
package rdpConn

import (
	"fmt"
	"os/exec"

	"WinIdent"
)

func StrMstsConn(ip string, port string) string {
	//	return fmt.Sprintf("mstsc /v:'%s'", ip)
	return fmt.Sprintf("mstsc /v:%s:%s", ip, port)
}

func MstsCmd(ip string, username string, password string, port string) error {
	connStr := StrMstsConn(ip, port)
	err := winIdent.CreateRDPSession(ip, username, password)
	defer winIdent.DelRDPSession(ip)
	if err != nil {
		fmt.Println(err)
		return err
	}
	//	Cmd := exec.Command("PowerShell", "-Command", connStr)
	fmt.Println(connStr)
	Cmd := exec.Command("cmd", "/c", connStr)
	_, errCmd := Cmd.Output()
	if errCmd != nil {
		fmt.Println(errCmd)
		return errCmd
	}
	return nil
}


text:
package db

import (
	"fmt"
	"os"

	"github.com/brianloveswords/airtable"
	"github.com/hackclub/awesome_hackclub_auto/pkg/logging"
)

func projectsTable() airtable.Table {
	client := airtable.Client{
		APIKey: os.Getenv("AIRTABLE_API_KEY"),
		BaseID: os.Getenv("AIRTABLE_BASE_ID"),
	}

	return client.Table("Projects")
}

func CreateProjectIntent(fields ProjectFields) string {
	projects := projectsTable()

	fields.Status = ProjectStatusIntent
	project := Project{
		Fields: fields,
	}

	err := projects.Create(&project)
	if err != nil {
		logging.Log(err, "error", false)
	}

	return project.ID
}

func GetProject(id string) Project {
	projects := projectsTable()

	project := Project{}
	err := projects.Get(id, &project)

	if err != nil {
		return Project{}
	}

	logging.Log(fmt.Sprintf("Got project %s from Airtable", project.Fields.Name), "info", false)
	return project
}

func UpdateProject(newProject Project) {
	projects := projectsTable()

	err := projects.Update(&newProject)
	if err != nil {
		logging.Log(err, "error", false)
	}
	logging.Log(fmt.Sprintf("Updated project %s in Airtable", newProject.Fields.Name), "info", false)
}

func DeleteProject(project Project) {
	projects := projectsTable()

	project.Fields.Status = ProjectStatusDeleted

	err := projects.Update(&project)
	if err != nil {
		logging.Log(err, "error", false)
	}
	logging.Log(fmt.Sprintf("Removed project %s from Airtable", project.Fields.Name), "info", false)
}

func GetAllProjects() []Project {
	table := projectsTable()

	projects := []Project{}

	err := table.List(&projects, &airtable.Options{Filter: "Status = 'project'", Sort: airtable.Sort{
		[2]string{"Category", "asc"},
		[2]string{"Language", "asc"},
		[2]string{"Name", "asc"},
	}})
	if err != nil {
		logging.Log(err, "error", false)
	}
	logging.Log("Got all projects from Airtable", "info", false)
	return projects
}


text:
package filter

import (
	"math"
	"strconv"
	"strings"

	"github.com/go-apibox/types"
)

type Uint32SetFilter struct {
	base       int
	delimiter  string
	minCount   int
	maxCount   int
	validators []Uint32SetValidator
	allowVals  []string
}

type Uint32SetValidator func(paramName string, paramValue []uint32) *Error

// Uint32Set return a uint64 set filter.
func Uint32Set() *Uint32SetFilter {
	f := new(Uint32SetFilter)
	f.base = 10
	f.delimiter = ","
	f.minCount = 0
	f.maxCount = types.MaxInt
	return f
}

// Allow allow value is a string in the specified list
func (f *Uint32SetFilter) Allow(vals ...string) *Uint32SetFilter {
	f.allowVals = append(f.allowVals, vals...)
	return f
}

// Base set the base of uint64.
// Uint32SetFilter interprets a string s in the given base (2 to 36) and returns
// the corresponding value i. If base == 0, the base is implied by the
// string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.
func (f *Uint32SetFilter) Base(base int) *Uint32SetFilter {
	f.base = base
	return f
}

// Delimiter set the delimiter of set string.
func (f *Uint32SetFilter) Delimiter(delimiter string) *Uint32SetFilter {
	f.delimiter = delimiter
	return f
}

// MinCount set the max item count of set.
func (f *Uint32SetFilter) MinCount(count int) *Uint32SetFilter {
	f.minCount = count
	return f
}

// MaxCount set the max item count of set.
func (f *Uint32SetFilter) MaxCount(count int) *Uint32SetFilter {
	f.maxCount = count
	return f
}

// AddValidator add a custom validator to filter
func (f *Uint32SetFilter) AddValidator(validator Uint32SetValidator) *Uint32SetFilter {
	f.validators = append(f.validators, validator)
	return f
}

// ItemMin valid whether item value of set is not smaller than specified value.
func (f *Uint32SetFilter) ItemMin(val uint32) *Uint32SetFilter {
	f.AddValidator(func(paramName string, paramValue []uint32) *Error {
		for _, v := range paramValue {
			if v < val {
				return NewError(ErrorInvalidParam, paramName, "ItemTooSmall")
			}
		}
		return nil
	})
	return f
}

// ItemMax valid whether item value of set is not larger than specified value.
func (f *Uint32SetFilter) ItemMax(val uint32) *Uint32SetFilter {
	f.AddValidator(func(paramName string, paramValue []uint32) *Error {
		for _, v := range paramValue {
			if v > val {
				return NewError(ErrorInvalidParam, paramName, "ItemTooLarge")
			}
		}
		return nil
	})
	return f
}

// ItemLargerThan valid whether item value of set is larger than the specified value.
func (f *Uint32SetFilter) ItemLargerThan(val uint32) *Uint32SetFilter {
	f.AddValidator(func(paramName string, paramValue []uint32) *Error {
		for _, v := range paramValue {
			if v <= val {
				return NewError(ErrorInvalidParam, paramName, "ItemTooSmall")
			}
		}
		return nil
	})
	return f
}

// ItemSmallerThan valid whether item value of set is smaller than the specified value.
func (f *Uint32SetFilter) ItemSmallerThan(val uint32) *Uint32SetFilter {
	f.AddValidator(func(paramName string, paramValue []uint32) *Error {
		for _, v := range paramValue {
			if v >= val {
				return NewError(ErrorInvalidParam, paramName, "ItemTooLarge")
			}
		}
		return nil
	})
	return f
}

// ItemBetween valid whether item value of set is in the specified set.
func (f *Uint32SetFilter) ItemBetween(min, max uint32) *Uint32SetFilter {
	f.AddValidator(func(paramName string, paramValue []uint32) *Error {
		for _, v := range paramValue {
			if v < min {
				return NewError(ErrorInvalidParam, paramName, "ItemTooSmall")
			}
			if v > max {
				return NewError(ErrorInvalidParam, paramName, "ItemTooLarge")
			}
		}
		return nil
	})
	return f
}

// ItemIn valid item value of set should in the specified set.
func (f *Uint32SetFilter) ItemIn(set []uint32) *Uint32SetFilter {
	f.AddValidator(func(paramName string, paramValue []uint32) *Error {
		for _, item := range paramValue {
			itemFound := false
			for _, v := range set {
				if v == item {
					itemFound = true
					break
				}
			}
			if !itemFound {
				return NewError(ErrorInvalidParam, paramName, "ItemNotInSet")
			}
		}
		return nil
	})
	return f
}

// Run make the filter running.
func (f *Uint32SetFilter) Run(paramName string, paramValue interface{}) (interface{}, *Error) {
	if paramValue == nil {
		return nil, nil
	}

	var intVals []uint32
	switch val := paramValue.(type) {
	case string:
		val = strings.Trim(val, " \t\r\n")
		for _, allowVal := range f.allowVals {
			if allowVal == val {
				return val, nil
			}
		}
		if val != "" {
			fields := strings.Split(val, f.delimiter)
			for _, field := range fields {
				field = strings.Trim(field, " \t\r\n")
				v, err := strconv.ParseUint(field, f.base, 32)
				if err != nil {
					goto parse_error
				}
				if v > uint64(math.MaxUint32) {
					goto parse_error
				}
				intVals = append(intVals, uint32(v))
			}
		} else {
			intVals = []uint32{}
		}
	case []string:
		fields := val
		for _, field := range fields {
			field = strings.Trim(field, " \t\r\n")
			v, err := strconv.ParseUint(field, f.base, 32)
			if err != nil {
				goto parse_error
			}
			if v > uint64(math.MaxUint32) {
				goto parse_error
			}
			intVals = append(intVals, uint32(v))
		}
	case []uint32:
		for _, v := range val {
			intVals = append(intVals, uint32(v))
		}
	default:
		goto parse_error
	}

	if len(intVals) < f.minCount {
		return nil, NewError(ErrorInvalidParam, paramName, "TooFew")
	}
	if len(intVals) > f.maxCount {
		return nil, NewError(ErrorInvalidParam, paramName, "TooMany")
	}

	for _, validator := range f.validators {
		if err := validator(paramName, intVals); err != nil {
			return nil, err
		}
	}

	return intVals, nil

parse_error:
	return nil, NewError(ErrorInvalidParam, paramName, "NotUint32Set")
}

repository: go-apibox/filter

repo_name: go-apibox/filter


text:
#pragma once
#include "GLFW\glfw3.h"
#include "Events\Event.h"
#include <string>
#include <functional>

struct WindowData
{
	std::string Title;
	uint32_t width, height;
	WindowData(const std::string& title = "OpenGL Tutorial", uint32_t width = 1920, uint32_t height = 1080) :
		Title(title), width(width), height(height) {}
};

class IWindow
{
public:
	using EventCallback = std::function<void(Event&)>;

	virtual ~IWindow() {}
	virtual void OnUpdate() = 0;
	virtual uint32_t GetWidth() const = 0;
	virtual uint32_t GetHeight() const = 0;

	virtual void SetEventCallback(const EventCallback& callback) = 0;
	virtual void SetVSync(bool enabled) = 0;
	virtual bool IsVSync() const = 0;

	virtual void* GetNativeWindow() const = 0;
	virtual void Shutdown() = 0;

	static IWindow* Create(const WindowData& data = WindowData());

};

repository: Render-Devs/OpenGL-TechTalks

repo_name: Render-Devs/OpenGL-TechTalks


text:
package config

// HTTP defines the available http configuration.
type HTTP struct {
	Addr      string `ocisConfig:"addr" env:"SEARCH_HTTP_ADDR"`
	Namespace string `ocisConfig:"-" yaml:"-"`
	Root      string `ocisConfig:"root" env:"SEARCH_HTTP_ROOT"`
}

repository: butonic/ocis

repo_name: butonic/ocis


text:
package assert

import (
	"fmt"
	"testing"
)

type BooleanAssertion func(val bool) (bool, string)
type IntegerAssertion func(val int) (bool, string)

func IsTrue() BooleanAssertion {
	return IsEqualToBool(true)
}

func IsFalse() BooleanAssertion {
	return IsEqualToBool(false)
}

func IsEqualToBool(cond bool) BooleanAssertion {
	return func(val bool) (bool, string) {
		if val != cond {
			return false, fmt.Sprintf("Expected \"%v\" but was: \"%v\"", cond, val)
		}
		return true, ""
	}
}

func IsEqualToInt(cond int) IntegerAssertion {
	return func(val int) (bool, string) {
		if val != cond {
			return false, fmt.Sprintf("Expected \"%v\" but was: \"%v\"", cond, val)
		}
		return true, ""
	}
}

func AssertThatBool(t *testing.T, val bool, test BooleanAssertion) {
	if result, msg := test(val); !result {
		t.Error(msg)
	}
}

func AssertThatInt(t *testing.T, val int, test IntegerAssertion) {
	if result, msg := test(val); !result {
		t.Error(msg)
	}
}

repository: PtrTeixeira/cookbook

repo_name: PtrTeixeira/cookbook

gha_language: Kotlin


text:
@inproceedings{talk2014,
  title = {Uptake Kinetics of Heavy Metals from Water Using a High Surface Area Supported Inorganic Metal Oxide.},
  abstract = {Efficient removal of radionuclides from water is extremely important given recent events, such as the Fukushima nuclear disaster.  Supported calcium-contg. inorg. metal oxide may be able to rapidly exchange with radionuclides from an aq. environment.  The feasibility studies were performed and the uptake kinetics of cobalt, thorium, cerium, and cesium from soln. were measured.  The uptake and rate consts. were detd. using pseudo-first order and pseudo-second order rate laws.  The applicability of these rate law models to the system was compared and contrasted to other models, notably Langmuir and Freundlich adsorption models. [on SciFinder(R)]},
  booktitle = {Abstracts of {{Papers}}, 247th {{ACS National Meeting}} \& {{Exposition}}, {{Dallas}}, {{TX}}, {{United States}}, {{March}} 16-20, 2014},
  publisher = {{American Chemical Society}},
  author = {Honeycutt, Wesley T. and Hamby, Hayden and Apblett, Allen and Materer, Nicholas F.},
  year = {2014},
  pages = {ENVR-272},
  note = {Copyright (C) 2015 American Chemical Society (ACS). All Rights Reserved.}
}

@inproceedings{talk2015,
  title = {Selectivity and Kinetic Behavior of Heavy Metal and Radionuclides on Supported Ion-Exchange Adsorbant.},
  abstract = {The removal of radionuclides by selective concn. from seawater is an esp. attractive goal since oceans contain valuable materials, although at low concns.  Radionuclide sources include natural abundance and seepage plus that which is due to industrially generated wastewater streams and nuclear incidents.  Challenges include the selectivity required for the low concns., high material vols., and high ionic strengths.  To address these problems, a recently available supported ion-exchange adsorbent was detd. by kinetic assay to be selective for uranium from simulated seawater.  These assay were also preformed for neodymium, lead, cobalt, strontium, cadmium, cesium, copper, thorium, barium, chromium, and nickel adsorbates, chosen due to either their presence in common wastewater streams or as surrogates for more exotic radionuclides.  The adsorbent was also tested using groundwater and lake water, each doped with analyte ions.  Anal. of the data revealed properties about the exchange mechanism regarding the Langmuirian growth of the analytes on the adorbant and leaching during subsurface migration by target ions.  Under simulated conditions, the test material was able to conc. heavy ions on the surface of the exchange interface with particular selectivity for uranium. [on SciFinder(R)]},
  booktitle = {Abstracts of {{Papers}}, 249th {{ACS National Meeting}} \& {{Exposition}}, {{Denver}}, {{CO}}, {{United States}}, {{March}} 22-26, 2015},
  publisher = {{American Chemical Society}},
  author = {Honeycutt, Wesley T. and Kadossov, Evgueni B. and Apblett, Allen W. and Materer, Nicholas F.},
  year = {2015},
  pages = {I+EC-44},
  note = {Copyright (C) 2016 American Chemical Society (ACS). All Rights Reserved.}
}

@inproceedings{jacob2016,
  series = {20},
  title = {Monitoring of {{Carbon Dioxide}} and {{Methane Plumes}} from {{Combined Ground}}-{{Airborne Sensors}}},
  volume = {61},
  abstract = {A hybrid ground-airborne sensing network for real-time plume monitoring of CO2 and CH4 for carbon sequestration is investigated. Conventional soil gas monitoring has difficulty in distinguishing gas flux signals from leakage with those associated with meteorologically driven changes. A low-cost, lightweight sensor system has been developed and implemented onboard a small unmanned aircraft and is combined with a large-scale ground network that measures gas concentration. These are combined with other atmospheric diagnostics, including thermodynamic data and velocity from ultrasonic anemometers and multi-hole probes. To characterize the system behavior and verify its effectiveness, field tests have been conducted with simulated discharges of CO2 and CH4 from compressed gas tanks to mimic leaks and generate gaseous plumes, as well as field tests over the Farnsworth CO2-EOR site in the Anadarko Basin. Since the sensor response time is a function of vehicle airspeed, dynamic calibration models are required to determine accurate location of gas concentration in space and time. Comparisons are made between the two tests and results compared with historical models combining both flight and atmospheric dynamics.},
  booktitle = {Convection and {{Boyancy Driven Flows}}: {{Environmental}}},
  publisher = {{APS}},
  author = {Jacob, Jamey and Mitchell, Taylor and Honeycutt, Wesley T. and Materer, Nicholas F. and Clark, Peter},
  month = nov,
  year = {2016}
}

@phdthesis{dissertation,
  address = {Stillwater, Oklahoma},
  type = {Dissertation},
  title = {Development and {{Applications}} of {{Chemical Sensors}} for the {{Detection}} of {{Atmospheric Carbon Dioxide}} and {{Methane}}},
  abstract = {This is a description of the design of a low-power, low-cost networked array of sensors for the remote monitoring of carbon dioxide and methane.  The goal was to create a scalable self-powered two-dimensional array for the detection of these gases in a large area.  The sensor selection, electronic design, and data communication was studied and optimized to allow for multiple units to form a self-assembling network for acre-scale coverage with minimal human intervention.  The final electronic design of the solar-powered units is flexible, providing a foundation for future field deployable remote monitoring devices.  Sensors were selected for this application from commercially available models based on low-power, low-cost, market availability, detection range, and accuracy around the global baseline criteria.  For environmental monitoring, carbon dioxide sensors are characterized near 400 ppm and methane from 2 to 200 ppm.  For both gases, exertions up to several 1000 pm were examined to mimic large releases.  An Xbee mesh network of radios was utilized to coordinate the individual units in the array, and the data was transferred in real-time over the cellular network to a dedicated server.  The system was tested at a site north of the Oklahoma State campus, an unmanned airfield east of Stillwater, OK, and an injection well near Farnsworth, TX.  Data collected from the Stillwater test sites show that the system is reliable for baseline gas levels.  The gas injection well site was monitored as a potential source of carbon dioxide and methane leaks due to the carbon dioxide injection process undertaken there for carbon sequestration and enhanced oil recovery efforts.  The sensors are shown to be effective at detecting gas concentration at the sites and few possible leak events are detected.},
  school = {Oklahoma State University},
  author = {Honeycutt, Wesley T.},
  month = may,
  year = {2017}
}

extension: bib


text:
package main

import (
	"fmt"
	"github.com/cdn-madness/tweetmap/lib"
	"github.com/cdn-madness/tweetmap/protobuf"
	"github.com/darkhelmet/twitterstream"
	"os"
	"runtime"
	"time"
)

func main() {

	runtime.GOMAXPROCS(runtime.NumCPU())

	// Get environment variables and construct API info
	apiCfg := tweetmap.TwitterAPIConfig{
		AccessSecret:   os.Getenv("TWITTER_ACCESS_SECRET"),
		AccessToken:    os.Getenv("TWITTER_ACCESS_TOKEN"),
		ConsumerSecret: os.Getenv("TWITTER_CONSUMER_SECRET"),
		ConsumerKey:    os.Getenv("TWITTER_CONSUMER_KEY"),
		SouthEast:      twitterstream.Point{0, 0},
		NorthWest:      twitterstream.Point{90, 180},
	}

	filter := func(t *twitterstream.Tweet) bool {
		return true
	}

	doneChan := make(chan bool)
	tweetChan, errChan := tweetmap.ListenToTwitter(apiCfg, filter, doneChan)

	go func(tc chan *prototweet.Tweet) {
		for tweet := range tc {
			fmt.Printf("Received tweet from %s\n", tweet.User)
		}
		fmt.Println("Exiting tweet function\n")
	}(tweetChan)

	go func(ec chan error) {
		for err := range ec {
			fmt.Printf("Error: %s\n", err.Error())
		}
		fmt.Println("Exiting error function\n")
	}(errChan)

	time.Sleep(10 * time.Second)
	close(doneChan)
	time.Sleep(100 * time.Second)
}

repository: alexurquhart/tweetmap

repo_name: alexurquhart/tweetmap


text:
@Misc{kaggle,
	OPTkey = {key},
	OPTauthor = {author},
	title = {Titanic: Machine Learning from Disaster},
	howpublished = {Web},
	month = {April},
	year = {2017},
	note = {\url{https://www.kaggle.com/c/titanic}
	},
	OPTannote = {},
}

@Misc{wikipedia:decision_tree,
	OPTkey = {key},
	author = {Wikipedia contributors.},
	title = {Decision tree learning},
	howpublished = {Wikipedia, The Free Encyclopedia},
	month = {April},
	year = {2017},
	note = {Retrieved 18:34, April 5, 2017, from \url{ https://en.wikipedia.org/w/index.php?title=Decision_tree_learning&oldid=773803391}},
	OPTannote = {annote},
}

@Article{shannon,
	author = {C.E. Shannon},
	title = {A Mathematical Theory of Communication},
	journal = {University of Illinois Press},
	year = {1949},
	OPTkey = {key},
	OPTvolume = {volume},
	OPTnumber = {number},
	OPTpages = {pages},
	OPTmonth = {month},
	OPTnote = {note},
	OPTannote = {annote},
}

repository: miguelamezola/titanic

repo_name: miguelamezola/titanic


text:
@inproceedings{HaladjianiPigACI,
address = {New York, NY, USA},
author = {Haladjian, Juan and Ermis, Ayca and Hodaie, Zardosht and Br{\"{u}}gge, Bernd},
booktitle = {Proceedings of the Fourth International Conference on Animal-Computer Interaction},
doi = {10.1145/3152130.3152145},
isbn = {978-1-4503-5364-9},
keywords = {activity recognition,animal,iPig,pig,wearable},
pages = {10:1----10:5},
publisher = {ACM},
series = {ACI2017},
title = {{iPig: Towards Tracking the Behavior of Free-roaming Pigs}},
year = {2017}
}


text:
package client

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"strconv"
)

// CreateFileInfo are parameters for Client.CreateFile
type CreateFileInfo struct {
	// The path to create
	FilePath string `json:"filePath"`
	// Whether the path is shared
	Shared bool `json:"isPathShared"`
	// Metadata to store with the file
	Metadata string `json:"metadata"`
}

// CreateFile creates a file. See https://maidsafe.readme.io/docs/nfsfile for more information.
func (c *Client) CreateFile(cf CreateFileInfo) error {
	req := &Request{
		Path:     "/nfs/file",
		Method:   "POST",
		JSONBody: cf,
	}
	_, err := c.Do(req)
	return err
}

// MoveFileInfo are parameters for Client.MoveFile. This is currently undocumented/unsupported. See
// https://maidsafe.atlassian.net/browse/CS-60 for more info.
type MoveFileInfo struct {
	SrcPath      string `json:"srcPath"`
	SrcShared    bool   `json:"isSrcPathShared"`
	DestPath     string `json:"destPath"`
	DestShared   bool   `json:"isDestPathShared"`
	RetainSource bool   `json:"retainSource"`
}

// MoveFile moves a file. This is currently undocumented/unsupported. See https://maidsafe.atlassian.net/browse/CS-60
// for more info.
func (c *Client) MoveFile(mf MoveFileInfo) error {
	// TODO: appears broken
	req := &Request{
		Path:     "/nfs/movefile",
		Method:   "POST",
		JSONBody: mf,
	}
	_, err := c.Do(req)
	return err
}

// DeleteFileInfo are parameters for Client.DeleteFile
type DeleteFileInfo struct {
	// The path to delete
	FilePath string
	// Whether the path is shared
	Shared bool
}

// DeleteFile deletes a file. See https://maidsafe.readme.io/docs/nfs-delete-file for more info.
func (c *Client) DeleteFile(df DeleteFileInfo) error {
	req := &Request{
		Path:   "/nfs/file/" + url.QueryEscape(df.FilePath) + "/" + strconv.FormatBool(df.Shared),
		Method: "DELETE",
	}
	_, err := c.Do(req)
	return err
}

// ChangeFileInfo are parameters for Client.ChangeFile. This is currently undocumented/unsupported. See
// https://maidsafe.atlassian.net/browse/CS-60 for more info.
type ChangeFileInfo struct {
	FilePath string `json:"-"`
	Shared   bool   `json:"-"`
	NewName  string `json:"name,omitempty"`
	Metadata string `json:"metadata,omitempty"`
}

// ChangeFile changes the file name, metadata, or both. This is currently undocumented/unsupported. See
// https://maidsafe.atlassian.net/browse/CS-60 for more info.
func (c *Client) ChangeFile(cf ChangeFileInfo) error {
	// TODO: what if they want to set metadata to empty?
	if cf.NewName == "" && cf.Metadata == "" {
		return errors.New("Must provide name or metadata")
	}
	req := &Request{
		Path:     "/nfs/file/metadata/" + url.QueryEscape(cf.FilePath) + "/" + strconv.FormatBool(cf.Shared),
		Method:   "PUT",
		JSONBody: cf,
	}
	_, err := c.Do(req)
	return err
}

// WriteFileInfo are parameters for Client.WriteFile
type WriteFileInfo struct {
	// The path to write to
	FilePath string
	// Whether the path is shared
	Shared bool
	// The contents to write
	Contents io.ReadCloser
	// The byte offset in the file to start writing
	Offset int64
}

// WriteFile writes a file. See https://maidsafe.readme.io/docs/nfs-update-file-content for more info.
func (c *Client) WriteFile(wf WriteFileInfo) error {
	// TODO: support chunking instead of all in mem
	defer wf.Contents.Close()
	byts, err := ioutil.ReadAll(wf.Contents)
	if err != nil {
		return fmt.Errorf("Unable to read contents: %v", err)
	}
	req := &Request{
		Path:    "/nfs/file/" + url.QueryEscape(wf.FilePath) + "/" + strconv.FormatBool(wf.Shared),
		Method:  "PUT",
		RawBody: byts,
		Query:   map[string][]string{"offset": []string{strconv.FormatInt(wf.Offset, 10)}},
	}
	_, err = c.Do(req)
	return err
}

// GetFileInfo are parameters for Client.GetFile
type GetFileInfo struct {
	// The path to get
	FilePath string
	// Whether the path is shared
	Shared bool
	// The byte offset to start reading at
	Offset int64
	// The amount of bytes to read. If the value is 0 then there is no length constraint
	Length int64
}

// GetFile obtains a file's contents. See https://maidsafe.readme.io/docs/nfs-get-file for more info.
func (c *Client) GetFile(gf GetFileInfo) (io.ReadCloser, error) {
	// TODO: support chunking instead of all in mem
	query := map[string][]string{"offset": []string{strconv.FormatInt(gf.Offset, 10)}}
	if gf.Length > 0 {
		query["length"] = []string{strconv.FormatInt(gf.Length, 10)}
	}
	req := &Request{
		Path:   "/nfs/file/" + url.QueryEscape(gf.FilePath) + "/" + strconv.FormatBool(gf.Shared),
		Method: "GET",
		Query:  query,
	}
	resp, err := c.Do(req)
	if err != nil {
		return nil, fmt.Errorf("Unable to get file: %v", err)
	}
	byts, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("Unable to read file output: %v", err)
	}
	return ioutil.NopCloser(bytes.NewReader(byts)), nil
}

repository: cretz/go-safeclient

repo_name: cretz/go-safeclient


text:
@article{Warden-2018,
	Author = {Warden, Pete},
	Title = {{Speech Commands: A Dataset for Limited-Vocabulary Speech Recognition}},
	Booktitle = {{arXiv:1804.04309v1 [cs.CL] 9 Apr 2018}},
	Address = {{Mountain View, CA, USA}},
	Month = apr,
	Year = {2018}
	}

@phdthesis{Jansson-2018,
	Author = {Jansson, Patric},
	Title = {{Single-word speech recongnition with Convolutional Neural Networks on raw waveforms}},
	Month = apr,
	Year = {2018}
	}

@article{Tang-2018,
	Author = {Tang, Taphael and Line, Jimmy},
	Title = {{Deep residual learning for small-footprin keyword spotting}},
	Booktitle = {{arXiv:1210.10361v2 [cs.CL] 21 Sep 2018}},
	Address = {{Waterloo, CA}},
	Month = sep,
	Year = {2018}
	}

@article{Andrade-2018,
	Author = {Coimbra de Andrade, Douglas and Leo, Sabato and Loesner Da Silva Viana, Martin and Bernkopf, Christoph},
	Title = {{A Neural attention model for speech command recognition}},
	Booktitle = {{arXiv:1808.0892v1 [eess.AS] 27 Aug 2018}},
	Month = aug,
	Year = {2018}
	}

@article{Zang-2018,
	Author = {Chen, Qiyu and Zhang, Weibin and Xu, Xianmin and Xing, Xiaofen},
	Title = {{Improved Keyword Spotting based on Keyword/Garbage Models}},
	Address = {{GuangZhou, CHN}},
	Month = sep,
	Year = {2018}
	}

@article{Huh-2020,
	Author = {Huh, Jaesun and Lee, Minjae and Heo, Heesoo and Mun, Seongkyu and Son Chung, Joon},
	Title = {{Metric Learning for Keyword Spotting}},
	Address = {{South Corea}},
	Booktitle = {{arXiv:2005.08776v1 [eess.AS] 18 May 292}},
	Month = may,
	Year = {2020}
}

@article{de2018neural,
	title={A neural attention model for speech command recognition},
	author={de Andrade, Douglas Coimbra and Leo, Sabato and Viana, Martin Loesener Da Silva and Bernkopf, Christoph},
	journal={arXiv preprint arXiv:1808.08929},
	year={2018}
}

@inproceedings{sainath2015convolutional,
	title={Convolutional neural networks for small-footprint keyword spotting},
	author={Sainath, Tara N and Parada, Carolina},
	booktitle={Sixteenth Annual Conference of the International Speech Communication Association},
	year={2015}
}


text:
package output

import "github.com/stefanoj3/dirstalk/pkg/scan"

func NewNullSaver() NullSaver {
	return NullSaver{}
}

type NullSaver struct{}

func (n NullSaver) Save(r scan.Result) error {
	return nil
}

func (n NullSaver) Close() error {
	return nil
}

repository: bbhunter/dirstalk

repo_name: bbhunter/dirstalk


text:
---
---

@phdthesis{tahir2018framework,
  title={A Framework for Spatial Database Explanations},
  author={Tahir, Anique},
  year={2018},
  school={Arizona State University}
}

@inproceedings{yu2019geosparkviz,
  title={GeoSparkViz in action: a data system with built-in support for geospatial visualization},
  author={Yu, Jia and Tahir, Anique and Sarwat, Mohamed},
  booktitle={2019 IEEE 35th International Conference on Data Engineering (ICDE)},
  pages={1992--1995},
  year={2019},
  organization={IEEE}
}

@inproceedings{tahir2019automated,
  title={An Automated Framework for Explaining Facts Extracted From Mobility Datasets},
  author={Tahir, Anique and Sun, Yuhan and Sarwat, Mohamed},
  booktitle={2019 20th IEEE International Conference on Mobile Data Management (MDM)},
  pages={269--278},
  year={2019},
  organization={IEEE},
  selected={true}
}

@article{moraffah2021causal,
  title={Causal inference for time series analysis: Problems, methods and evaluation},
  author={Moraffah, Raha and Sheth, Paras and Karami, Mansooreh and Bhattacharya, Anchit and Wang, Qianru and Tahir, Anique and Raglin, Adrienne and Liu, Huan},
  journal={Knowledge and Information Systems},
  pages={1--45},
  year={2021},
  publisher={Springer}
}

@inproceedings{anique2022covid,
  title={Improving Vaccine Stance Detection by Combining Online and Offline Data},
  author={Tahir, Anique and Cheng, Lu and Sheth, Paras and Liu, Huan},
  booktitle={SBP-BRiMS},
  selected={true},
  year={2022},
}

@inproceedings{tahir2022distributional,
  title={Distributional Shift Adaptation using Domain-Specific Features},
  author={Tahir, Anique and Cheng, Lu and Guo, Ruocheng and Liu, Huan},
  booktitle={2022 IEEE International Conference on Big Data (Big Data)},
  pages={5593--5597},
  year={2022},
  selected={true},
  organization={IEEE}
}

@inproceedings{jeong2023exploring,
  title={Exploring platform migration patterns between twitter and mastodon: A user behavior study},
  author={Jeong, Ujun and Sheth, Paras and Tahir, Anique and Alatawi, Faisal and Bernard, H Russell and Liu, Huan},
  booktitle={Proceedings of the International AAAI Conference on Web and Social Media},
  year={2023}
}

@inproceedings{tahir2023fairness,
  title={Fairness through Aleatoric Uncertainty},
  author={Tahir, Anique and Cheng, Lu and Liu, Huan},
  booktitle={Proceedings of the 32nd ACM International Conference on Information and Knowledge Management},
  year={2023},
  selected={true}
}