text:
---
---

@string{aps = {American Physical Society,}}

@digital{neonwakefieldsingle,
  website={https://stream.resonate.coop/artist/22110/release/electro-magnetic-drones-percussion-1},
  abstract={ an on-going project combining drones and percussion in a live improvised set, using only electro-magnetic interference as a sampling source. The track 'Neon Wakefield' is an edit of a full 5 hour recorded live performance as part of the Wakefield Artwalk in 2018 hosted at the Neon Workshops. Released June 26th exclusively on resonate.coop},
  title={Electro-Magnetic: Drones & Percussion #1},
  author={GRST},
  year={2022},
  publisher={self-released},
  url={https://stream.resonate.coop/artist/22110/release/electro-magnetic-drones-percussion-1},
  preview={cover_credit_David_Lindsay.jpg},
  selected={true}
}

@digital{containerobjectep,
  website={https://grst1.bandcamp.com/album/container-object-ep},
  abstract={Recorded during 2020 using a variety of electro-acoustic techniques and physical modelling. Dedicated to the memory of Ana Karina Jimenez-Villarreal - an activist, artist, and proud anti-Chavista. All sales will go to BIASAN, a Bradford-based grassroots asylum seeker and refugee charity. Mastered by D.Glare at Declared Sound. Released January 11, 2022},
  title={container+=object},
  author={GRST},
  year={2022},
  publisher={self-released},
  url={https://grst1.bandcamp.com/album/container-object-ep},
  preview={container_cover.jpg},
  selected={true}
}

@physical{everthingdrone,
  title={Everything Lasts Forever And Nothing Ever Dies: a compendium of Drone in all it's guises},
  abstract={For their third release, Difficult Art and Music tracked down an international roster of some of the finest artists, musicians and writers working in the field of Drone. With an open brief to merely explore the notion of Drone in the broadest possible terms, contributors responded with a wide range of interpretations. From long-form electro-acoustic works to existential treatise, procedural apps to abstract collages, the artists explored themes of political stagnation, minimal composition, site specificity, and more. By no means an easy collection, ‘Everything Lasts Forever And Nothing Ever Dies’ is a complex study in the aesthetics and philosophies of drone in all of guises. Released on numbered cassette with hand-made fabric cases, complete with exclusive digital-only downloads, a full-colour research magazine / art journal, and an audio-embedded art-print, this exclusive set is limited to 25 copies.},
  author={Various},
  year={2022},
  journal={Difficult Art And Music},
  website={https://difficultartandmusic.bandcamp.com/album/everything-lasts-forever-and-nothing-ever-dies-a-compendium-of-drone-in-all-its-guises},
  preview={daam_cover.jpg}
  }

@article{PhysRev.47.777,
  abbr={PhysRev},
  title={Can Quantum-Mechanical Description of Physical Reality Be Considered Complete?},
  author={Einstein, A. and Podolsky, B. and Rosen, N.},
  abstract={In a complete theory there is an element corresponding to each element of reality. A sufficient condition for the reality of a physical quantity is the possibility of predicting it with certainty, without disturbing the system. In quantum mechanics in the case of two physical quantities described by non-commuting operators, the knowledge of one precludes the knowledge of the other. Then either (1) the description of reality given by the wave function in quantum mechanics is not complete or (2) these two quantities cannot have simultaneous reality. Consideration of the problem of making predictions concerning a system on the basis of measurements made on another system that had previously interacted with it leads to the result that if (1) is false then (2) is also false. One is thus led to conclude that the description of reality as given by a wave function is not complete.},
  journal={Phys. Rev.,},
  volume={47},
  issue={10},
  pages={777--780},
  numpages={0},
  year={1935},
  month={May},
  publisher=aps,
  doi={10.1103/PhysRev.47.777},
  url={http://link.aps.org/doi/10.1103/PhysRev.47.777},
  html={https://journals.aps.org/pr/abstract/10.1103/PhysRev.47.777},
  pdf={example_pdf.pdf}
}

@article{einstein1905molekularkinetischen,
  title={{\"U}ber die von der molekularkinetischen Theorie der W{\"a}rme geforderte Bewegung von in ruhenden Fl{\"u}ssigkeiten suspendierten Teilchen},
  author={Einstein, A.},
  journal={Annalen der physik,},
  volume={322},
  number={8},
  pages={549--560},
  year={1905},
  publisher={Wiley Online Library}
}

@article{einstein1905movement,
  abbr={Ann. Phys.},
  title={Un the movement of small particles suspended in statiunary liquids required by the molecular-kinetic theory 0f heat},
  author={Einstein, A.},
  journal={Ann. Phys.,},
  volume={17},
  pages={549--560},
  year={1905}
}

@article{einstein1905electrodynamics,
  title={On the electrodynamics of moving bodies},
  author={Einstein, A.},
  year={1905}
}

@book{przibram1967letters,
  bibtex_show={true},
  title={Letters on wave mechanics},
  author={Einstein, Albert and Schrödinger, Erwin and Planck, Max and Lorentz, Hendrik Antoon and Przibram, Karl},
  year={1967},
  publisher={Vision},
  preview={wave-mechanics.gif}
}


text:
package _0786

func kthSmallestPrimeFraction(arr []int, k int) []int {
	n := len(arr)
	left, right := 0., 1.
	for {
		mid := (left + right) / 2
		i, count := -1, 0
		x, y := 0, 1

		for j := 1; j < n; j++ {
			for float64(arr[i+1])/float64(arr[j]) < mid {
				i++
				if arr[i]*y > arr[j]*x {
					x, y = arr[i], arr[j]
				}
			}
			count += i + 1
		}

		if count == k {
			return []int{x, y}
		}
		if count < k {
			left = mid
		} else {
			right = mid
		}
	}
}

license: MIT

repository: godcong/leetcode

license_type: permissive

repo_name: godcong/leetcode

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: Go

extension: go


text:
template<FunctionTemplateParams FunctionSeparator typename RetType>
class FunctionClassName : public FunctionBase
{
public:
    FunctionClassName() {}
    FunctionClassName(const FunctionClassName &other)
    { if(!other.empty()) mInvoker = other.mInvoker->clone(); }

    FunctionClassName(RetType(*func)(FunctionParams)) : mInvoker(new FreeFunctionHolder(func)) {}

    template <class ClassType>
    FunctionClassName(ClassType *object, RetType(ClassType::*func)(FunctionParams)) :
        mInvoker(new MemberFunctionHolder<ClassType>(object, func)) {}

    template <class ClassType>
    FunctionClassName(ClassType *object, RetType(ClassType::*func)(FunctionParams) const) :
        mInvoker(new ConstMemberFunctionHolder<ClassType>(object, func)) {}

#ifdef __APPLE__
    FunctionClassName(id object, SEL selector) :
        mInvoker(new ObjectiveCMemberFunctionHolder(object, selector)) {}
#endif

    RetType operator ()(FunctionParams) { return mInvoker->invoke(FunctionArgs); }
    FunctionClassName &operator =(const FunctionClassName &other)
    { if(other.empty()) mInvoker.reset(); else mInvoker = other.mInvoker->clone(); return *this; }

    bool compare(const FunctionBase &otherBase) const
    {
        const FunctionClassName *other = dynamic_cast<const FunctionClassName*>(&otherBase);
        return other && !empty() && !other->empty() && mInvoker->compare(other->mInvoker.get());
    }
    bool operator ==(const FunctionBase &other) const
    {
        return compare(other);
    }

    bool empty() const { return !mInvoker.get(); }

private:
    class FunctionHolderBase;
    typedef std::auto_ptr<FunctionHolderBase> Invoker;

    class FunctionHolderBase
    {
    public:
        FunctionHolderBase() {}
        virtual ~FunctionHolderBase() {}

        virtual RetType invoke(FunctionParams) = 0;
        virtual Invoker clone() = 0;
        virtual bool compare(FunctionHolderBase *) const = 0;

    private:
        FunctionHolderBase(const FunctionHolderBase &);
        void operator =(const FunctionHolderBase &);
    };

    class FreeFunctionHolder : public FunctionHolderBase
    {
    public:
        typedef RetType(*FunctionT)(FunctionParams);
        FreeFunctionHolder(FunctionT func) : FunctionHolderBase(), mFunction(func) {}

        virtual RetType invoke(FunctionParams) { return mFunction(FunctionArgs); }
        virtual Invoker clone() { return Invoker(new FreeFunctionHolder(mFunction)); }
        virtual bool compare(FunctionHolderBase *otherBase) const
        {
            FreeFunctionHolder *other = dynamic_cast<FreeFunctionHolder*>(otherBase);
            return other && mFunction == other->mFunction;
        }

    private:
        FunctionT mFunction;
    };

    template <class ClassType>
    class MemberFunctionHolder : public FunctionHolderBase
    {
    public:
        typedef RetType (ClassType::*FunctionT)(FunctionParams);
        MemberFunctionHolder(ClassType *object, FunctionT func) : mObject(object), mFunction(func) {}

        virtual RetType invoke(FunctionParams) { return (mObject->*mFunction)(FunctionArgs); }
        virtual Invoker clone() { return Invoker(new MemberFunctionHolder(mObject, mFunction)); }
        virtual bool compare(FunctionHolderBase *otherBase) const
        {
            MemberFunctionHolder *other = dynamic_cast<MemberFunctionHolder*>(otherBase);
            return other && mFunction == other->mFunction && mObject == other->mObject;
        }

    private:
        FunctionT mFunction;
        ClassType *mObject;
    };

    template <class ClassType>
    class ConstMemberFunctionHolder : public FunctionHolderBase
    {
    public:
        typedef RetType (ClassType::*FunctionT)(FunctionParams) const;
        ConstMemberFunctionHolder(ClassType *object, FunctionT func) : mObject(object), mFunction(func) {}

        virtual RetType invoke(FunctionParams) { return (mObject->*mFunction)(FunctionArgs); }
        virtual Invoker clone() { return Invoker(new ConstMemberFunctionHolder(mObject, mFunction)); }
        virtual bool compare(FunctionHolderBase *otherBase) const
        {
            ConstMemberFunctionHolder *other = dynamic_cast<ConstMemberFunctionHolder*>(otherBase);
            return other && mFunction == other->mFunction && mObject == other->mObject;
        }

    private:
        FunctionT mFunction;
        ClassType *mObject;
    };

#ifdef __APPLE__
    class ObjectiveCMemberFunctionHolder : public FunctionHolderBase
    {
    public:
        typedef RetType (*FunctionT)(id, SEL FunctionSeparator FunctionParams);
        ObjectiveCMemberFunctionHolder(id object, SEL selector) : mObject(object), mSelector(selector)
        { mFunction = (FunctionT)class_getMethodImplementation(object_getClass(object), selector); }

        virtual RetType invoke(FunctionParams) { return mFunction(mObject, mSelector FunctionSeparator FunctionArgs); }
        virtual Invoker clone() { return Invoker(new ObjectiveCMemberFunctionHolder(mObject, mSelector)); }
        virtual bool compare(FunctionHolderBase *otherBase) const
        {
            ObjectiveCMemberFunctionHolder *other = dynamic_cast<ObjectiveCMemberFunctionHolder*>(otherBase);
            return other && mFunction == other->mFunction && mObject == other->mObject && mSelector == other->mSelector;
        }

    private:
        FunctionT mFunction;
        SEL mSelector;
        id mObject;
    };
#endif

private:
    Invoker mInvoker;
};

template<FunctionTemplateParams FunctionSeparator typename RetType>
class Function<RetType(FunctionTemplateArgs)> : public FunctionClassName<FunctionTemplateArgs FunctionSeparator RetType>
{
public:
    typedef FunctionClassName<FunctionTemplateArgs FunctionSeparator RetType> BaseType;
    Function() : BaseType() {}
    Function(const Function &other) : BaseType(*static_cast<const BaseType*>(&other)) {}

    Function(RetType(*func)(FunctionParams)) : BaseType(func) {}

    template <class ClassType>
    Function(ClassType *object, RetType(ClassType::*func)(FunctionParams)) : BaseType(object, func) {}

    template <class ClassType>
    Function(ClassType *object, RetType(ClassType::*func)(FunctionParams) const) : BaseType(object, func) {}

#ifdef __APPLE__
    Function(id object, SEL selector) : BaseType(object, selector) {}
#endif

    Function &operator =(const Function &other)
    { *static_cast<BaseType*>(this) = other; return *this; }
};

// bind function like in boost::bind
template <FunctionTemplateParams FunctionSeparator class RetType>
Function<RetType(FunctionTemplateArgs)> bind(RetType(*func)(FunctionParams))
{ return Function<RetType(FunctionTemplateArgs)>(func); }

template <FunctionTemplateParams FunctionSeparator class ClassType, class RetType>
Function<RetType(FunctionTemplateArgs)> bind(ClassType *object, RetType(ClassType::*func)(FunctionParams))
{ return Function<RetType(FunctionTemplateArgs)>(object, func); }

template <FunctionTemplateParams FunctionSeparator class ClassType, class RetType>
Function<RetType(FunctionTemplateArgs)> bind(ClassType *object, RetType(ClassType::*func)(FunctionParams) const)
{ return Function<RetType(FunctionTemplateArgs)>(object, func); }

#ifdef __APPLE__
template<FunctionTemplateParams FunctionSeparator typename RetType>
Function<RetType(FunctionTemplateArgs)> bind(id object, SEL selector)
{ return Function<RetType(FunctionTemplateArgs)>(object, selector); }
#endif

repository: gurumobile/RemoteControlGalileoExam

repo_name: gurumobile/RemoteControlGalileoExam

extension: h


text:
package libhoney

import "github.com/honeycombio/libhoney-go/transmission"

// MockOutput implements the Output interface and passes it along to the
// transmission.MockSender.
//
// Deprecated: Please use the transmission.MockSender directly instead.
// It is provided here for backwards compatibility and will be removed eventually.
type MockOutput struct {
	transmission.MockSender
}

func (w *MockOutput) Add(ev *Event) {
	transEv := &transmission.Event{
		APIHost:    ev.APIHost,
		APIKey:     ev.WriteKey,
		Dataset:    ev.Dataset,
		SampleRate: ev.SampleRate,
		Timestamp:  ev.Timestamp,
		Metadata:   ev.Metadata,
		Data:       ev.data,
	}
	w.MockSender.Add(transEv)
}

func (w *MockOutput) Events() []*Event {
	evs := []*Event{}
	for _, ev := range w.MockSender.Events() {
		transEv := &Event{
			APIHost:    ev.APIHost,
			WriteKey:   ev.APIKey,
			Dataset:    ev.Dataset,
			SampleRate: ev.SampleRate,
			Timestamp:  ev.Timestamp,
			Metadata:   ev.Metadata,
		}
		transEv.data = ev.Data
		evs = append(evs, transEv)
	}
	return evs
}

repository: honeycombio/libhoney-go

repo_name: honeycombio/libhoney-go

branch_name: refs/heads/main


text:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
 * @lc app=leetcode.cn id=51 lang=cpp
 *
 * [51] N皇后
 */

// @lc code=start
class Solution {
public:
    vector<vector<string> > ret;
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<int> > counter(n, vector<int>(n, 0));
        // cout << string(n, '.') << endl;
        vector<string> tmp(n, string(n, '.'));

        helper(tmp, counter, 0, n);
        return ret;
    }

    void helper(vector<string> &tmp, vector<vector<int> > &cnt, int row, int n){
        // for(auto s: tmp){
        //     cout << s << endl;
        // }
        // cout << endl;
        if (row == n) {ret.push_back(tmp);return;}
        for(int i = 0; i < n; ++i){
            if (cnt[row][i] == 0){
                for (int j = 0; j < n; ++j) ++cnt[j][i];
                for (int l = 1; l < n; ++l){
                    int ii = row - l, jj = i - l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    ++cnt[ii][jj];
                }
                for (int l = 1; l < n; ++l){
                    int ii = row + l, jj = i + l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    ++cnt[ii][jj];
                }
                for (int l = 1; l < n; ++l){
                    int ii = row - l, jj = i + l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    ++cnt[ii][jj];
                }
                for (int l = 1; l < n; ++l){
                    int ii = row + l, jj = i - l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    ++cnt[ii][jj];
                }
                tmp[row][i] = 'Q';
                helper(tmp, cnt, row + 1, n);
                tmp[row][i] = '.';
                for (int j = 0; j < n; ++j) --cnt[j][i];
                for (int l = 1; l < n; ++l){
                    int ii = row - l, jj = i - l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    --cnt[ii][jj];
                }
                for (int l = 1; l < n; ++l){
                    int ii = row + l, jj = i + l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    --cnt[ii][jj];
                }
                for (int l = 1; l < n; ++l){
                    int ii = row - l, jj = i + l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    --cnt[ii][jj];
                }
                for (int l = 1; l < n; ++l){
                    int ii = row + l, jj = i - l;
                    if (ii >=n || jj >= n || ii < 0 || jj < 0) break;
                    --cnt[ii][jj];
                }
            }
        }
    }
};
// @lc code=end

extension: cpp


text:
DESCRIPTION = "nEo GTK theme - a very fast, high contrast GTK theme"
HOMEPAGE = "http://jmccloud.jm.funpic.de"
AUTHOR = "Jesus McCloud <bernd.pruenster@gmail.com"
RDEPENDS_${PN} += "icon-theme-neo"
RSUGGESTS_${PN} = "elementary-theme-neo e-wm-theme-illume-neo gpe-theme-neo icon-theme-neo"
PACKAGE_ARCH = "all"
LICENSE = "unknown"

SRCREV = "f847105c5ef5d488a4bce0c0a85d572c3509d56f"
PV = "0.3+gitr${SRCPV}"
PR = "r8"

SRC_URI = "git://git.shr-project.org/repo/shr-themes.git;protocol=http;branch=master"

S = "${WORKDIR}/git/gtk/${PN}/"

require gtk-theme.inc

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
// netcat is a console tool to connect to a TCP server
package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"os"
)

// main is the entry point of the program
func main() {

	// Check arguments count
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s <endpoint>\n", os.Args[0])
		return
	}

	// Resolve target server address
	addr, err := net.ResolveTCPAddr("tcp", os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	// Connect to the server
	conn, err := net.DialTCP("tcp", nil, addr)
	if err != nil {
		log.Fatal(err)
	}

	// Create the channel
	done := make(chan struct{})

	// Start the go routine to display data returned by the server
	go func() {
		io.Copy(os.Stdout, conn) // NOTE: ignoring errors
		log.Println("done")
		done <- struct{}{} // signal the main goroutine
	}()

	// Send input data to the server up to the input stream is closed
	mustCopy(conn, os.Stdin)

	// Close the connection
	conn.CloseWrite()

	// wait for background goroutine to finish
	<-done

	// Close the read part of the connection
	conn.CloseRead()
}

// mustCopy copies data between a Reader and a Writer
func mustCopy(dst io.Writer, src io.Reader) {
	if _, err := io.Copy(dst, src); err != nil {
		log.Fatal(err)
	}
}

repository: pperret/GoExercices

repo_name: pperret/GoExercices


text:
DESCRIPTION = "Lightweight web browser capable of handling many of the \
web standards in use today."
HOMEPAGE = "http://www.netsurf-browser.org/"
SECTION = "x11/network"
LICENSE = "GPLv2"
SRCREV = "3859"
PV = "1.1+svnr${SRCPV}"
PR = "r0"

SRC_URI = "svn://svn.netsurf-browser.org/trunk;module=netsurf \
           file://netsurf.desktop"
S = "${WORKDIR}/netsurf"

DEPENDS = "gtk+ (>=2.8) lemon-native re2c-native libxml2 librsvg jpeg \
           libmng curl openssl libglade (>=2.0)"

do_compile() {
        make -f Makefile.unix
}

do_install() {
	install -d ${D}/${bindir}
	install -d ${D}/${libdir}/netsurf
	install -d ${D}/${datadir}/netsurf
	install -d ${D}/${datadir}/applications
	install -d ${D}/${datadir}/pixmaps
        install -m 0755 nsgtk ${D}/${libdir}/netsurf
	install -m 0644 gtk/res/*.css ${D}/${datadir}/netsurf
	install -m 0644 gtk/res/ca-bundle.txt ${D}/${datadir}/netsurf
	install -m 0644 gtk/res/netsurf.glade ${D}/${datadir}/netsurf
	install -m 0644 gtk/res/netsurf-logo.png ${D}/${datadir}/netsurf
	install -m 0644 gtk/res/netsurf.xpm ${D}/${datadir}/netsurf
	install -m 0644 gtk/res/throbber.gif ${D}/${datadir}/netsurf
	install -m 0644 gtk/res/messages ${D}/${datadir}/netsurf
        install -m 0644 gtk/res/netsurf.xpm ${D}/${datadir}/pixmaps
	install -m 0644 ${WORKDIR}/netsurf.desktop ${D}/${datadir}/applications
        cat >${D}/${bindir}/netsurf <<EOF
#!/bin/sh
NETSURFRES=${datadir}/netsurf
export NETSURFRES
exec ${libdir}/netsurf/nsgtk "\$@"
EOF
        chmod 0755 ${D}/${bindir}/netsurf
}


text:
@Misc{Ansible,
  author       = {{Wikipedia}},
  title        = {Ansible (Software)},
  howpublished = {Web page},
  note         = {Online; accessed 10-Mar-2017},
  owner        = {S17-IR-P010},
  url          = {https://en.wikipedia.org/wiki/Ansible_(software)},
}

@Misc{github-cloudmesh-client,
  author       = {Gregor von Laszewski},
  title        = {Cloudmesh/client},
  howpublished = {Code Repository},
  note         = {Accessed: 2017-3-10},
  owner        = {S17-IR-P010},
  url          = {https://github.com/progrium/buildstep},
}

@InProceedings{haar-cascade,
  author    = {Paul Viola and Michael Jones},
  title     = {Rapid object detection using a boosted cascade of simple features},
  booktitle = {Third {IEEE} International Conference on e-Science and Grid Computing (e-Science 2007)},
  year      = {2001},
  address   = {Cambridge, MA},
  month     = dec,
  publisher = {Institute of Electrical and Electronics Engineers ({IEEE})},
  doi       = {10.1109/CVPR.2001.990517},
  owner     = {S17-IR-P010},
  url       = {http://wearables.cc.gatech.edu/paper_of_week/viola01rapid.pdf},
}

extension: bib


text:
package module

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/zieckey/simgo"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
)

var (
	ErrConvert = errors.New("convert error")
	mu         sync.Mutex
)

//解析查询参数
type SearchRequestParams struct {
	Days        []interface{}          `json:"days"`
	Page_size   int32                  `json:"page_size"`
	Page_number int32                  `json:"page_number"`
	Day         string                 `json:"day"`
	Business    string                 `json:"business"`
	Keywords    map[string]interface{} `json:"keywords"`
	Options     map[string]interface{} `json:"options"`
	//	Filters     map[string]interface{} `json:"filters"`
}

func NewSearchRequestParams() *SearchRequestParams {
	return &SearchRequestParams{
		Days:     make([]interface{}, 0),
		Keywords: make(map[string]interface{}),
		Options:  make(map[string]interface{}),
		//		Filters:  make(map[string]interface{}),
	}
}

type QueryBody struct {
	Query *SearchRequestParams `json:"query"`
}

func NewQuery() *QueryBody {
	return &QueryBody{
		Query: NewSearchRequestParams(),
	}
}

type Proxy struct {
	poseidon_search_url string
	Sqp                 *SearchRequestParams
}

func New() *Proxy {
	return &Proxy{
		Sqp: NewSearchRequestParams(),
	}
}

func (p *Proxy) Initialize() error {
	fw := simgo.DefaultFramework
	p.poseidon_search_url, _ = fw.Conf.SectionGet("proxy", "poseidon_search_url")

	simgo.HandleFunc("/service/proxy/mdsearch", p.MdsearchAction, p).Methods("POST")
	p.Sqp = NewSearchRequestParams()
	return nil
}

func (p *Proxy) Uninitialize() error {
	return nil
}

/**
 * multi day search
 * @param  {[type]} this *SearchController) MdsearchAction( [description]
 * @return {[type]}      [description]
 */
func (p *Proxy) MdsearchAction(w http.ResponseWriter, r *http.Request) {
	days, err := p.GetDays(r)
	if err != nil {
		panic(err)
	}
	tasknum := len(days)
	log.Println("tasknum:", tasknum, days)
	log.Println(days)
	//init result channel container
	c := make(chan string, tasknum)

	for _, day := range days {
		if day == "" {
			continue
		}
		go p.send(day, c)
	}

	//recieve result
	//var response_num string
	buf := bytes.NewBuffer([]byte("["))
	for i := 0; i < tasknum; i++ {
		chanr := <-c
		buf.WriteString(chanr)
		if i != (tasknum - 1) {
			buf.WriteString(",")
		}
	}
	buf.WriteString("]")
	w.Write(buf.Bytes())
}

/**
 * send request put data into channel
 * @param  {[type]} this *SearchController) send(day string, c chan string [description]
 * @return {[type]}      [description]
 */
func (p *Proxy) send(day string, c chan string) {
	defer func() {
		if err := recover(); err != nil {
			c <- "request timeout"
		}
	}()
	b, _ := p.GetPostBody(day)
	body := bytes.NewBuffer(b)
	req, err := http.NewRequest("POST", p.poseidon_search_url, body)
	log.Println("send url ", p.poseidon_search_url)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()

	re, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	c <- string(re)
}

func (p *Proxy) getparams(r *http.Request) (*SearchRequestParams, error) {
	jsonenc := json.NewDecoder(r.Body)
	searchParams := make(map[string]interface{}, 1000)
	err := jsonenc.Decode(&searchParams)
	if err != nil {
		return nil, err
	}

	query, ok := searchParams["query"].(map[string]interface{})
	if !ok {
		return nil, ErrConvert
	}

	p.Sqp.Page_size = int32(query["page_size"].(float64))
	p.Sqp.Page_number = int32(query["page_number"].(float64))
	p.Sqp.Business = query["business"].(string)
	p.Sqp.Keywords = query["keywords"].(map[string]interface{})

	p.Sqp.Options = query["options"].(map[string]interface{})
	//Sqp.Filters = query["filters"].(map[string]interface{})

	if query["day"] != nil {
		p.Sqp.Day = query["day"].(string)
	}
	if query["days"] != nil {
		p.Sqp.Days = query["days"].([]interface{})
	}

	return p.Sqp, nil
}

func (p *Proxy) GetDays(r *http.Request) ([]string, error) {
	params, err := p.getparams(r)
	if err != nil {
		return nil, err
	}

	//初始化新容器，断离params大对象
	days := make([]string, len(params.Days))
	for i, day := range params.Days {
		if newday, ok := day.(string); ok {
			days[i] = newday
		}
	}

	return days, nil
}

func (p *Proxy) GetPostBody(day string) ([]byte, error) {
	mu.Lock()
	defer mu.Unlock()
	p.Sqp.Day = day
	query := NewQuery()
	query.Query = p.Sqp
	body, err := json.Marshal(query)
	if err != nil {
		return nil, err
	}

	return body, nil
}


text:
// Copyright 2015 CoreOS, Inc.
//
// 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 main

import (
	"encoding/json"
	"flag"
	"fmt"
	"net"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"
	"time"

	"github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/go-systemd/daemon"
	log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"

	"github.com/coreos/flannel/backend"
	"github.com/coreos/flannel/backend/alloc"
	"github.com/coreos/flannel/backend/hostgw"
	"github.com/coreos/flannel/backend/udp"
	"github.com/coreos/flannel/backend/vxlan"
	"github.com/coreos/flannel/pkg/ip"
	"github.com/coreos/flannel/pkg/task"
	"github.com/coreos/flannel/subnet"
)

type CmdLineOpts struct {
	etcdEndpoints string
	etcdPrefix    string
	etcdKeyfile   string
	etcdCertfile  string
	etcdCAFile    string
	help          bool
	version       bool
	ipMasq        bool
	subnetFile    string
	iface         string
}

var opts CmdLineOpts

func init() {
	flag.StringVar(&opts.etcdEndpoints, "etcd-endpoints", "http://127.0.0.1:4001,http://localhost:2379", "a comma-delimited list of etcd endpoints")
	flag.StringVar(&opts.etcdPrefix, "etcd-prefix", "/coreos.com/network", "etcd prefix")
	flag.StringVar(&opts.etcdKeyfile, "etcd-keyfile", "", "SSL key file used to secure etcd communication")
	flag.StringVar(&opts.etcdCertfile, "etcd-certfile", "", "SSL certification file used to secure etcd communication")
	flag.StringVar(&opts.etcdCAFile, "etcd-cafile", "", "SSL Certificate Authority file used to secure etcd communication")
	flag.StringVar(&opts.subnetFile, "subnet-file", "/run/flannel/subnet.env", "filename where env variables (subnet and MTU values) will be written to")
	flag.StringVar(&opts.iface, "iface", "", "interface to use (IP or name) for inter-host communication")
	flag.BoolVar(&opts.ipMasq, "ip-masq", false, "setup IP masquerade rule for traffic destined outside of overlay network")
	flag.BoolVar(&opts.help, "help", false, "print this message")
	flag.BoolVar(&opts.version, "version", false, "print version and exit")
}

// TODO: This is yet another copy (others found in etcd, fleet) -- Pull it out!
// flagsFromEnv parses all registered flags in the given flagset,
// and if they are not already set it attempts to set their values from
// environment variables. Environment variables take the name of the flag but
// are UPPERCASE, have the given prefix, and any dashes are replaced by
// underscores - for example: some-flag => PREFIX_SOME_FLAG
func flagsFromEnv(prefix string, fs *flag.FlagSet) {
	alreadySet := make(map[string]bool)
	fs.Visit(func(f *flag.Flag) {
		alreadySet[f.Name] = true
	})
	fs.VisitAll(func(f *flag.Flag) {
		if !alreadySet[f.Name] {
			key := strings.ToUpper(prefix + "_" + strings.Replace(f.Name, "-", "_", -1))
			val := os.Getenv(key)
			if val != "" {
				fs.Set(f.Name, val)
			}
		}
	})
}

func writeSubnetFile(sn *backend.SubnetDef) error {
	// Write out the first usable IP by incrementing
	// sn.IP by one
	sn.Net.IP += 1

	dir, name := filepath.Split(opts.subnetFile)
	os.MkdirAll(dir, 0755)

	tempFile := filepath.Join(dir, "."+name)
	f, err := os.Create(tempFile)
	if err != nil {
		return err
	}

	fmt.Fprintf(f, "FLANNEL_SUBNET=%s\n", sn.Net)
	fmt.Fprintf(f, "FLANNEL_MTU=%d\n", sn.MTU)
	_, err = fmt.Fprintf(f, "FLANNEL_IPMASQ=%v\n", opts.ipMasq)
	f.Close()
	if err != nil {
		return err
	}

	// rename(2) the temporary file to the desired location so that it becomes
	// atomically visible with the contents
	return os.Rename(tempFile, opts.subnetFile)
}

func lookupIface() (*net.Interface, net.IP, error) {
	var iface *net.Interface
	var ipaddr net.IP
	var err error

	if len(opts.iface) > 0 {
		if ipaddr = net.ParseIP(opts.iface); ipaddr != nil {
			iface, err = ip.GetInterfaceByIP(ipaddr)
			if err != nil {
				return nil, nil, fmt.Errorf("Error looking up interface %s: %s", opts.iface, err)
			}
		} else {
			iface, err = net.InterfaceByName(opts.iface)
			if err != nil {
				return nil, nil, fmt.Errorf("Error looking up interface %s: %s", opts.iface, err)
			}
		}
	} else {
		log.Info("Determining IP address of default interface")
		if iface, err = ip.GetDefaultGatewayIface(); err != nil {
			return nil, nil, fmt.Errorf("Failed to get default interface: %s", err)
		}
	}

	if ipaddr == nil {
		ipaddr, err = ip.GetIfaceIP4Addr(iface)
		if err != nil {
			return nil, nil, fmt.Errorf("Failed to find IPv4 address for interface %s", iface.Name)
		}
	}

	return iface, ipaddr, nil
}

func newSubnetManager() *subnet.SubnetManager {
	peers := strings.Split(opts.etcdEndpoints, ",")

	cfg := &subnet.EtcdConfig{
		Endpoints: peers,
		Keyfile:   opts.etcdKeyfile,
		Certfile:  opts.etcdCertfile,
		CAFile:    opts.etcdCAFile,
		Prefix:    opts.etcdPrefix,
	}

	for {
		sm, err := subnet.NewSubnetManager(cfg)
		if err == nil {
			return sm
		}

		log.Error("Failed to create SubnetManager: ", err)
		time.Sleep(time.Second)
	}
}

func newBackend(sm *subnet.SubnetManager) (backend.Backend, error) {
	config := sm.GetConfig()

	var bt struct {
		Type string
	}

	if len(config.Backend) == 0 {
		bt.Type = "udp"
	} else {
		if err := json.Unmarshal(config.Backend, &bt); err != nil {
			return nil, fmt.Errorf("Error decoding Backend property of config: %v", err)
		}
	}

	switch strings.ToLower(bt.Type) {
	case "udp":
		return udp.New(sm, config.Backend), nil
	case "alloc":
		return alloc.New(sm), nil
	case "host-gw":
		return hostgw.New(sm), nil
	case "vxlan":
		return vxlan.New(sm, config.Backend), nil
	default:
		return nil, fmt.Errorf("'%v': unknown backend type", bt.Type)
	}
}

func run(sm *subnet.SubnetManager, be backend.Backend, exit chan int) {
	var err error
	defer func() {
		if err == nil || err == task.ErrCanceled {
			exit <- 0
		} else {
			log.Error(err)
			exit <- 1
		}
	}()

	iface, ipaddr, err := lookupIface()
	if err != nil {
		return
	}

	if iface.MTU == 0 {
		err = fmt.Errorf("Failed to determine MTU for %s interface", ipaddr)
		return
	}

	log.Infof("Using %s as external interface", ipaddr)

	sn, err := be.Init(iface, ipaddr)
	if err != nil {
		return
	}

	if opts.ipMasq {
		flannelNet := sm.GetConfig().Network
		if err = setupIPMasq(flannelNet); err != nil {
			return
		}
	}

	writeSubnetFile(sn)
	daemon.SdNotify("READY=1")

	log.Infof("%s mode initialized", be.Name())
	be.Run()
}

func main() {
	// glog will log to tmp files by default. override so all entries
	// can flow into journald (if running under systemd)
	flag.Set("logtostderr", "true")

	// now parse command line args
	flag.Parse()

	if opts.help {
		fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(0)
	}

	if opts.version {
		fmt.Fprintln(os.Stderr, Version)
		os.Exit(0)
	}

	flagsFromEnv("FLANNELD", flag.CommandLine)

	sm := newSubnetManager()
	be, err := newBackend(sm)
	if err != nil {
		log.Info(err)
		os.Exit(1)
	}

	// Register for SIGINT and SIGTERM and wait for one of them to arrive
	log.Info("Installing signal handlers")
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)

	exit := make(chan int)
	go run(sm, be, exit)

	for {
		select {
		case <-sigs:
			// unregister to get default OS nuke behaviour in case we don't exit cleanly
			signal.Stop(sigs)

			log.Info("Exiting...")
			be.Stop()

		case code := <-exit:
			log.Infof("%s mode exited", be.Name())
			os.Exit(code)
		}
	}
}

repository: aaronyangzju/flannel

repo_name: aaronyangzju/flannel


text:
package test

import (
	"os"
	"io"
	"net/http"
	"fmt"
	"github.com/foxiswho/shop-go/module/conf"
	"github.com/foxiswho/shop-go/module/file"
	"github.com/foxiswho/shop-go/util/conv"
	"github.com/foxiswho/shop-go/module/context"
)

type Upload struct {
}

func NewUpload() *Upload {
	return new(Upload)
}
func (x *Upload) UploadIndex(c *context.BaseContext) error {
	//上传令牌 初始化
	maps := make(map[string]interface{})
	maps["type_id"] = 1
	maps["id"] = 1
	maps["aid"] = 1
	cry, err := file.TokeMake(maps)
	if err != nil {
		fmt.Println("令牌加密错误：" + err.Error())
		c.Error(err)
	}
	c.Set("tmpl", "example/test/upload")
	c.Set("data", map[string]interface{}{
		"title": "上传",
		"upload_token": cry,
	})
	return nil
}

func UploadPostIndex(c *context.BaseContext) error {

	//-----------
	// Read file
	//-----------

	// Source
	file, err := c.FormFile("file")
	if err != nil {
		return err
	}
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()
	root_path := "." + conf.Conf.Upload.RootPath
	err = os.MkdirAll(root_path, os.ModePerm)
	fmt.Print("Create Directory=========", root_path)
	if err != nil {
		fmt.Printf("Create Directory ERROR %s", err)
	} else {
		fmt.Print("Create Directory OK! ", root_path)
	}
	// Destination
	dst, err := os.Create(root_path + file.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}

	return c.HTML(http.StatusOK, fmt.Sprintf("
File %s uploaded successfully
", root_path+file.Filename))
}

func UploadMorePostIndex(c *context.BaseContext) error {
	// Multipart form
	form, err := c.MultipartForm()
	if err != nil {
		return err
	}
	files := form.File["files"]
	root_path := "." + conf.Conf.Upload.RootPath
	err = os.MkdirAll(root_path, os.ModePerm)
	fmt.Print("Create Directory=========", root_path)
	if err != nil {
		fmt.Printf("Create Directory ERROR %s", err)
	} else {
		fmt.Print("Create Directory OK! ", root_path)
	}
	for _, file := range files {
		// Source
		src, err := file.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		// Destination
		dst, err := os.Create(root_path + file.Filename)
		if err != nil {
			return err
		}
		defer dst.Close()

		// Copy
		if _, err = io.Copy(dst, src); err != nil {
			return err
		}

	}

	return c.HTML(http.StatusOK, fmt.Sprintf("
Uploaded successfully %d files .
", len(files)))
}

//上传图片 支持 markdown编辑器上传图片
// @router /upload/image [post]
func UploadDbHandler(c *context.BaseContext) error {
	fmt.Println("pppppppppp")
	fmt.Println("pppppppppp")
	fmt.Println("pppppppppp")
	fmt.Println("pppppppppp")
	fmt.Println("pppppppppp")
	pp,err:=c.FormParams()
	fmt.Println("pppppppppp",pp,err)
	//声明
	var maps map[string]interface{}
	t := c.FormValue("t")
	fmt.Println("token=>",c.FormValue("token"))
	token := c.FormValue("token")
	fmt.Println("token=>",token)
	//token 验证
	if len(token) > 0 {
		//解密
		maps, err = file.TokenDeCode(token)
		if err != nil {
			fmt.Println("令牌：" + token)
			fmt.Println("令牌解密失败：" + err.Error())
			token = ""
			c.JSON(http.StatusBadRequest, map[string]interface{}{
				"message": "令牌解密失败：" + err.Error(),
			})
			return nil
		} else {
			fmt.Println("令牌解密", maps)
		}
	}
	//判断是否是 markdown编辑器 输出相应的错误
	if token == "" {
		if t == "markdown" {
			//md := &editor.EditorMd{}
			//md.Message = "令牌错误"
			//md.Success = 0
			//c.JSON(http.StatusBadRequest, map[string]interface{}{
			//	"json": md,
			//})
		} else {
			c.JSON(http.StatusBadRequest, map[string]interface{}{
				"message": "令牌错误：",
			})
		}
		return nil
	}
	//上传文件file表单元素名称
	file_name := "file"
	if t == "markdown" {
		file_name = "editormd-image-file"
	}
	//上传
	f, err := file.Upload(file_name, c.Request(), maps)
	//如果是markdown编辑器返回
	if t == "markdown" {
		//md := &editor.EditorMd{}
		//if err != nil {
		//	md.Message = err.Error()
		//	md.Success = 0
		//} else {
		//	md.Message = "上传成功"
		//	md.Url = f.Http
		//	md.Success = 1
		//}
		c.JSON(http.StatusOK, map[string]interface{}{
			"message": "",
			//"json":    md,
		})
	} else {
		//其他返回
		if err != nil {
			c.JSON(http.StatusBadRequest, map[string]interface{}{
				"message": err.Error(),
			})
		} else {
			m, err := conv.ObjToMap(f)
			if err != nil {
				c.JSON(http.StatusOK, map[string]interface{}{
					"message": "操作成功",
				})
			} else {
				c.JSON(http.StatusOK, map[string]interface{}{
					"message": "操作成功",
					"json":    m,
				})
			}
		}

	}
	return nil
}

repository: foxiswho/shop-go

repo_name: foxiswho/shop-go


text:
package main

import (
	"bufio"
	"bytes"
	"context"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"regexp"
	"strings"

	"github.com/Masterminds/semver"
	"github.com/pkg/errors"
	"github.com/sourcegraph/src-cli/internal/api"
)

func init() {
	usage := `
Create a campaign with the given attributes. If -name or -desc are not specified $EDITOR will open a temporary Markdown file to edit both.

Examples:

  Create a campaign with the given name, branch, description and campaign patch set:

		$ src campaigns create -name="Format Go code" \
		   -desc="This campaign runs gofmt over all Go repositories" \
		   -branch=run-go-fmt \
		   -patchset=Q2FtcGFpZ25QbGFuOjM=

  Create a manual campaign with the given name and description and adds two GitHub pull requests to it:

		$ src campaigns create -name="Migrate to Python 3" \
		   -desc="This campaign tracks all Python 3 migration PRs"
		$ src campaigns add-changesets -campaign=<id-returned-by-previous-command> \
		   -repo-name=github.com/our-org/a-python-repo 5612 7321

`

	flagSet := flag.NewFlagSet("create", flag.ExitOnError)
	usageFunc := func() {
		fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src campaigns create %s':\n", flagSet.Name())
		flagSet.PrintDefaults()
		fmt.Println(usage)
	}
	var (
		nameFlag        = flagSet.String("name", "", "Name of the campaign.")
		descriptionFlag = flagSet.String("desc", "", "Description for the campaign in Markdown.")
		namespaceFlag   = flagSet.String("namespace", "", "ID of the namespace under which to create the campaign. The namespace can be the GraphQL ID of a Sourcegraph user or organisation. If not specified, the ID of the authenticated user is queried and used. (Required)")
		patchsetIDFlag  = flagSet.String("patchset", "", "ID of patch set the campaign should turn into changesets. If no patch set is specified, a campaign is created to which changesets can be added manually.")
		branchFlag      = flagSet.String("branch", "", "Name of the branch that will be created in each repository on the code host. Required for Sourcegraph >= 3.13 when 'patchset' is specified.")

		changesetsFlag = flagSet.Int("changesets", 1000, "Returns the first n changesets per campaign.")

		formatFlag = flagSet.String("f", "{{friendlyCampaignCreatedMessage .}}", `Format for the output, using the syntax of Go package text/template. (e.g. "{{.ID}}: {{.Name}}") or "{{.|json}}")`)
		apiFlags   = api.NewFlags(flagSet)
	)

	handler := func(args []string) error {
		err := flagSet.Parse(args)
		if err != nil {
			return err
		}

		var name, description string

		if *nameFlag == "" || *descriptionFlag == "" {
			editor := &CampaignEditor{
				Name:        *nameFlag,
				Description: *descriptionFlag,
			}

			var err error
			name, description, err = editor.EditAndExtract()
			if err != nil {
				return err
			}
		} else {
			name = *nameFlag
			description = *descriptionFlag
		}

		if name == "" {
			return &usageError{errors.New("campaign name cannot be blank")}
		}

		if description == "" {
			return &usageError{errors.New("campaign description cannot be blank")}
		}

		ctx := context.Background()
		client := cfg.apiClient(apiFlags, flagSet.Output())

		if *patchsetIDFlag != "" {
			// We only need to check for -branch if the Sourcegraph version is >= 3.13
			version, err := getSourcegraphVersion(ctx, client)
			if err != nil {
				return err
			}
			needsBranch, err := sourcegraphVersionCheck(version, ">= 3.13-0", "2020-02-13")
			if err != nil {
				return err
			}

			if needsBranch && *branchFlag == "" {
				return &usageError{errors.New("branch cannot be blank for campaigns with a patch set")}
			}
		}

		var namespace string
		if *namespaceFlag != "" {
			namespace = *namespaceFlag
		} else {
			var currentUserResult struct {
				CurrentUser *User
			}

			if _, err := client.NewQuery(currentUserIDQuery).Do(ctx, &currentUserResult); err != nil {
				return err
			}
			if currentUserResult.CurrentUser.ID == "" {
				return errors.New("Failed to query authenticated user's ID")
			}
			namespace = currentUserResult.CurrentUser.ID
		}

		tmpl, err := parseTemplate(*formatFlag)
		if err != nil {
			return err
		}

		input := map[string]interface{}{
			"name":        name,
			"description": description,
			"namespace":   namespace,
			"patchSet":    api.NullString(*patchsetIDFlag),
			"branch":      *branchFlag,
		}

		var result struct {
			CreateCampaign Campaign
		}

		if ok, err := client.NewRequest(campaignFragment+createcampaignMutation, map[string]interface{}{
			"input":           input,
			"changesetsFirst": api.NullInt(*changesetsFlag),
		}).Do(ctx, &result); err != nil || !ok {
			return err
		}

		return execTemplate(tmpl, result.CreateCampaign)
	}

	// Register the command.
	campaignsCommands = append(campaignsCommands, &command{
		flagSet:   flagSet,
		handler:   handler,
		usageFunc: usageFunc,
	})
}

const currentUserIDQuery = `query CurrentUser { currentUser { id } }`

const createcampaignMutation = `mutation CreateCampaign($input: CreateCampaignInput!, $changesetsFirst: Int) {
  createCampaign(input: $input) {
	... campaign
  }
}
`

const (
	sep    = "------- EVERYTHING BELOW THIS LINE WILL BE IGNORED -------"
	notice = `You are creating a new campaign.
Write a name and description for this campaign in this file.
The first line of text is the name and the rest is the description.`
)

type CampaignEditor struct {
	Name        string
	Description string
}

func (e *CampaignEditor) EditAndExtract() (string, string, error) {
	f, err := ioutil.TempFile("", "new-campaign*.md")
	if err != nil {
		return "", "", err
	}
	defer os.Remove(f.Name())

	err = e.writeTemplate(f)
	if err != nil {
		return "", "", err
	}

	err = openInEditor(f.Name())
	if err != nil {
		return "", "", errors.Wrap(err, "Failed to open text editor to edit campaign")
	}

	content, err := extractContent(f.Name())
	if err != nil {
		return "", "", err
	}

	var name, description string

	parts := strings.SplitN(content, "\n\n", 2)
	if len(parts) >= 1 {
		name = strings.TrimSpace(strings.Replace(parts[0], "\n", " ", -1))
	}
	if len(parts) >= 2 {
		description = strings.TrimSpace(parts[1])
	}

	return name, description, nil
}

func (e *CampaignEditor) writeTemplate(f *os.File) error {
	template := e.Name + "\n\n" + e.Description
	template += "\n\n" + sep
	template += "\n\n" + notice

	_, err := f.WriteString(template)
	return err
}

func extractContent(file string) (string, error) {
	fileContent, err := ioutil.ReadFile(file)
	if err != nil {
		return "", err
	}

	trimmed := bytes.TrimSpace(fileContent)

	scanner := bufio.NewScanner(bytes.NewReader(trimmed))

	content := []string{}

	for scanner.Scan() {
		line := scanner.Text()
		if line == sep {
			break
		}
		content = append(content, line)
	}
	if err = scanner.Err(); err != nil {
		return "", err
	}

	return strings.Join(content, "\n"), nil
}

func openInEditor(file string) error {
	editor := os.Getenv("EDITOR")
	if editor == "" {
		return errors.New("$EDITOR is not set")
	}

	cmd := exec.Command(editor, file)

	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	tty, err := os.OpenFile("/dev/tty", os.O_RDONLY, 0660)
	if err == nil {
		cmd.Stdin = tty
	}

	return cmd.Run()
}

const sourcegraphVersionQuery = `query SourcegraphVersion {
  site {
    productVersion
  }
}
`

func getSourcegraphVersion(ctx context.Context, client api.Client) (string, error) {
	var sourcegraphVersion struct {
		Site struct {
			ProductVersion string
		}
	}

	_, err := client.NewQuery(sourcegraphVersionQuery).Do(ctx, &sourcegraphVersion)
	return sourcegraphVersion.Site.ProductVersion, err
}

func sourcegraphVersionCheck(version, constraint, minDate string) (bool, error) {
	if version == "dev" || version == "0.0.0+dev" {
		return true, nil
	}

	buildDate := regexp.MustCompile(`^\d+_(\d{4}-\d{2}-\d{2})_[a-z0-9]{7}$`)
	matches := buildDate.FindStringSubmatch(version)
	if len(matches) > 1 {
		return matches[1] >= minDate, nil
	}

	c, err := semver.NewConstraint(constraint)
	if err != nil {
		return false, nil
	}

	v, err := semver.NewVersion(version)
	if err != nil {
		return false, err
	}
	return c.Check(v), nil
}


text:
# Auto-Generated by cargo-bitbake 0.3.9
#
inherit cargo

# If this is git based prefer versioned ones if they exist
# DEFAULT_PREFERENCE = "-1"

# how to get os-config could be as easy as but default to a git checkout:
# SRC_URI += "crate://crates.io/os-config/0.0.14"
SRC_URI += "git://git@github.com/resin-os/os-config.git;protocol=ssh"
SRCREV = "ac44cb7b3c853ec0ad5ad8fdac6d3b2ef8a0ba8a"
S = "${WORKDIR}/git"
CARGO_SRC_DIR=""
PV_append = ".AUTOINC+ac44cb7b3c"

# please note if you have entries that do not begin with crate://
# you must change them to how that package can be fetched
SRC_URI += " \
crate://crates.io/adler32/1.0.2 \
crate://crates.io/aho-corasick/0.6.4 \
crate://crates.io/assert_cli/0.5.4 \
crate://crates.io/atty/0.2.6 \
crate://crates.io/backtrace-sys/0.1.16 \
crate://crates.io/backtrace/0.3.5 \
crate://crates.io/base64/0.9.0 \
crate://crates.io/bitflags/0.9.1 \
crate://crates.io/bitflags/1.0.1 \
crate://crates.io/build_const/0.2.0 \
crate://crates.io/bytecount/0.2.0 \
crate://crates.io/byteorder/1.2.1 \
crate://crates.io/bytes/0.4.6 \
crate://crates.io/cargo_metadata/0.3.3 \
crate://crates.io/cc/1.0.4 \
crate://crates.io/cfg-if/0.1.2 \
crate://crates.io/clap/2.31.2 \
crate://crates.io/colored/1.6.0 \
crate://crates.io/core-foundation-sys/0.2.3 \
crate://crates.io/core-foundation/0.2.3 \
crate://crates.io/crc/1.7.0 \
crate://crates.io/dbus/0.6.1 \
crate://crates.io/difference/1.0.0 \
crate://crates.io/dtoa/0.4.2 \
crate://crates.io/encoding_rs/0.7.2 \
crate://crates.io/env_logger/0.5.6 \
crate://crates.io/environment/0.1.1 \
crate://crates.io/error-chain/0.11.0 \
crate://crates.io/foreign-types-shared/0.1.1 \
crate://crates.io/foreign-types/0.3.2 \
crate://crates.io/fuchsia-zircon-sys/0.3.3 \
crate://crates.io/fuchsia-zircon/0.3.3 \
crate://crates.io/futures-cpupool/0.1.8 \
crate://crates.io/futures/0.1.18 \
crate://crates.io/glob/0.2.11 \
crate://crates.io/hex/0.3.2 \
crate://crates.io/httparse/1.2.4 \
crate://crates.io/humantime/1.1.1 \
crate://crates.io/hyper-tls/0.1.2 \
crate://crates.io/hyper/0.11.21 \
crate://crates.io/idna/0.1.4 \
crate://crates.io/iovec/0.1.2 \
crate://crates.io/itoa/0.3.4 \
crate://crates.io/kernel32-sys/0.2.2 \
crate://crates.io/language-tags/0.2.2 \
crate://crates.io/lazy_static/0.2.11 \
crate://crates.io/lazy_static/1.0.0 \
crate://crates.io/lazycell/0.6.0 \
crate://crates.io/libc/0.2.37 \
crate://crates.io/libdbus-sys/0.1.3 \
crate://crates.io/libflate/0.1.14 \
crate://crates.io/log/0.3.9 \
crate://crates.io/log/0.4.1 \
crate://crates.io/maplit/1.0.1 \
crate://crates.io/matches/0.1.6 \
crate://crates.io/memchr/2.0.1 \
crate://crates.io/mime/0.3.5 \
crate://crates.io/mime_guess/2.0.0-alpha.4 \
crate://crates.io/mio/0.6.13 \
crate://crates.io/miow/0.2.1 \
crate://crates.io/native-tls/0.1.5 \
crate://crates.io/net2/0.2.32 \
crate://crates.io/num-traits/0.2.0 \
crate://crates.io/num_cpus/1.8.0 \
crate://crates.io/openssl-sys/0.9.27 \
crate://crates.io/openssl/0.10.5 \
crate://crates.io/openssl/0.9.24 \
crate://crates.io/percent-encoding/1.0.1 \
crate://crates.io/phf/0.7.21 \
crate://crates.io/phf_codegen/0.7.21 \
crate://crates.io/phf_generator/0.7.21 \
crate://crates.io/phf_shared/0.7.21 \
crate://crates.io/pkg-config/0.3.9 \
crate://crates.io/pulldown-cmark/0.1.2 \
crate://crates.io/quick-error/1.2.1 \
crate://crates.io/quote/0.3.15 \
crate://crates.io/rand/0.3.22 \
crate://crates.io/rand/0.4.2 \
crate://crates.io/redox_syscall/0.1.37 \
crate://crates.io/redox_termios/0.1.1 \
crate://crates.io/regex-syntax/0.4.2 \
crate://crates.io/regex/0.2.6 \
crate://crates.io/relay/0.1.1 \
crate://crates.io/remove_dir_all/0.3.0 \
crate://crates.io/reqwest/0.8.5 \
crate://crates.io/rustc-demangle/0.1.7 \
crate://crates.io/safemem/0.2.0 \
crate://crates.io/same-file/0.1.3 \
crate://crates.io/schannel/0.1.10 \
crate://crates.io/scoped-tls/0.1.0 \
crate://crates.io/security-framework-sys/0.1.16 \
crate://crates.io/security-framework/0.1.16 \
crate://crates.io/semver-parser/0.7.0 \
crate://crates.io/semver/0.8.0 \
crate://crates.io/serde/1.0.27 \
crate://crates.io/serde_derive/1.0.27 \
crate://crates.io/serde_derive_internals/0.19.0 \
crate://crates.io/serde_json/1.0.10 \
crate://crates.io/serde_urlencoded/0.5.1 \
crate://crates.io/siphasher/0.2.2 \
crate://crates.io/skeptic/0.13.2 \
crate://crates.io/slab/0.3.0 \
crate://crates.io/slab/0.4.0 \
crate://crates.io/smallvec/0.2.1 \
crate://crates.io/syn/0.11.11 \
crate://crates.io/synom/0.11.3 \
crate://crates.io/take/0.1.0 \
crate://crates.io/tempdir/0.3.6 \
crate://crates.io/termcolor/0.3.5 \
crate://crates.io/termion/1.5.1 \
crate://crates.io/textwrap/0.9.0 \
crate://crates.io/thread_local/0.3.5 \
crate://crates.io/time/0.1.39 \
crate://crates.io/tokio-core/0.1.12 \
crate://crates.io/tokio-io/0.1.5 \
crate://crates.io/tokio-proto/0.1.1 \
crate://crates.io/tokio-service/0.1.0 \
crate://crates.io/tokio-tls/0.1.4 \
crate://crates.io/unicase/1.4.2 \
crate://crates.io/unicase/2.1.0 \
crate://crates.io/unicode-bidi/0.3.4 \
crate://crates.io/unicode-normalization/0.1.5 \
crate://crates.io/unicode-width/0.1.4 \
crate://crates.io/unicode-xid/0.0.4 \
crate://crates.io/unindent/0.1.2 \
crate://crates.io/unreachable/1.0.0 \
crate://crates.io/url/1.7.0 \
crate://crates.io/utf8-ranges/1.0.0 \
crate://crates.io/uuid/0.5.1 \
crate://crates.io/vcpkg/0.2.2 \
crate://crates.io/version_check/0.1.3 \
crate://crates.io/void/1.0.2 \
crate://crates.io/walkdir/1.0.7 \
crate://crates.io/winapi-build/0.1.1 \
crate://crates.io/winapi-i686-pc-windows-gnu/0.4.0 \
crate://crates.io/winapi-x86_64-pc-windows-gnu/0.4.0 \
crate://crates.io/winapi/0.2.8 \
crate://crates.io/winapi/0.3.4 \
crate://crates.io/wincolor/0.1.6 \
crate://crates.io/ws2_32-sys/0.2.1 \
"

# FIXME: update generateme with the real MD5 of the license file
LIC_FILES_CHKSUM=" \
file://Apache-2.0;md5=86d3f3a95c324c9479bd8986968f4327 \
"

SUMMARY = "resinOS configuration tool"
HOMEPAGE = "https://github.com/resin-os/os-config"
LICENSE = "Apache-2.0"

# includes this file if it exists but does not fail
# this is useful for anything you may want to override from
# what cargo-bitbake generates.
include os-config-${PV}.inc
include os-config.inc

repository: bshibley/meta-resin

repo_name: bshibley/meta-resin


text:
@article{biswas2019trend,
	title={Trend of child marriage in Bangladesh: A reflection on significant socioeconomic factors},
	author={Biswas, Raaj Kishore and Khan, Jahidur Rahman and Kabir, Enamul},
	journal={Children and Youth Services Review},
	year={2019},
	publisher={Elsevier}
}

repository: Raaj-Kishore-Biswas/academic-kickstart

repo_name: Raaj-Kishore-Biswas/academic-kickstart


text:
@article{Kri63,
  added-at = {2007-11-02T23:09:02.000+0100},
  author = {Kripke, S.},
  biburl = {http://www.bibsonomy.org/bibtex/229a6d29b497e81ff703f4f8e5ccdf009/bsmyth},
  description = {all-bibs-cleaned.bib},
  interhash = {e656a632b816cd5c661b015201e0e88f},
  intrahash = {29a6d29b497e81ff703f4f8e5ccdf009},
  journal = {Acta Phil. Fennica},
  keywords = {imported},
  pages = {83--94},
  timestamp = {2007-11-02T23:09:04.000+0100},
  title = {{Semantical Considerations on Modal Logic}},
  volume = 16,
  year = 1963
}

@BOOK{Tufte2006,
	author = {Edward R. Tufte},
	title = {Beautiful Evidence},
	year = {2006},
	publisher = {Graphics Press, {LLC}},
	month = {May},
	edition = {First},
	place = {Cheshire, Connecticut},
	isbn = {0-9613921-7-7}
}

@BOOK{Tufte2001,
	author = {Edward R. Tufte},
	title = {The Visual Display of Quantitative Information},
	publisher = {Graphics Press},
	year = {2001},
	address = {Cheshire, Connecticut},
	isbn = {0-9613921-4-2}
}

@BOOK{Tufte1990,
	author = {Edward R. Tufte},
	title = {Envisioning Information},
	publisher = {Graphics Press},
	year = {1990},
	address = {Cheshire, Connecticut},
	isbn = {0-9613921-1-8}
}

@BOOK{Tufte1997,
	author = {Edward R. Tufte},
	title = {Visual Explanations},
	publisher = {Graphics Press},
	year = {1997},
	address = {Cheshire, Connecticut},
	isbn = {0-9613921-2-6}
}

@BOOK{Bringhurst2005,
	author = {Robert Bringhurst},
	title = {The Elements of Typography},
	publisher = {Hartley \& Marks},
	year = {2005},
	edition = {3.1},
	isbn = {0-88179-205-5}
}

@BOOK{Mittelbach2004,
	author = {Frank Mittelbach and Michel Goossens},
	title = {The \LaTeX\ Companion},
	publisher = {Addison--Wesley},
	year = {2004},
	edition = {Second},
	isbn = {0-201-36299-6}
}

@MISC{pkg-geometry,
    author = {Hideo Umeki},
    title = {The \texttt{geometry} package},
    year = {2008},
    month = dec,
    howpublished = {\url{http://ctan.org/pkg/geometry}}
}

repository: fromeroj/iimas

repo_name: fromeroj/iimas

gha_language: TeX


text:
package goline
/*
 *  Filename:    question_test.go
 *  Author:      Bryan Matsuo <bmatsuo@soe.ucsc.edu>
 *  Created:     Sat Aug 13 02:30:29 PDT 2011
 *  Description:
 *  Usage:       gotest
 */
import (
    "testing"
)

func testOptions(T *testing.T) {
    q := newQuestion(String)
    if q.Case != NilCase {
        T.Errorf("New String answer's case is not nil")
    }
}

func testGood(T *testing.T, q *Question, name, in string, v interface{}) error {
    t := q.Type()
    err := q.parse(in)
    if err != nil {
        T.Errorf("%s %s parse failed %s", name, t.String(), err.Error())
    } else if q.val != v {
        T.Errorf("Parsed value != expected value (%#v != %#v)", q.val, v)
    }
    return err
}
func testBad(T *testing.T, q *Question, name, in string) error {
    t := q.Type()
    err := q.parse(in)
    if err == nil {
        T.Errorf("%s improper %s parse succeded!", name, t.String())
    }
    if q.val != nil {
        T.Errorf("Parsed %s value != nil (%#v != nil)", t.String(), q.val)
    }
    return err
}

func TestQuestionInt(T *testing.T) {
    q := newQuestion(Int)
    // Standard parse tests
    testGood(T, q, "Simple", "1234", int64(1234))
    testBad(T, q, "Simple", "123JumpStreet")
    // Ranged parse tests
    q.In(IntRange{int64(-3), int64(10)})
    testGood(T, q, "In-range", "5", int64(5))
    testGood(T, q, "Edge-low", "-3", int64(-3))
    testGood(T, q, "Edge-high", "10", int64(10))
    testBad(T, q, "Low", "-4")
    testBad(T, q, "High", "11")
}

func TestQuestionUint(T *testing.T) {
    q := newQuestion(Uint)
    // Standard parse tests
    testGood(T, q, "Simple", "1234", uint64(1234))
    testGood(T, q, "Trimmed", " 4321  \n", uint64(4321))
    testBad(T, q, "Simple", "123JumpStreet")
    // Ranged parse tests
    q.In(UintRange{uint64(1), uint64(10)})
    testGood(T, q, "In-range", "5", uint64(5))
    testGood(T, q, "Edge-low", "1", uint64(1))
    testGood(T, q, "Edge-high", "10", uint64(10))
    testBad(T, q, "Low", "0")
    testBad(T, q, "High", "11")
}

func TestQuestionFloat(T *testing.T) {
    q := newQuestion(Float)
    // NOTE: Only use floating point number with a lossless 64bit representation.
    // Standard parse tests
    testGood(T, q, "Int", "1234", float64(1234))
    testGood(T, q, "Simple", "-12.75", float64(-12.75))
    testGood(T, q, "Scientific", "123.5e+1", float64(1235.0))
    testBad(T, q, "Complex", "123.5+i5")
    // Ranged parse tests
    q.In(FloatRange{float64(1), float64(10)})
    testGood(T, q, "In-range", "5", float64(5))
    testGood(T, q, "Edge-low", "1", float64(1))
    testGood(T, q, "Edge-high", "10", float64(10))
    testBad(T, q, "Low", "0")
    testBad(T, q, "High", "11")
}

func TestQuestionString(T *testing.T) {
    q := newQuestion(String)
    // Standard parse tests
    testGood(T, q, "Simple", "1234", "1234")
    q.Whitespace &= ^Trim
    testGood(T, q, "No trim default", " 4321  \n", " 4321  \n")
    q.Whitespace |= Collapse
    testGood(T, q, "Collapse", " 4321  \tabc  \n", " 4321 abc \n")
    // Ranged parse tests
    q.In(StringRange{"aaa", "zzz"})
    testGood(T, q, "In-range", "tidoeids", "tidoeids")
    testGood(T, q, "Edge-low", "aaa", "aaa")
    testGood(T, q, "Edge-high", "zzz", "zzz")
    testBad(T, q, "Low", "ZZZ")
    testBad(T, q, "High", "{")
    q.In(StringSet([]string{"abc", "def", "ghi"}))
    testGood(T, q, "In set", "def", "def")
    testBad(T, q, "Not in set", "blah")
}

repository: mattbaird/goline

repo_name: mattbaird/goline


text:
@BOOK{ Knuth:TeX,
  author   = "Knuth, Donald E.",
  title    = "The {T}e{X} book",
  publisher= "Addison-Wesley",
  year     = 1984
}

@BOOK{ Lamport:LaTeX,
  author    = "Lamport, Leslie",
  title     = "{LaTeX}: A Document Preparation System (2nd Edition)",
  publisher = "Addison-Wesley",
  year      = 1994,
  note      = "See also \cite{Knuth:TeX}."
}

@INBOOK{ Grandstrand,
  author   = {O. Grandstrand},
  title    = {Innovation and Intellectual Property Rights},
  chapter  = 10,
  crossref = {Fberg04}
}

@BOOK{ Fberg04,
  editor    = {J. Fagerberg and D.C. Mowery and R.R. Nelson},
  title     = {Oxford Handbook of Innovation},
  booktitle = {Oxford Handbook of Innovation},
  publisher = {Oxford University Press},
  address   = {Oxford},
  volume    = 1,
  year      = 2004
}

@BOOK{ Klote,
  author    = "Klote, John H.l Milke, James A.",
  title     = "The Handbook of Smoke Control Engineering",
  year      = "2012",
  publisher = "ASHRAE",
  address   = "Atlanta, GA"
}

@incollection{Xincollection,
	author	= "",
	title	= "",
	booktitle= "",
	publisher= "",
	%editor	= "",
	%volume	= "",
	%number	= "",
	%series	= "",
	%type	= "",
	%chapter= "",
	%pages	= "",
	%address= "",
	%edition= "",
	year	= "",
	%month	= "",
	%note	= "",
}

	@manual{ NFPA92,
	title		= NFPA 92: Standard for Smoke Control Systems,
	%author		= "",
	%organization	= NPFA,
	%address	= "",
	%edition	= "",
	year		= 2012,
	%month		= "",
	%note		= "",
}

branch_name: refs/heads/authoring


text:
package components

import "github.com/scipipe/scipipe"

type Concatenator struct {
	scipipe.Process
	name     string
	In       *scipipe.FilePort
	Out      *scipipe.FilePort
	OutPath  string
	workflow *scipipe.Workflow
}

func NewConcatenator(wf *scipipe.Workflow, name string, outPath string) *Concatenator {
	concat := &Concatenator{
		name:     name,
		In:       scipipe.NewFilePort(),
		Out:      scipipe.NewFilePort(),
		OutPath:  outPath,
		workflow: wf,
	}
	wf.AddProc(concat)
	return concat
}

func (proc *Concatenator) Name() string {
	return proc.name
}

func (proc *Concatenator) Run() {
	defer proc.Out.Close()
	go proc.In.RunMergeInputs()

	outFt := scipipe.NewInformationPacket(proc.OutPath)
	outFh := outFt.OpenWriteTemp()
	for ft := range proc.In.InChan {
		fr := NewFileReader(proc.workflow, proc.Name()+"_filereader")
		go func() {
			defer close(fr.FilePath)
			fr.FilePath <- ft.GetPath()
		}()
		for line := range fr.OutLine {
			scipipe.Debug.Println("Processing ", line, "...")
			outFh.Write([]byte(line))
		}
	}
	outFh.Close()
	outFt.Atomize()
	proc.Out.Send(outFt)
}

func (proc *Concatenator) IsConnected() bool {
	isConnected := true
	if !proc.In.IsConnected() {
		scipipe.Error.Println("Concatenator: Port 'In' is not connected!")
		isConnected = false
	}
	if !proc.Out.IsConnected() {
		scipipe.Error.Println("Concatenator: Port 'Out' is not connected!")
		isConnected = false
	}
	return isConnected
}

repository: dongensi/scipipe

repo_name: dongensi/scipipe


text:
require xorg-driver-video.inc
DESCRIPTION = "X.Org X server -- MSM display driver"
PE = "1"
PV = "1.1.0+${PR}+gitr${SRCREV}"
PR = "${INC_PR}.0"

SRC_URI = "git://codeaurora.org/quic/xwin/xf86-video-msm.git;protocol=git;branch=chromium \
           file://compile_cfbbd17f0d4ab0f30915594d74e1b2b12c4ff8a1.patch \
           file://kgsl_drm.h "
SRC_URI_append_htcdream = "file://no_neon_cfbbd17f0d4ab0f30915594d74e1b2b12c4ff8a1.patch"

SRCREV = "cfbbd17f0d4ab0f30915594d74e1b2b12c4ff8a1"
S = "${WORKDIR}/git"

do_compile_prepend() {
        install -d ${S}/src/linux
        install -d ${S}/src/drm
        install -m 0644 ${STAGING_KERNEL_DIR}/include/linux/msm_mdp.h ${S}/src/linux/
        install -m 0644 ${WORKDIR}/kgsl_drm.h ${S}/src/drm/
}

PACKAGE_ARCH = "${MACHINE_ARCH}"

ARM_INSTRUCTION_SET = "arm"

CFLAGS += " -I${STAGING_INCDIR}/xorg "
CFLAGS += " -Wno-error "


text:
file(REMOVE_RECURSE
  "CMakeFiles/template_filter_pdgen"
  "template_filter.plugindescription"
)

# Per-language clean rules from dependency scanning.
foreach(lang )
  include(CMakeFiles/template_filter_pdgen.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

extension: cmake


text:
/* CC0 - free software.
To the extent possible under law, all copyright and related or neighboring
rights to this work are waived. See the LICENSE file for more information. */

package base32k

import (
	"bytes"
	"fmt"
	"math/rand"
	"testing"
)

// 00000000 11111111 00000000 11111111 10101010 01010101 10101010 01010101 11111111 10100101 01011010 11110000 00001111 10101010 01010101 00000000
var srcData = []byte{0x00, 0xff, 0x00, 0xff, 0xaa, 0x55, 0xaa, 0x55, 0xff, 0xa5, 0x5a, 0xf0, 0x0f, 0xaa, 0x55, 0x00}

var encodeExpectedBytes = map[int][]byte{
	//    0     1     2     3     4     5     6     7     8     9     10    11    12    13    14    15    16    17    18    19    20    21    22    23    24    25    26    27
	// ... .. ..00 00 0000  010101011010101 000001111111100 000101101010100 101111111110101 010110101010010 101011010101011 111111000000001 111111100000000
	16: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe5, 0x9a, 0xab, 0xe4, 0xb5, 0x92, 0xe5, 0xbf, 0xb5, 0xe8, 0xad, 0x94, 0xe8, 0x8f, 0xbc, 0xe4, 0xab, 0x95, 0xe8, 0x80, 0x80, 0x69},
	// 010101011010101 000001111111100 000101101010100 101111111110101 010110101010010 101011010101011 111111000000001 111111100000000
	15: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe5, 0x9a, 0xab, 0xe4, 0xb5, 0x92, 0xe5, 0xbf, 0xb5, 0xe8, 0xad, 0x94, 0xe8, 0x8f, 0xbc, 0xe4, 0xab, 0x95},
	// ...111111110101 010110101010010 101011010101011 111111000000001 111111100000000
	9: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe5, 0x9a, 0xab, 0xe4, 0xb5, 0x92, 0xe8, 0xbf, 0xb5, 0x6d},
	// ...........0101 010110101010010 101011010101011 111111000000001 111111100000000
	8: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe5, 0x9a, 0xab, 0xe4, 0xb5, 0x92, 0xe8, 0x80, 0x85, 0x65},
	// ....10101010010 101011010101011 111111000000001 111111100000000
	7: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe5, 0x9a, 0xab, 0xe8, 0x95, 0x92, 0x6c},
	// ............010 101011010101011 111111000000001 111111100000000
	6: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe5, 0x9a, 0xab, 0xe8, 0x80, 0x82, 0x64},
	// .....1010101011 111111000000001 111111100000000
	5: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe8, 0x8a, 0xab, 0x6b},
	// .............11 111111000000001 111111100000000
	4: {0xe7, 0xbc, 0x80, 0xe7, 0xb8, 0x81, 0xe8, 0x80, 0x83, 0x63},
	// ......000000001 111111100000000
	3: {0xe7, 0xbc, 0x80, 0xe8, 0x80, 0x81, 0x6a},
	// ..............1 111111100000000
	2: {0xe7, 0xbc, 0x80, 0xe8, 0x80, 0x81, 0x62},
	// .......00000000
	1: {0xe8, 0x80, 0x80, 0x69},
	0: {},
}

var encodeExpectedStrings = map[int]string{
	16: "缀縁嚫䵒念譔菼䫕耀i",
	15: "缀縁嚫䵒念譔菼䫕",
	9:  "缀縁嚫䵒迵m",
	8:  "缀縁嚫䵒者e",
	7:  "缀縁嚫蕒l",
	6:  "缀縁嚫耂d",
	5:  "缀縁芫k",
	4:  "缀縁考c",
	3:  "缀老j",
	2:  "缀老b",
	1:  "耀i",
	0:  "",
}

func TestEncode(t *testing.T) {
	for n, expected := range encodeExpectedBytes {
		t.Run(fmt.Sprintf("data_size_%d", n), func(t *testing.T) {
			encoded := Encode(srcData[:n])
			if len(encoded) < len(expected) {
				t.Error(fmt.Sprintf("[%d] Encoded too short: %d (need: %d)", n, len(encoded), len(expected)))
				return
			}
			if len(encoded) > len(expected) {
				t.Error(fmt.Sprintf("[%d] Encoded too long: %d (need: %d), extra: %x", n, len(encoded), len(expected), encoded[len(expected):]))
				return
			}
			for i, b := range expected {
				if encoded[i] != b {
					t.Error(fmt.Sprintf("[%d](%d) Expected: %0.8b (0x%0.2x) got: %0.8b (0x%0.2x)", n, i, b, b, encoded[i], encoded[i]))
				}
			}
		})
	}
}

func TestEncodeToString(t *testing.T) {
	for n, expectedString := range encodeExpectedStrings {
		t.Run(fmt.Sprintf("string_length_%d", n), func(t *testing.T) {
			encodedString := EncodeToString(srcData[:n])
			if encodedString != expectedString {
				t.Error(fmt.Sprintf("[%d] String '%s' doesn't match expected string '%s'\n", n, encodedString, expectedString))
			}
		})
	}
}

func TestDecode(t *testing.T) {
	for n, srcBytes := range encodeExpectedBytes {
		t.Run(fmt.Sprintf("data_size_%d", n), func(t *testing.T) {
			decoded, err := Decode(srcBytes)
			if err != nil {
				t.Error("Error in Decode:", err)
			}
			expected := srcData[:n]
			if len(decoded) < len(expected) {
				t.Error(fmt.Sprintf("[%d] Decoded too short: %d (need: %d)", n, len(decoded), len(expected)))
				return
			}
			if len(decoded) > len(expected) {
				t.Error(fmt.Sprintf("[%d] Decoded too long: %d (need: %d)", n, len(decoded), len(expected)))
				return
			}
			for i, b := range expected {
				if decoded[i] != b {
					t.Error(fmt.Sprintf("[%d](%d) Expected: %0.8b (%0.2x) got: %0.8b (%0.2x)", n, i, b, b, decoded[i], decoded[i]))
				}
			}
		})
	}
}

func TestDecodeFromString(t *testing.T) {
	for n, decodeSrcString := range encodeExpectedStrings {
		t.Run(fmt.Sprintf("string_length_%d", n), func(t *testing.T) {
			decoded, err := DecodeFromString(decodeSrcString)
			if err != nil {
				t.Error(fmt.Sprintf("[%d]Error while decoding: %s", n, err))
			}
			for i, b := range decoded {
				if b != srcData[i] {
					t.Error(fmt.Sprintf("[%d](%d) Expected 0x%0.2x, got 0x%0.2x\n", n, i, decoded, srcData[i]))
				}
			}
		})
	}
}

func TestGetRuneFromBytes(t *testing.T) {
	data := []byte{0xf0, 0xa5, 0x5a, 0xa5}
	// 11110000 10100101 01011010 10100101

	// 0010 0101 1111 0000 => 25f0
	// 0101 0010 1111 1000 => 52f8
	// 0010 1001 0111 1100 => 297c
	// 0101 0100 1011 1110 => 54be
	// 0010 1010 0101 1111 => 2a5f
	// 0101 0101 0010 1111 => 552f
	// 0110 1010 1001 0111 => 6a97
	// 0011 0101 0100 1011 => 354b

	i := uint(0)
	expectedIndices := []uint{1, 2, 2, 2, 2, 2, 2, 2}
	expectedBits := []uint{7, 0, 1, 2, 3, 4, 5, 6}
	expectedValues := []uint16{0x25f0, 0x52f8, 0x297c, 0x54be, 0x2a5f, 0x552f, 0x6a97, 0x354b}
	for _, b := range []uint{0, 1, 2, 3, 4, 5, 6, 7} {
		t.Run(fmt.Sprintf("bit_offset_%d", b), func(t *testing.T) {
			value, newIndex, newBit, err := getRuneFromBytes(data, i, uint(b))
			if err != nil {
				t.Error(fmt.Sprintf("[b=%d] err raised: %s", b, err))
			}
			if newIndex != expectedIndices[b] {
				t.Error(fmt.Sprintf("[b=%d] index incorrect, expected: %d, got: %d", b, expectedIndices[b], newIndex))
			}
			if newBit != expectedBits[b] {
				t.Error(fmt.Sprintf("[b=%d] bit index incorrect, expected: %d, got: %d", b, expectedBits[b], newBit))
			}
			if value != expectedValues[b] {
				t.Error(fmt.Sprintf("[b=%d] value incorrect, expected: 0x%0.2x, got: 0x%0.2x", b, expectedValues[b], value))
			}
		})
	}
}

func TestGetBytesFromRune(t *testing.T) {
	runes := []rune{0x25f0, 0x52f8, 0x297c, 0x54be, 0x2a5f, 0x552f, 0x6a97, 0x354b}
	expectedBytes := map[uint]struct {
		data      []byte
		remainder byte
		bit       uint
	}{
		// 010 0101 1111 0000
		0: {[]byte{0xf0}, 0x25, 7},
		// 0100 1011 1110 000.
		1: {[]byte{0xe0, 0x4b}, 0x00, 0},
		// 0 1001 0111 1100 00..
		2: {[]byte{0xc0, 0x97}, 0x00, 1},
		// 01 0010 1111 1000 0...
		3: {[]byte{0x80, 0x2f}, 0x01, 2},
		// 010 0101 1111 0000 ....
		4: {[]byte{0x00, 0x5f}, 0x02, 3},
		// 0100 1011 1110 000. ....
		5: {[]byte{0x00, 0xbe}, 0x04, 4},
		// 0 1001 0111 1100 00.. ....
		6: {[]byte{0x00, 0x7c}, 0x09, 5},
		// 01 0010 1111 1000 0... ....
		7: {[]byte{0x00, 0xf8}, 0x012, 6},
	}
	for b, expected := range expectedBytes {
		t.Run(fmt.Sprintf("bit_offset_%d", b), func(t *testing.T) {
			data, remainder, bit := getBytesFromRune(uint16(runes[0]), 0, b)
			if bit != expected.bit {
				t.Error(fmt.Sprintf("[%d] bit index incorrect, expected: %d, got: %d", b, expected.bit, bit))
			}
			if remainder != expected.remainder {
				t.Error(fmt.Sprintf("[%d] remainder incorrect, expected: 0x%0.2x, got: 0x%0.2x", b, expected.remainder, remainder))
			}
			if len(data) > len(expected.data) {
				t.Error(fmt.Sprintf("[%d] data too long: %d (need: %d)", b, len(data), len(expected.data)))
			}
			if len(data) < len(expected.data) {
				t.Error(fmt.Sprintf("[%d] data too short: %d (need: %d)", b, len(data), len(expected.data)))
			}
			for j, b := range data {
				if b != expected.data[j] {
					t.Error(fmt.Sprintf("[%d](%d) data incorrect, expected: 0x%0.2x, got: 0x%0.2x", b, j, expected.data[j], b))
				}
			}
		})
	}
}

func TestEncodeDecode(t *testing.T) {
	lengths := []int{100, 10000, 1000000, 100000000}
	for _, length := range lengths {
		if length > 10000 && testing.Short() {
			t.Skip("Skipping very long decode(encode()) tests")
		}
		t.Run(fmt.Sprintf("length_%d", length), func(t *testing.T) {
			var dataBuf bytes.Buffer
			dataBuf.Grow(length)
			for i := int(0); i < length; i += 1 {
				dataBuf.WriteByte(byte(rand.Intn(256)))
			}
			expectedData := dataBuf.Bytes()
			data, err := Decode(Encode(expectedData))
			if err != nil {
				t.Error("Error while decoding:", err)
			}
			if len(data) > len(expectedData) {
				t.Error(fmt.Sprintf("[%d] data too long: %d (need: %d)", length, len(data), len(expectedData)))
			}
			if len(data) < len(expectedData) {
				t.Error(fmt.Sprintf("[%d] data too short: %d (need: %d)", length, len(data), len(expectedData)))
			}
			for i, b := range data {
				if b != expectedData[i] {
					t.Error(fmt.Sprintf("[%d](%d) data incorrect, expected: 0x%0.2x, got: 0x%0.2x", length, i, expectedData[i], b))
				}
			}
		})
	}
}