text:
package service

import (
	"context"
	"math"
	"sort"
	"sync"
	"time"

	pb "./pluginProto"
	empty "github.com/golang/protobuf/ptypes/empty"
)

// XCachePlugin is the base interface for a complete plugin
type XCachePlugin interface {
	Init(...interface{})
	GetHint(context.Context, *pb.FileHint) (*pb.FileHint, error)
	UpdateStats(context.Context, *pb.FileRequest) (*empty.Empty, error)
	ResetHistory(context.Context, *empty.Empty) (*empty.Empty, error)
}

// PluginServiceServer is the server API for PluginService curService.
type PluginServiceServer struct {
	stats           []*weightedFileStats
	statsFilenames  map[string]int
	SelFunctionType FunctionType
	Exp             float32
}

// Init the PluginServiceServer struct
func (curService PluginServiceServer) Init(vars ...interface{}) {
	curService.stats = make([]*weightedFileStats, 0)
	curService.statsFilenames = make(map[string]int)
}

// Clear the PluginServiceServer struct
func (curService *PluginServiceServer) Clear() {
	curService.stats = make([]*weightedFileStats, 0)
	curService.statsFilenames = make(map[string]int)
}

// GetHint function for plugin service
func (curService PluginServiceServer) GetHint(ctx context.Context, curFile *pb.FileHint) (*pb.FileHint, error) {
	curStats := curService.getOrInsertStats(curFile.Filename)
	Q2 := curService.getThreshold()
	store := false
	if curStats.weight < Q2 {
		store = true
	}
	return &pb.FileHint{
		Filename: curFile.Filename,
		Store:    store,
	}, nil
}

// UpdateStats function for plugin service
func (curService PluginServiceServer) UpdateStats(ctx context.Context, curFile *pb.FileRequest) (*empty.Empty, error) {
	currentTime := time.Now()
	curStats := curService.getOrInsertStats(curFile.Filename)
	curStats.updateStats(
		curFile.Hit, curStats.totRequests+1, curFile.Downloaded, currentTime, curFile.MeanTime,
	)
	return &empty.Empty{}, nil
}

// ResetHistory function for plugin service
func (curService PluginServiceServer) ResetHistory(ctx context.Context, _ *empty.Empty) (*empty.Empty, error) {
	curService.Clear()
	return &empty.Empty{}, nil
}

func updateWeightSingleFile(curStats *weightedFileStats, functionType FunctionType, exp float32, curTime time.Time, curWg *sync.WaitGroup) {
	curStats.updateWeight(
		functionType,
		exp,
		curTime,
	)
	curWg.Done()
}

func (curService *PluginServiceServer) updateWeights() {
	wg := sync.WaitGroup{}
	curTime := time.Now()
	for idx := 0; idx < len(curService.stats); idx++ {
		wg.Add(1)
		go updateWeightSingleFile(curService.stats[idx], curService.SelFunctionType, curService.Exp, curTime, &wg)
	}
	wg.Wait()
}

func (curService *PluginServiceServer) getThreshold() float32 {
	if len(curService.stats) == 0 {
		return 0.0
	}
	curService.updateWeights()
	// Order from the highest weight to the smallest
	sort.Sort(ByWeight(curService.stats))

	Q2 := curService.stats[int(math.Floor(float64(0.5*float32(len(curService.stats)))))].weight
	Q1Idx := int(math.Floor(float64(0.25 * float32(len(curService.stats)))))
	Q1 := curService.stats[Q1Idx].weight
	if Q1 > 2*Q2 {
		for idx := 0; idx < Q1Idx; idx++ {
			delete(curService.statsFilenames, curService.stats[idx].filename)
		}
		copy(curService.stats, curService.stats[Q1Idx:])
		curService.stats = curService.stats[:len(curService.stats)-1]
	}
	return Q2
}

func (curService *PluginServiceServer) getOrInsertStats(filename string) *weightedFileStats {
	var result *weightedFileStats
	if _, inStats := curService.statsFilenames[filename]; !inStats {
		curService.stats = append(curService.stats, &weightedFileStats{
			filename,
			-1,
			0.,
			0.,
			0,
			0,
			time.Now(),
			[StatsMemorySize]time.Time{},
			0,
			0.,
		})
		curService.statsFilenames[filename] = len(curService.stats) - 1
		result = curService.stats[len(curService.stats)-1]
	} else {
		if curService.stats[curService.statsFilenames[filename]].filename != filename {
			for idx := 0; idx < len(curService.stats); idx++ {
				if curService.stats[idx].filename == filename {
					curService.statsFilenames[filename] = idx
					break
				}
			}
		}
		result = curService.stats[curService.statsFilenames[filename]]
	}
	return result
}

repository: Cloud-PG/smart-cache

repo_name: Cloud-PG/smart-cache


text:
@online{noauthor_one_nodate,
	title = {One Project, Two Grants? The Scientist MagazineŽ},
	url = {http://www.the-scientist.com/?articles.view/articleNo/34212/title/One-Project--Two-Grants-/},
	shorttitle = {One Project, Two Grants?},
	abstract = {A new analysis reveals that {US} funding agencies may sometimes pay for the same project twice, leading to calls for greater oversight of grant duplication.},
	titleaddon = {The Scientist},
	urldate = {2013-02-01}
}

repository: pmean/build-website

license_type: permissive

repo_name: pmean/build-website

branch_name: refs/heads/master

extension: bib


text:
package command

import (
	"bytes"
	"fmt"
	"github.com/spf13/cobra"
	. "github.com/taichi/keigo/core"
	"github.com/taichi/keigo/log"
	"github.com/taichi/keigo/util"
	"strings"
)

var wait, time int

type desc struct {
	Use, Label string
	Index      int
}

func addLampCommands(parent *cobra.Command) {
	for _, v := range []desc{
		{"red", "red lamp", 0},
		{"yellow", "yellow lamp", 1},
		{"green", "green lamp", 2},
		{"buzzer1", "buzzer1", 3},
		{"buzzer2", "buzzer2", 4},
	} {
		parent.AddCommand(newLampCmd(v))
	}
	parent.AddCommand(newACOPCmd())
	parent.AddCommand(newALOFCmd("off"))
	parent.AddCommand(newALOFCmd("ALOF"))
}

var longTemplate = util.Must("Long", `turn on/off {{.Label}}.
Example:
    keigo {{.Use}} off
    keigo {{.Use}} on
    keigo {{.Use}} blink
    keigo {{.Use}} quickblink
    keigo {{.Use}} on -t 3 -w 2`)

func newLampCmd(d desc) *cobra.Command {
	newCmd := &cobra.Command{
		Use:   d.Use,
		Short: fmt.Sprintf("turn on/off %s", d.Label),
		Long:  longTemplate.Do(d),
		Run: newRunFn(func(cmd *cobra.Command, args []string) {
			var state = On

			if 0 < len(args) {
				states := map[string]State{
					"off":        Off,
					"on":         On,
					"blink":      Blink,
					"quickblink": QuickBlink,
					"0":          Off,
					"1":          On,
					"2":          Blink,
					"3":          QuickBlink,
				}
				state = states[strings.ToLower(args[0])]
			}

			if state != nil {
				st := *NewStates(8)
				st[d.Index] = state
				order := &ACOP{
					LampOrBuzzer,
					Seconds(wait),
					Seconds(time),
					st,
				}
				results := execute(order, &ACOP{})
				printResults(cmd, &results)
			} else {
				cmd.Printf("lamp status supports off/on/blink/quickblink")
			}
		}),
	}
	addTimeFlags(newCmd)

	return newCmd
}

func addTimeFlags(cmd *cobra.Command) {
	cmd.Flags().IntVarP(&wait, "wait", "w", 0, "waiting for specific seconds.")
	cmd.Flags().IntVarP(&time, "time", "t", 0, "turn lamp off after specific seconds.")
}

func printResults(cmd *cobra.Command, results *[]string) {
	// TODO support json output
	// TODO support colorized output
	currentState := (*results)[1]
	log.Debugf("RAW OUTPUT : %s", currentState)
	cmd.Println("Current Lamp Status")
	statusLabels := map[uint8]string{
		'0': "off",
		'1': "on",
		'2': "blink",
		'3': "quickblink",
	}

	for i, l := range []string{"RED", "YELLOW", "GREEN", "BUZZER1", "BUZZER2"} {
		cmd.Println("-------------------")
		cmd.Printf("%-10s : %6s\n", l, statusLabels[currentState[i]])
	}
}

func newACOPCmd() *cobra.Command {
	newCmd := &cobra.Command{
		Use:   "ACOP",
		Short: "execute ACOP command",
		Long: `execute low level ACOP command
Example:
    keigo ACOP x12
    keigo ACOP –u 1 x12`,
	}

	addTimeFlags(newCmd)
	u := newCmd.Flags().IntP("unit", "u", 0, "output to specific unit")
	newCmd.Run = newRunFn(func(cmd *cobra.Command, args []string) {
		unit := *u
		var buffer bytes.Buffer
		fmt.Fprintf(&buffer, "ACOP ")
		if 0 < unit {
			fmt.Fprintf(&buffer, "-u %d ", unit)
		}

		if 0 < len(args) {
			fmt.Fprintf(&buffer, "%s ", args[0])
		}

		if 0 < wait {
			fmt.Fprintf(&buffer, "-w %d ", wait)
		}
		if 0 < time {
			fmt.Fprintf(&buffer, "-t %d", time)
		}

		results := execute(&buffer, &ACOP{})
		printResults(cmd, &results)
	})

	return newCmd
}

var alofTemplate = util.Must("alof",
	`turn off all lamp and buzzer.
Example:
    keigo {{.Use}}`)

func newALOFCmd(use string) *cobra.Command {
	return &cobra.Command{
		Use:   use,
		Short: "turn off all lamp and buzzer",
		Long:  alofTemplate.Do(map[string]string{"Use": use}),
		Run: newRunFn(func(cmd *cobra.Command, args []string) {
			results := execute(ALOF, &ACOP{})
			printResults(cmd, &results)
		}),
	}
}

// TODO RLY1 - RLY8 support

repository: taichi/keigo

repo_name: taichi/keigo

extension: go


text:
package main

import (
	"image"
	"image/color"
	"image/draw"
	"os"
	"path/filepath"

	"github.com/faiface/gui"
	"github.com/faiface/gui/win"
	"golang.org/x/image/math/fixed"
)

func Browser(env gui.Env, theme *Theme, dir string, cd <-chan string, view chan<- string) {
	reload := func(dir string) (names []string, lineHeight int, namesImage *image.RGBA) {
		names = nil

		filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
			if path == dir {
				return nil
			}
			rel, err := filepath.Rel(dir, path)
			if err != nil {
				return nil
			}
			if info.IsDir() {
				names = append(names, rel+string(filepath.Separator))
				return filepath.SkipDir
			}
			names = append(names, rel)
			return nil
		})

		var images []image.Image
		for _, name := range names {
			images = append(images, MakeTextImage(name, theme.Face, theme.Text))
		}

		const inset = 4

		var width int
		for _, img := range images {
			if img.Bounds().Dx() > width {
				width = img.Bounds().Inset(-inset).Dx()
			}
		}

		metrics := theme.Face.Metrics()
		lineHeight = (metrics.Height + 2*fixed.I(inset)).Ceil()
		height := lineHeight * len(names)

		namesImage = image.NewRGBA(image.Rect(0, 0, width+2*inset, height+2*inset))
		for i := range images {
			r := image.Rect(
				0, lineHeight*i,
				width, lineHeight*(i+1),
			)
			DrawLeftCentered(namesImage, r.Inset(inset), images[i], draw.Over)
		}

		return names, lineHeight, namesImage
	}

	redraw := func(r image.Rectangle, selected int, position image.Point, lineHeight int, namesImage image.Image) func(draw.Image) image.Rectangle {
		return func(drw draw.Image) image.Rectangle {
			draw.Draw(drw, r, &image.Uniform{theme.Background}, image.ZP, draw.Src)
			draw.Draw(drw, r, namesImage, position, draw.Over)
			if selected >= 0 {
				highlightR := image.Rect(
					namesImage.Bounds().Min.X,
					namesImage.Bounds().Min.Y+lineHeight*selected,
					namesImage.Bounds().Max.X,
					namesImage.Bounds().Min.Y+lineHeight*(selected+1),
				)
				highlightR = highlightR.Sub(position).Add(r.Min)
				draw.DrawMask(
					drw, highlightR.Intersect(r),
					&image.Uniform{theme.Highlight}, image.ZP,
					&image.Uniform{color.Alpha{64}}, image.ZP,
					draw.Over,
				)
			}
			return r
		}
	}

	names, lineHeight, namesImage := reload(dir)

	var (
		r        image.Rectangle
		position = image.ZP
		selected = -1
	)

	for {
		select {
		case path := <-cd:
			if filepath.IsAbs(path) {
				dir = path
			} else {
				dir = filepath.Join(dir, path)
			}
			names, lineHeight, namesImage = reload(dir)
			position = image.ZP
			selected = -1
			env.Draw() <- redraw(r, selected, position, lineHeight, namesImage)

		case e, ok := <-env.Events():
			if !ok {
				close(env.Draw())
				return
			}

			switch e := e.(type) {
			case gui.Resize:
				r = e.Rectangle
				env.Draw() <- redraw(r, selected, position, lineHeight, namesImage)

			case win.MoDown:
				if !e.Point.In(r) {
					continue
				}
				click := e.Point.Sub(r.Min).Add(position)
				i := click.Y / lineHeight
				if i < 0 || i >= len(names) {
					continue
				}
				if selected == i {
					func() {
						path := filepath.Join(dir, names[selected])
						f, err := os.Open(path)
						if err != nil {
							return
						}
						defer f.Close()
						info, err := f.Stat()
						if err != nil {
							return
						}
						if info.IsDir() {
							dir = path
							names, lineHeight, namesImage = reload(dir)
							position = image.ZP
							selected = -1
							env.Draw() <- redraw(r, selected, position, lineHeight, namesImage)
						} else {
							view <- path
						}
					}()
				} else {
					selected = i
					env.Draw() <- redraw(r, selected, position, lineHeight, namesImage)
				}

			case win.MoScroll:
				newP := position.Sub(e.Point.Mul(16))
				if newP.X > namesImage.Bounds().Max.X-r.Dx() {
					newP.X = namesImage.Bounds().Max.X - r.Dx()
				}
				if newP.Y > namesImage.Bounds().Max.Y-r.Dy() {
					newP.Y = namesImage.Bounds().Max.Y - r.Dy()
				}
				if newP.X < namesImage.Bounds().Min.X {
					newP.X = namesImage.Bounds().Min.X
				}
				if newP.Y < namesImage.Bounds().Min.Y {
					newP.Y = namesImage.Bounds().Min.Y
				}
				if newP != position {
					position = newP
					env.Draw() <- redraw(r, selected, position, lineHeight, namesImage)
				}
			}
		}
	}
}

license: MIT

repository: pubgo/gotests

repo_name: pubgo/gotests

gha_license_id: MIT

gha_language: Go


text:
include(vcpkg_common_functions)

set(QCP_VERSION 2.0.1)

vcpkg_download_distfile(ARCHIVE
    URLS "https://www.qcustomplot.com/release/${QCP_VERSION}/QCustomPlot.tar.gz"
    FILENAME "QCustomPlot-${QCP_VERSION}.tar.gz"
    SHA512 a15598718146ed3c6b5d38530a56661c16269e530fe0dedb71b4cb2722b5733a3b57689d668a75994b79c19c6e61dcc133dbcb9ed77b93a165f4ac826a5685b9
)
vcpkg_extract_source_archive_ex(
    OUT_SOURCE_PATH SOURCE_PATH
    ARCHIVE ${ARCHIVE}
    REF ${QCP_VERSION}
)

vcpkg_download_distfile(ARCHIVE
    URLS "https://www.qcustomplot.com/release/${QCP_VERSION}/QCustomPlot-sharedlib.tar.gz"
    FILENAME "QCustomPlot-sharedlib-${QCP_VERSION}.tar.gz"
    SHA512 ce90540fca7226eac37746327e1939a9c7af38fc2595f385ed04d6d1f49560da08fb5fae15d1b9d22b6ba578583f70de8f89ef26796770d41bf599c1b15c535d
)
vcpkg_extract_source_archive(${ARCHIVE} ${SOURCE_PATH})

vcpkg_configure_qmake(SOURCE_PATH
    ${SOURCE_PATH}/qcustomplot-sharedlib/sharedlib-compilation/sharedlib-compilation.pro
)

vcpkg_build_qmake(
    RELEASE_TARGETS release-all
    DEBUG_TARGETS debug-all
)

set(DEBUG_DIR "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg")
set(RELEASE_DIR "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-rel")

# Install header file
file(INSTALL ${SOURCE_PATH}/qcustomplot.h
    DESTINATION ${CURRENT_PACKAGES_DIR}/include
)

# Install module files
macro(_install_module_file source_dir target_dir filename_regex)
    file(GLOB _files ${source_dir}/*)
    list(FILTER _files INCLUDE REGEX ${filename_regex})
    file(INSTALL ${_files} DESTINATION ${target_dir})
endmacro()

_install_module_file(${DEBUG_DIR}/debug
    ${CURRENT_PACKAGES_DIR}/debug/lib
    "qcustomplotd[2]*\.(lib|a)$")

_install_module_file(${RELEASE_DIR}/release
    ${CURRENT_PACKAGES_DIR}/lib
    "qcustomplot[2]*\.(lib|a)$")

if(VCPKG_LIBRARY_LINKAGE STREQUAL dynamic)
    file(INSTALL
        ${DEBUG_DIR}/debug/qcustomplotd2.dll
        DESTINATION ${CURRENT_PACKAGES_DIR}/debug/bin
    )

    file(INSTALL
        ${RELEASE_DIR}/release/qcustomplot2.dll
        DESTINATION ${CURRENT_PACKAGES_DIR}/bin
    )
endif()

vcpkg_copy_pdbs()

# Handle copyright
configure_file(${SOURCE_PATH}/GPL.txt ${CURRENT_PACKAGES_DIR}/share/${PORT}/copyright COPYONLY)

repository: alcroito/vcpkg

repo_name: alcroito/vcpkg

gha_license_id: NOASSERTION

extension: cmake


text:
@article{devlin2018bert,
  title={Bert: Pre-training of deep bidirectional transformers for language understanding},
  author={Devlin, Jacob and Chang, Ming-Wei and Lee, Kenton and Toutanova, Kristina},
  journal={arXiv preprint arXiv:1810.04805},
  year={2018}
}

@article{poria2017,
  title={A deeper look into sarcastic tweets using deep convolutional neural networks},
  author={Poria, Soujanya and Cambria, Erik and Hazarike, Devamanyu and Vij, Prateek},
  journal={arXiv:1610.08815v2},
  year={2017}
}

@article{ghosh2016,
  title={Fracking sarcasm using neural network},
  author={Ghosh, Aniruddha and Veale, Tony},
  journal={Proceedings of NAACL-HLT},
  year={2016}
}

@article{barbosa2010,
  title={Robust sentiment detection on twitter from biased and noisy data},
  author={Barbosa, Luciano and Feng, Junlan},
  journal={Coline 2010: Poster Volume},
  year={2010}
}

@article{joshi2017,
  title={Automatic sarcasm detection: a survey},
  author={Joshi, Aditya and Bhattacharyya, Pushpak},
  journal={ACM Computing Surveys},
  year={2017}
}

@article{schmidt1977,
  title={On so-called rhetorical questions},
  author={Schmidt-Radefeldt, Jurgen},
  journal={Journal of Pragmatics},
  year={1977}
}
@article{bengio2003neural,
  title={A neural probabilistic language model},
  author={Bengio, Yoshua and Ducharme, R{\'e}jean and Vincent, Pascal and Jauvin, Christian},
  journal={Journal of machine learning research},
  volume={3},
  number={Feb},
  pages={1137--1155},
  year={2003}
}
@inproceedings{hinton1986learning,
  title={Learning distributed representations of concepts},
  author={Hinton, Geoffrey E and others},
  booktitle={Proceedings of the eighth annual conference of the cognitive science society},
  volume={1},
  pages={12},
  year={1986},
  organization={Amherst, MA}
}
@article{mikolov2013efficient,
  title={Efficient estimation of word representations in vector space},
  author={Mikolov, Tomas and Chen, Kai and Corrado, Greg and Dean, Jeffrey},
  journal={arXiv preprint arXiv:1301.3781},
  year={2013}

}
@book{hinton1984distributed,
  title={Distributed representations},
  author={Hinton, Geoffrey E and McClelland, James L and Rumelhart, David E and others},
  year={1984},
  publisher={Carnegie-Mellon University Pittsburgh, PA}
}
@article{santos2014,
  title={Deep convolutional neural networks for sentiment anlysis of short texts},
  author={dos Santos, Cicero Nogueira and Gatti, Maira},
  journal={Proceedings of COLING 2014, the 25th International Conference on Computational Linguistics: Technical Papers},
  pages={69--78},
  year={2014}
}

@article{joshi2016,
  title={Are word embedding-based features useful for sarcasm detection?} ,
  author={Joshi, Aditya and Tripathi, Vaibhav and Patel, Kevin and Bhattacharyya, Pushpak and Carman, Mark},
  journal={arXiv:1610.00883v1},
  year={2016}
}

@article{medhat2014,
  title={Sentiment analysis algorithms and applications: a survey},
  author={Medhat, Walaa and Hassan, Ahmed and Korashe, Hoda},
  journal={Ain Shams Engineering Journal},
  page={1093--1113},
  year={2014}
}

@article{chan2015,
  title={Deep convolutional neural networks for acoustic modeling in low resource languages},
  author={Chan, William and Lane, Ian},
  journal={In IEEE International Conferene on Acoustics, Speech and Signal Processing},
  year={2015}
}

@inproceedings{pennington2014glove,
  title={Glove: Global vectors for word representation},
  author={Pennington, Jeffrey and Socher, Richard and Manning, Christopher},
  booktitle={Proceedings of the 2014 conference on empirical methods in natural language processing (EMNLP)},
  pages={1532--1543},
  year={2014}
}
@article{peters2018deep,
  title={Deep contextualized word representations},
  author={Peters, Matthew E and Neumann, Mark and Iyyer, Mohit and Gardner, Matt and Clark, Christopher and Lee, Kenton and Zettlemoyer, Luke},
  journal={arXiv preprint arXiv:1802.05365},
  year={2018}
}

@article{giachanou2016,
 author = {Giachanou, Anastasia and Crestani, Fabio},
 title = {Like It or Not: A Survey of Twitter Sentiment Analysis Methods},
 journal = {ACM Comput. Surv.},
 issue_date = {November 2016},
 volume = {49},
 number = {2},
 month = jun,
 year = {2016},
 issn = {0360-0300},
 pages = {28:1--28:41},
 articleno = {28},
 numpages = {41},
 url = {http://doi.acm.org/10.1145/2938640},
 doi = {10.1145/2938640},
 acmid = {2938640},
 publisher = {ACM},
 address = {New York, NY, USA},
 keywords = {Sentiment analysis, microblogs, opinion mining, twitter},
}

@misc{pos-tag,
title={Universal POS tags},
year={2017},
url={https://universaldependencies.org/u/pos/},
journal={Universal features}}

@misc{spacy-named-entity,
title={Annotation Specifications Schemes used for labels, tags and training data.}, url={https://spacy.io/api/annotation},
year={2019}
journal={spaCy · Industrial-strength Natural Language Processing in Python}}

@article{thorndike1948punc,
 ISSN = {00029556},
 URL = {http://www.jstor.org/stable/1416968},
 author = {E. L. Thorndike},
 journal = {The American Journal of Psychology},
 number = {2},
 pages = {222--228},
 publisher = {University of Illinois Press},
 title = {The Psychology of Punctuation},
 volume = {61},
 year = {1948}
}


text:
# - Try to find Libldns (NLNet DNS resolving library)
#
# Once done this will define the following CMake variables:
#
#  - Libldns_FOUND
#  - Libldns_INCLUDE_DIRS
#  - Libldns_LIBRARIES
#  - Libldns_DEFINITIONS
#
include(FeatureSummary)

set_package_properties(Libldns PROPERTIES
    DESCRIPTION "simplify DNS programming"
    URL "https://github.com/threatstack/libldns"
)

find_package(PkgConfig)
pkg_check_modules(PC_libldns QUIET libldns)

set(Libldns_DEFINITIONS ${PC_libldns_CFLAGS_OTHER})

find_path(Libldns_INCLUDE_DIR
    ldns/ldns.h
    HINTS ${PC_libldns_INCLUDEDIR} ${PC_libldns_INCLUDE_DIRS}
)

find_library(Libldns_LIBRARY
    NAMES ldns
    HINTS ${PC_libldns_LIBDIR} ${PC_libldns_LIBRARY_DIRS}
)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
    Libldns
    DEFAULT_MSG
    Libldns_LIBRARY Libldns_INCLUDE_DIR
)
mark_as_advanced(Libldns_INCLUDE_DIR Libldns_LIBRARY)

if(Libldns_FOUND)
    set(Libldns_INCLUDE_DIRS ${Libldns_INCLUDE_DIR})
    set(Libldns_LIBRARIES ${Libldns_LIBRARY})
endif()

gha_language: CMake


text:
package avardstock

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	h "github.com/qasemt/helper"
	"os"
	"path"
	"strings"
	"sync"
)

var pathdb string

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::STRUCT INIT
type Nemad struct {
	ID        uint64 `gorm:"primary_key; not null"`
	NemadID   string
	GroupCode string
	GroupName string
	NemadCode string
	NameEn    string
	NameFa    string
	NameFull  string
	AvardCode int
}

type NemadAvard struct {
	ID          uint64 `gorm:"primary_key; not null"`
	TypeId      string `json:"type_id"`
	Type        string `json:"type"`
	EntityId    int64  `json:"entity_id"`
	EntityType  string `json:"entity_type"`
	TradeSymbol string `json:"trade_symbol"`
	Title       string `json:"title"`
}

type StockFromWebService struct {
	ID        uint64  `gorm:"primary_key; not null"`
	AssetId   string  `gorm:"unique_index:indexok;not null"`
	IsIndex   int     `gorm:"not null;default:0"`
	TimeFrame int     `gorm:"unique_index:indexok; not null"`
	TypeChart int     `gorm:"unique_index:indexok; not null;default:0"`
	Time      int64   `gorm:"unique_index:indexok;not null" json:"time"`
	O         float64 `json:"open"`
	H         float64 `json:"high"`
	L         float64 `json:"low"`
	C         float64 `json:"close"`
	V         float64 `json:"volume"`
}

func (e StockFromWebService) TOString() string {

	return fmt.Sprintf("ID :%v Time:%f ,frame: %v type :%v", e.ID, e.Time, e.TimeFrame, e.TypeChart)
}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
func DatabaseInit(dbName1 string, timefrm string) (*gorm.DB, string, error) {
	var err error
	var db *gorm.DB
	var dirdbstr string
	var fullPath string

	dirdbstr = path.Join(h.GetRootCache(), "cache")

	if _, err := os.Stat(dirdbstr); os.IsNotExist(err) {
		os.MkdirAll(dirdbstr, os.ModePerm)
	}

	if timefrm == "" {
		fullPath = path.Join(dirdbstr, fmt.Sprintf("%v.bin", dbName1))
	} else {
		//fullPath = path.Join(dirdbstr, fmt.Sprintf("%v_%v.bin", dbName1, timefrm))
		fullPath = path.Join(dirdbstr, fmt.Sprintf("%v.bin", dbName1))
	}

	db, err = gorm.Open("sqlite3", fullPath)
	if err != nil {
		db = nil
		panic("failed to connect database")
	}

	return db, fullPath, nil
}
func Migrate(dbName1 string, isp *StockProvider) error {

	var fullPath string

	db, fullPath, er := DatabaseInit(dbName1, "")

	if er != nil {
		return errors.New(fmt.Sprintf("err:%v %v", er, fullPath))
	}
	defer isp.closeMyDb(db)
	if strings.Contains(fullPath, "main.bin") {
		db.AutoMigrate(&Nemad{})
	} else {
		db.AutoMigrate(&StockFromWebService{})
	}
	return nil
}
func InsertStocks(d *gorm.DB, k *sync.Mutex, last_record StockFromWebService, isIndex bool, stockList []StockFromWebService, assetid string, timeframe h.ETimeFrame, tc h.ETypeChart) error {
	defer k.Unlock()

	k.Lock()
	if d == nil {
		return errors.New("db not init")
	}
	/*for i := 0; i < len(stockList); i++ {
		t := stockList[i]
		t.AssetId = assetid
		t.TimeFrame = int(timeframe)
		t.TypeChart = int(tc)
		if e1 := d.Where("asset_id = ? and time_frame = ? and type_chart=? and time  = ?", assetid, timeframe, int(tc), t.Time).Order("time desc").Limit(1).First(&t).Error; gorm.IsRecordNotFoundError(e1) {
			d.Create(&t)
		}
	}*/
	//________________
	valueStrings := []string{}
	for _, t := range stockList {

		t.AssetId = assetid
		t.TimeFrame = int(timeframe)
		t.TypeChart = int(tc)
		if isIndex == true {
			t.IsIndex = 1
		}

		valueStrings = append(valueStrings, fmt.Sprintf("(\"%s\", %v,%v, %v, %v, %v, %v, %v, %v, %v)", t.AssetId, t.IsIndex, t.TimeFrame, t.TypeChart, t.Time, t.O, t.H, t.L, t.C, t.V))
	}

	smt := `INSERT OR REPLACE  INTO stock_from_web_services (asset_id,is_index,time_frame,type_chart,TIME,o,h,l,c,v) VALUES   %s ;`

	smt = fmt.Sprintf(smt, strings.Join(valueStrings, ","))

	tx := d.Begin()
	if err := tx.Exec(smt).Error; err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()
	//::::::::::::::::::::::::
	if last_record.ID != 0 {
		smt1 := fmt.Sprintf(" delete from stock_from_web_services where  id = %v", last_record.ID)
		tx1 := d.Begin()
		if err1 := tx1.Exec(smt1).Error; err1 != nil {
			tx1.Rollback()
			return err1
		}
		tx1.Commit()
	}

	return nil
}

func getLastRecord(d *gorm.DB, k *sync.Mutex, assetid string, timeframe int, tc h.ETypeChart, out *StockFromWebService) error {
	defer k.Unlock()
	k.Lock()
	if d == nil {
		return errors.New("db not init")
	}

	if e1 := d.Where("asset_id = ? and time_frame = ? and type_chart=?", assetid, timeframe, int(tc)).Order("time desc").Limit(1).First(out).Error; gorm.IsRecordNotFoundError(e1) {
		//fmt.Println("getLastRecord () -> record not found")
	}

	if d.Error != nil {
		return d.Error
	}
	return nil
}
func getRecordesStock(d *gorm.DB, k *sync.Mutex, assetid string, timeframe h.ETimeFrame, tc h.ETypeChart) ([]StockFromWebService, error) {
	defer k.Unlock()
	k.Lock()

	if d == nil {
		return nil, errors.New("db not init")
	}
	var items []StockFromWebService

	if e1 := d.Where("asset_id = ? and time_frame = ? and type_chart=?", assetid, int(timeframe), int(tc)).Order("time").Find(&items).Error; gorm.IsRecordNotFoundError(e1) {
		//fmt.Println("getLastRecord () -> record not found")
	}

	if d.Error != nil {
		return nil, d.Error
	}
	return items, nil
}
func GetNemadList(d *gorm.DB, k *sync.Mutex) ([]NemadAvard, error) {
	defer k.Unlock()
	k.Lock()

	if d == nil {
		return nil, errors.New("db not init")
	}
	var items []NemadAvard
	if e1 := d.Find(&items).Error; gorm.IsRecordNotFoundError(e1) {
		fmt.Println("getNemadList () -> record not found")
	}
	if d.Error != nil {
		return nil, d.Error
	}
	return items, nil
}

func InsertAssetInfoFromAvard(d *gorm.DB, k *sync.Mutex, avardsAsset []NemadAvard) error {
	defer k.Unlock()
	k.Lock()
	if d == nil {
		return errors.New("db not init")
	}
	d.DropTableIfExists(&NemadAvard{})
	d.AutoMigrate(&NemadAvard{})

	//-----------------------------------------------------
	valueStrings := []string{}

	for _, f := range avardsAsset {
		valueStrings = append(valueStrings, fmt.Sprintf("(\"%s\", \"%s\", %v,\"%s\",\"%s\",\"%s\")", f.TypeId, f.Type, f.EntityId, f.EntityType, f.TradeSymbol, f.Title))
	}

	smt := `INSERT INTO nemad_avards (type_id,type,entity_id,entity_type,trade_symbol,title) VALUES  %s ;`

	smt = fmt.Sprintf(smt, strings.Join(valueStrings, ","))

	tx := d.Begin()
	if err := tx.Exec(smt).Error; err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()
	return nil
}

repository: Qasemt/golanglearning

repo_name: Qasemt/golanglearning


text:
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
)

func main() {
	contents, err := ioutil.ReadFile("../input")
	if err != nil {
		log.Fatal(err)
	}

	rawValues := strings.Split(string(contents), ",")
	opCodes := make([]int, len(rawValues))

	for x := 0; x < len(rawValues); x++ {
		opCodes[x], err = strconv.Atoi(strings.TrimSpace(rawValues[x]))
		if err != nil {
			log.Fatal(err)
		}
	}

	for noun := 0; noun < 99; noun++ {
		for verb := 0; verb < 99; verb++ {
			// make a copy
			testCodes := make([]int, len(opCodes))
			copy(testCodes, opCodes)

			testCodes[1] = noun
			testCodes[2] = verb

			answer, err := Intcode(testCodes...)
			if err != nil {
				log.Fatal(err)
			}
			if answer[0] == 19690720 {
				fmt.Printf("ANSWER: %d", (100*noun)+verb)
				os.Exit(0)
			}
		}
	}
	fmt.Fprintf(os.Stderr, "exhausted search space")
	os.Exit(1)
}

// Intcode processes the input.
func Intcode(opCodeInput ...int) (opCodes []int, err error) {
	opCodes = make([]int, len(opCodeInput))
	copy(opCodes, opCodeInput)

	var opCode, aValue, bValue, storeAt int
	for head := 0; head < len(opCodes); {
		opCode = opCodes[head]
		switch opCode {
		case 99:
			return
		case 1:
			// do add
			aValue = opCodes[opCodes[head+1]]
			bValue = opCodes[opCodes[head+2]]
			storeAt = opCodes[head+3]

			opCodes[storeAt] = aValue + bValue
			head = head + 4
		case 2:
			// do add
			aValue = opCodes[opCodes[head+1]]
			bValue = opCodes[opCodes[head+2]]
			storeAt = opCodes[head+3]

			opCodes[storeAt] = aValue * bValue
			head = head + 4
		default:
			err = fmt.Errorf("invalid opcode: %d", opCode)
			return
		}
	}
	return
}

repository: wcharczuk/advent

repo_name: wcharczuk/advent


text:
package electrum

import (
	"context"
	"crypto/sha256"
	"crypto/tls"
	"encoding/hex"
	"fmt"
	"math"
	"strings"
	"sync"
	"time"

	"github.com/checksum0/go-electrum/electrum"
	"github.com/ipfs/go-log"
	"go.uber.org/zap"
	"golang.org/x/exp/slices"

	"github.com/keep-network/keep-common/pkg/wrappers"
	"github.com/keep-network/keep-core/pkg/bitcoin"
	"github.com/keep-network/keep-core/pkg/internal/byteutils"
)

var (
	supportedProtocolVersions = []string{"1.4"}
	logger                    = log.Logger("keep-electrum")
)

// Connection is a handle for interactions with Electrum server.
type Connection struct {
	parentCtx   context.Context
	client      *electrum.Client
	clientMutex *sync.RWMutex
	config      Config
}

// Connect initializes handle with provided Config.
func Connect(parentCtx context.Context, config Config) (bitcoin.Chain, error) {
	if config.ConnectTimeout == 0 {
		config.ConnectTimeout = DefaultConnectTimeout
	}
	if config.ConnectRetryTimeout == 0 {
		config.ConnectRetryTimeout = DefaultConnectRetryTimeout
	}
	if config.RequestTimeout == 0 {
		config.RequestTimeout = DefaultRequestTimeout
	}
	if config.RequestRetryTimeout == 0 {
		config.RequestRetryTimeout = DefaultRequestRetryTimeout
	}
	if config.KeepAliveInterval == 0 {
		config.KeepAliveInterval = DefaultKeepAliveInterval
	}

	c := &Connection{
		parentCtx:   parentCtx,
		config:      config,
		clientMutex: &sync.RWMutex{},
	}

	if err := c.electrumConnect(); err != nil {
		return nil, fmt.Errorf("failed to initialize electrum client: [%w]", err)
	}

	if err := c.verifyServer(); err != nil {
		return nil, fmt.Errorf("failed to verify electrum server: [%w]", err)
	}

	// Keep the connection alive and check the connection health.
	go c.keepAlive()

	// TODO: Add reconnects on lost connection.

	return c, nil
}

// GetTransaction gets the transaction with the given transaction hash.
// If the transaction with the given hash was not found on the chain,
// this function returns an error.
func (c *Connection) GetTransaction(
	transactionHash bitcoin.Hash,
) (*bitcoin.Transaction, error) {
	txID := transactionHash.Hex(bitcoin.ReversedByteOrder)

	rawTransaction, err := requestWithRetry(
		c,
		func(ctx context.Context, client *electrum.Client) (string, error) {
			// We cannot use `GetTransaction` to get the the transaction details
			// as Esplora/Electrs doesn't support verbose transactions.
			// See: https://github.com/Blockstream/electrs/pull/36
			return client.GetRawTransaction(ctx, txID)
		})
	if err != nil {
		return nil, fmt.Errorf(
			"failed to get raw transaction with ID [%s]: [%w]",
			txID,
			err,
		)
	}

	result, err := convertRawTransaction(rawTransaction)
	if err != nil {
		return nil, fmt.Errorf("failed to convert transaction: [%w]", err)
	}

	return result, nil
}

// GetTransactionConfirmations gets the number of confirmations for the
// transaction with the given transaction hash. If the transaction with the
// given hash was not found on the chain, this function returns an error.
func (c *Connection) GetTransactionConfirmations(
	transactionHash bitcoin.Hash,
) (uint, error) {
	txID := transactionHash.Hex(bitcoin.ReversedByteOrder)

	txLogger := logger.With(
		zap.String("txID", txID),
	)

	rawTransaction, err := requestWithRetry(
		c,
		func(ctx context.Context, client *electrum.Client) (string, error) {
			// We cannot use `GetTransaction` to get the the transaction details
			// as Esplora/Electrs doesn't support verbose transactions.
			// See: https://github.com/Blockstream/electrs/pull/36
			return client.GetRawTransaction(ctx, txID)
		})
	if err != nil {
		return 0,
			fmt.Errorf(
				"failed to get raw transaction with ID [%s]: [%w]",
				txID,
				err,
			)
	}

	tx, err := decodeTransaction(rawTransaction)
	if err != nil {
		return 0, fmt.Errorf(
			"failed to decode the transaction [%s]: [%w]",
			rawTransaction,
			err,
		)
	}

	// As a workaround for the problem described in https://github.com/Blockstream/electrs/pull/36
	// we need to calculate the number of confirmations based on the latest
	// block height and block height of the transaction.
	// Electrum protocol doesn't expose a function to get the transaction's block
	// height (other that the `GetTransaction` that is unsupported by Esplora/Electrs).
	// To get the block height of the transaction we query the history of transactions
	// for the output script hash, as the history contains the transaction's block
	// height.

	// Initialize txBlockHeigh with minimum int32 value to identify a problem when
	// a block height was not found in a history of any of the script hashes.
	//
	// The history is expected to return a block height for confirmed transaction.
	// If a transaction is unconfirmed (is still in the mempool) the height will
	// have a value of `0` or `-1`.
	txBlockHeight := int32(math.MinInt32)
txOutLoop:
	for _, txOut := range tx.TxOut {
		script := txOut.PkScript
		scriptHash := sha256.Sum256(script)
		reversedScriptHash := byteutils.Reverse(scriptHash[:])
		reversedScriptHashString := hex.EncodeToString(reversedScriptHash)

		scriptHashHistory, err := requestWithRetry(
			c,
			func(
				ctx context.Context,
				client *electrum.Client,
			) ([]*electrum.GetMempoolResult, error) {
				return client.GetHistory(ctx, reversedScriptHashString)
			})
		if err != nil {
			// Don't return an error, but continue to the next TxOut entry.
			txLogger.Errorf("failed to get history for script hash: [%v]", err)
			continue txOutLoop
		}

		for _, transaction := range scriptHashHistory {
			if transaction.Hash == txID {
				txBlockHeight = transaction.Height
				break txOutLoop
			}
		}
	}

	// History querying didn't come up with the transaction's block height. Return
	// an error.
	if txBlockHeight == math.MinInt32 {
		return 0, fmt.Errorf(
			"failed to find the transaction block height in script hashes' histories",
		)
	}

	// If the block height is greater than `0` the transaction is confirmed.
	if txBlockHeight > 0 {
		latestBlockHeight, err := c.GetLatestBlockHeight()
		if err != nil {
			return 0, fmt.Errorf(
				"failed to get the latest block height: [%w]",
				err,
			)
		}

		if latestBlockHeight >= uint(txBlockHeight) {
			// Add `1` to the calculated difference as if the transaction block
			// height equals the latest block height the transaction is already
			// confirmed, so it has one confirmation.
			return latestBlockHeight - uint(txBlockHeight) + 1, nil
		}
	}

	return 0, nil
}

// BroadcastTransaction broadcasts the given transaction over the
// network of the Bitcoin chain nodes. If the broadcast action could not be
// done, this function returns an error. This function does not give any
// guarantees regarding transaction mining. The transaction may be mined or
// rejected eventually.
func (c *Connection) BroadcastTransaction(
	transaction *bitcoin.Transaction,
) error {
	rawTx := transaction.Serialize()

	rawTxLogger := logger.With(
		zap.String("rawTx", hex.EncodeToString(rawTx)),
	)
	rawTxLogger.Debugf("broadcasting transaction")

	var response string

	response, err := requestWithRetry(
		c,
		func(ctx context.Context, client *electrum.Client) (string, error) {
			return client.BroadcastTransaction(ctx, string(rawTx))
		})
	if err != nil {
		return fmt.Errorf("failed to broadcast the transaction: [%w]", err)
	}

	rawTxLogger.Infof("transaction broadcast successful: [%s]", response)

	return nil
}

// GetLatestBlockHeight gets the height of the latest block (tip). If the
// latest block was not determined, this function returns an error.
func (c *Connection) GetLatestBlockHeight() (uint, error) {
	blockHeight, err := requestWithRetry(
		c,
		func(ctx context.Context, client *electrum.Client) (int32, error) {
			headersChan, err := client.SubscribeHeaders(ctx)
			if err != nil {
				return 0, fmt.Errorf("failed to get the blocks tip height: [%w]", err)
			}
			tip := <-headersChan
			return tip.Height, nil
		})
	if err != nil {
		return 0, fmt.Errorf("failed to subscribe for headers: [%w]", err)
	}

	if blockHeight > 0 {
		return uint(blockHeight), nil
	}

	return 0, nil
}

// GetBlockHeader gets the block header for the given block height. If the
// block with the given height was not found on the chain, this function
// returns an error.
func (c *Connection) GetBlockHeader(
	blockHeight uint,
) (*bitcoin.BlockHeader, error) {
	getBlockHeaderResult, err := requestWithRetry(
		c,
		func(
			ctx context.Context,
			client *electrum.Client,
		) (*electrum.GetBlockHeaderResult, error) {
			return client.GetBlockHeader(ctx, uint32(blockHeight), 0)
		},
	)
	if err != nil {
		return nil, fmt.Errorf("failed to get block header: [%w]", err)
	}

	blockHeader, err := convertBlockHeader(getBlockHeaderResult)
	if err != nil {
		return nil, fmt.Errorf("failed to convert block header: %w", err)
	}

	return blockHeader, nil
}

func (c *Connection) electrumConnect() error {
	var client *electrum.Client
	var err error
	switch c.config.Protocol {
	case TCP:
		logger.Debug("establishing TCP connection to electrum server...")
		client, err = connectWithRetry(
			c,
			func(ctx context.Context) (*electrum.Client, error) {
				return electrum.NewClientTCP(ctx, c.config.URL)
			},
		)
	case SSL:
		// TODO: Implement certificate verification to be able to disable the `InsecureSkipVerify: true` workaround.
		// #nosec G402 (TLS InsecureSkipVerify set true)
		tlsConfig := &tls.Config{InsecureSkipVerify: true}

		logger.Debug("establishing SSL connection to electrum server...")
		client, err = connectWithRetry(
			c,
			func(ctx context.Context) (*electrum.Client, error) {
				return electrum.NewClientSSL(ctx, c.config.URL, tlsConfig)
			},
		)
	default:
		err = fmt.Errorf("unsupported protocol: [%s]", c.config.Protocol)
	}

	if err == nil {
		c.client = client
	}

	return err
}

func (c *Connection) verifyServer() error {
	type Server struct {
		version  string
		protocol string
	}

	server, err := requestWithRetry(
		c,
		func(ctx context.Context, client *electrum.Client) (*Server, error) {
			serverVersion, protocolVersion, err := client.ServerVersion(ctx)
			if err != nil {
				return nil, err
			}
			return &Server{serverVersion, protocolVersion}, nil
		},
	)
	if err != nil {
		return fmt.Errorf("failed to get server version: [%w]", err)
	}

	logger.Infof(
		"connected to electrum server [version: [%s], protocol: [%s]]",
		server.version,
		server.protocol,
	)

	// Log a warning if connected to a server running an unsupported protocol version.
	if !slices.Contains(supportedProtocolVersions, server.protocol) {
		logger.Warnf(
			"electrum server [%s] runs an unsupported protocol version: [%s]; expected one of: [%s]",
			c.config.URL,
			server.protocol,
			strings.Join(supportedProtocolVersions, ","),
		)
	}

	return nil
}

func (c *Connection) keepAlive() {
	ticker := time.NewTicker(c.config.KeepAliveInterval)

	for {
		select {
		case <-ticker.C:
			_, err := requestWithRetry(
				c,
				func(ctx context.Context, client *electrum.Client) (interface{}, error) {
					return nil, client.Ping(ctx)
				},
			)
			if err != nil {
				logger.Errorf(
					"failed to ping the electrum server; "+
						"please verify health of the electrum server: [%v]",
					err,
				)
			} else {
				// Adjust ticker starting at the time of the latest successful ping.
				ticker = time.NewTicker(c.config.KeepAliveInterval)
			}
		case <-c.parentCtx.Done():
			ticker.Stop()
			c.client.Shutdown()
			return
		}
	}
}

func connectWithRetry(
	c *Connection,
	newClientFn func(ctx context.Context) (*electrum.Client, error),
) (*electrum.Client, error) {
	var result *electrum.Client
	err := wrappers.DoWithDefaultRetry(
		c.parentCtx,
		c.config.ConnectRetryTimeout,
		func(ctx context.Context) error {
			connectCtx, connectCancel := context.WithTimeout(
				ctx,
				c.config.ConnectTimeout,
			)
			defer connectCancel()

			client, err := newClientFn(connectCtx)
			if err == nil {
				result = client
			}

			return err
		},
	)

	return result, err
}

func requestWithRetry[K interface{}](
	c *Connection,
	requestFn func(ctx context.Context, client *electrum.Client) (K, error),
) (K, error) {
	var result K

	err := wrappers.DoWithDefaultRetry(
		c.parentCtx,
		c.config.RequestRetryTimeout,
		func(ctx context.Context) error {
			if err := c.reconnectIfShutdown(); err != nil {
				return err
			}

			requestCtx, requestCancel := context.WithTimeout(ctx, c.config.RequestTimeout)
			defer requestCancel()

			c.clientMutex.RLock()
			r, err := requestFn(requestCtx, c.client)
			c.clientMutex.RUnlock()

			if err != nil {
				return fmt.Errorf("request failed: [%w]", err)
			}

			result = r
			return nil
		})

	return result, err
}

func (c *Connection) reconnectIfShutdown() error {
	c.clientMutex.Lock()
	defer c.clientMutex.Unlock()

	isClientShutdown := c.client.IsShutdown()
	if isClientShutdown {
		logger.Warn("connection to electrum server is down; reconnecting...")
		err := c.electrumConnect()
		if err != nil {
			return fmt.Errorf("failed to reconnect to electrum server: [%w]", err)
		}
		logger.Info("reconnected to electrum server")
	}

	return nil
}

branch_name: refs/heads/main


text:
@article{saade_spectral_2017,
 abstract = {We revisit classical bounds of Fisher on the ferromagnetic Ising model (Fisher 1967 Phys. Rev. 162 480), and show how to efficiently use them on an arbitrary given graph to rigorously upper-bound the partition function, magnetizations, and correlations. The results are valid on any finite graph, with arbitrary topology and arbitrary positive couplings and fields. Our results are based on high temperature expansions of the aforementioned quantities, and are expressed in terms of two related linear operators: the non-backtracking operator and the Bethe Hessian. As a by-product, we show that in a well-defined high-temperature region, the susceptibility propagation algorithm (Mezard 2009 J. Physiol. 103 107–13) converges and provides an upper bound on the true spin–spin correlations.},
 author = {Saade, Alaa and Krzakala, Florent and Zdeborová, Lenka},
 doi = {10.1088/1742-5468/aa6f1e},
 file = {IOP Full Text PDF:/Users/florentkrzakala/Zotero/storage/KLXF8U65/Saade et al. - 2017 - Spectral bounds for the Ising ferromagnet on an ar.pdf:application/pdf},
 issn = {1742-5468},
 journal = {J. Stat. Mech.},
 language = {en},
 month = {May},
 number = {5},
 pages = {053403},
 title = {Spectral bounds for the Ising ferromagnet on an arbitrary given graph},
 url = {https://doi.org/10.1088%2F1742-5468%2Faa6f1e},
 urldate = {2019-07-01},
 volume = {2017},
 year = {2017}
}

repository: krzakala/academic-kickstart

repo_name: krzakala/academic-kickstart


text:
@article{aaronson2015read,
    author = {Aaronson, Scott},
    doi = {10.1038/nphys3272},
    issn = {1745-2473},
    journal= Nature Physics,
    link =http://dx.doi.org/10.1038/nphys3272,
    month = {Apr},
    number = {4},
    pages = {291--293},
    publisher = {Springer Nature},
    title = {Read the fine print},
    volume = {11},
    year = {2015}
}

@article{adcock2015advances,
    archiveprefix = {arXiv},
    author = {Adcock, Jeremy and Allen, Euan and Day, Matthew and Frick, Stefan and Hinchliff, Janna and Johnson, Mack and Morley-Short, Sam and Pallister, Sam and Price, Alasdair and Stanisic, Stasja},
    eprint = 1512.02900,
    primaryclass = quant-ph,
    title = {Advances in quantum machine learning},
    year = {2015}
}

@article{alvarez2017supervised,
    archiveprefix = {arXiv},
    author = {Alvarez-Rodriguez, Unai and Lamata, Lucas and Escandell-Montero, Pablo and Mart{\'\i}n-Guerrero, Jos{\'e} D and Solano, Enrique},
    doi = {10.1038/s41598-017-13378-0},
    eprint = {1612.05535},
    journal = {Scientific Reports},
    month = {Oct},
    number = {1},
    pages = {13645},
    primaryclass = {quant-ph},
    publisher = Springer Nature,
    title = {Supervised Quantum Learning without Measurements},
    volume = {7},
    year = 2017
}

@article{ambainis2005quantum,
    author = {Ambainis, Andris},
    eprint = {quant-ph/0504012},
    title = Quantum search algorithms,
    year = {2005}
}

repository: lucainnocenti/bibtex-sanitizer

repo_name: lucainnocenti/bibtex-sanitizer

gha_language: Python


text:
# This is a dummy package so OE can use the poky mesa files
require mesa-dri_${PV}.bb

# override debug optimization for ARM when compiling in thumb mode
# gcc 4.4+ ICEs with -O1 -fno-omit-frame-pointer

DEBUG_OPTIMIZATION_thumb = "-O1 -g"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
package incoming

import (
	"github.com/Dmitriy-Vas/wave_buffer"
)

// GetID returns packet ID.
func (packet *QuestMsgPacket) GetID() int64 {
	return packet.ID
}

// SetID sets ID to the packet.
func (packet *QuestMsgPacket) SetID(id int64) {
	packet.ID = id
}

// GetSend returns whether to send this packet.
func (packet *QuestMsgPacket) GetSend() bool {
	return packet.Send
}

// SetSend sets whether to send this packet.
func (packet *QuestMsgPacket) SetSend(value bool) {
	packet.Send = value
}

type QuestMsgPacket struct {
	ID       int64
	Send     bool
	Text     string
	Color    string
	Language int32
}

func (packet *QuestMsgPacket) Read(b buffer.PacketBuffer) {
	packet.Text = b.ReadString(b.Bytes(), b.Index(), 0)
	packet.Color = b.ReadString(b.Bytes(), b.Index(), 0)
	packet.Language = b.ReadInt(b.Bytes(), b.Index())
}

func (packet *QuestMsgPacket) Write(b buffer.PacketBuffer) {
	b.WriteString(b.Bytes(), packet.Text, b.Index())
	b.WriteString(b.Bytes(), packet.Color, b.Index())
	b.WriteInt(b.Bytes(), packet.Language, b.Index())
}


text:
package handlers

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"testing"
	"time"

	ctrl "sigs.k8s.io/controller-runtime"

	"github.com/nats-io/nats.go"

	cev2event "github.com/cloudevents/sdk-go/v2/event"
	"github.com/kyma-project/kyma/components/eventing-controller/pkg/application/applicationtest"
	"github.com/kyma-project/kyma/components/eventing-controller/pkg/application/fake"
	"github.com/kyma-project/kyma/components/eventing-controller/pkg/env"
	"github.com/kyma-project/kyma/components/eventing-controller/pkg/handlers/eventtype"
	eventingtesting "github.com/kyma-project/kyma/components/eventing-controller/testing"
)

func TestConvertMsgToCE(t *testing.T) {
	eventTime := time.Now().Format(time.RFC3339)
	testCases := []struct {
		name               string
		natsMsg            nats.Msg
		expectedCloudEvent cev2event.Event
		expectedErr        error
	}{
		{
			name: "a valid Cloud Event NatsMessage",
			natsMsg: nats.Msg{
				Subject: "fooeventtype",
				Reply:   "",
				Header:  nil,
				Data:    []byte(NewNatsMessagePayload("foo-data", "id", "foosource", eventTime, "fooeventtype")),
				Sub:     nil,
			},
			expectedCloudEvent: eventingtesting.NewCloudEvent("\"foo-data\"", "id", "foosource", eventTime, "fooeventtype", t),
			expectedErr:        nil,
		}, {
			name: "an invalid Cloud Event NatsMessage with empty id",
			natsMsg: nats.Msg{
				Subject: "fooeventtype",
				Reply:   "",
				Header:  nil,
				Data:    []byte(NewNatsMessagePayload("foo-data", "", "foosource", eventTime, "fooeventtype")),
				Sub:     nil,
			},
			expectedCloudEvent: cev2event.New(cev2event.CloudEventsVersionV1),
			expectedErr:        errors.New("id: MUST be a non-empty string\n"),
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			gotCE, err := convertMsgToCE(&tc.natsMsg)
			if err != nil && tc.expectedErr == nil {
				t.Fatalf("Should not give error, got: %v", err)
			}
			if tc.expectedErr != nil {
				if err == nil {
					t.Fatalf("Received nil error, expected: %v got: %v", tc.expectedErr, err)
				}
				if tc.expectedErr.Error() != err.Error() {
					t.Fatalf("Received wrong error, expected: %v got: %v", tc.expectedErr, err)
				}
				return
			}
			if gotCE == nil {
				t.Fatalf("Test failed, got nil cloudevent")
			}
			if !(gotCE.Subject() == tc.expectedCloudEvent.Subject()) ||
				!(gotCE.ID() == tc.expectedCloudEvent.ID()) ||
				!(gotCE.DataContentType() == tc.expectedCloudEvent.DataContentType()) ||
				!(gotCE.Source() == tc.expectedCloudEvent.Source()) ||
				!(gotCE.Time().String() == tc.expectedCloudEvent.Time().String()) ||
				!(string(gotCE.Data()) == string(tc.expectedCloudEvent.Data())) {
				t.Errorf("received wrong cloudevent, expected: %v got: %v", tc.expectedCloudEvent, gotCE)
			}
		})
	}
}

func TestSubscription(t *testing.T) {
	natsPort := 5222
	subscriberPort := 8080
	subscriberReceiveURL := fmt.Sprintf("http://127.0.0.1:%d/store", subscriberPort)
	subscriberCheckURL := fmt.Sprintf("http://127.0.0.1:%d/check", subscriberPort)

	// Start Nats server
	natsServer := eventingtesting.RunNatsServerOnPort(natsPort)
	defer natsServer.Shutdown()

	natsURL := natsServer.ClientURL()
	natsClient := Nats{
		Subscriptions: make(map[string]*nats.Subscription),
		Config: env.NatsConfig{
			Url:           natsURL,
			MaxReconnects: 2,
			ReconnectWait: time.Second,
		},
		Log: ctrl.Log.WithName("reconciler").WithName("Subscription"),
	}
	err := natsClient.Initialize()
	if err != nil {
		t.Fatalf("failed to connect to Nats Server: %v", err)
	}

	// Create a new subscriber
	subscriber := eventingtesting.NewSubscriber(fmt.Sprintf(":%d", subscriberPort))
	subscriber.Start()

	// Shutting down subscriber
	defer subscriber.Shutdown()

	// Check subscriber is running or not by checking the store
	err = subscriber.CheckEvent("", subscriberCheckURL)
	if err != nil {
		t.Fatalf("subscriber did not receive the event: %v", err)
	}

	// Prepare event-type cleaner
	application := applicationtest.NewApplication(eventingtesting.ApplicationNameNotClean, nil)
	applicationLister := fake.NewApplicationListerOrDie(context.Background(), application)
	cleaner := eventtype.NewCleaner(eventingtesting.EventTypePrefix, applicationLister)

	// Create a subscription
	sub := eventingtesting.NewSubscription("sub", "foo", eventingtesting.WithNotCleanEventTypeFilter)
	sub.Spec.Sink = subscriberReceiveURL
	err = natsClient.SyncSubscription(sub, cleaner)
	if err != nil {
		t.Fatalf("failed to Sync subscription: %v", err)
	}

	data := "sampledata"
	// Send an event
	err = SendEvent(&natsClient, data)
	if err != nil {
		t.Fatalf("failed to publish event: %v", err)
	}

	expectedDataInStore := fmt.Sprintf("\"%s\"", data)
	// Check for the event
	err = subscriber.CheckEvent(expectedDataInStore, subscriberCheckURL)
	if err != nil {
		t.Fatalf("subscriber did not receive the event: %v", err)
	}

	// Delete subscription
	err = natsClient.DeleteSubscription(sub)
	if err != nil {
		t.Fatalf("failed to delete subscription: %v", err)
	}

	newData := "datawhichdoesnotexist"
	// Send an event
	err = SendEvent(&natsClient, newData)
	if err != nil {
		t.Fatalf("failed to publish event: %v", err)
	}

	// Check for the event that it did not reach subscriber
	// Store should never return newdata hence CheckEvent should fail to match newdata
	notExpectedNewDataInStore := fmt.Sprintf("\"%s\"", newData)
	err = subscriber.CheckEvent(notExpectedNewDataInStore, subscriberCheckURL)
	if err != nil && !strings.Contains(err.Error(), "failed to check the event after retries") {
		t.Fatalf("failed to CheckEvent: %v", err)
	}
	// newdata was received by the subscriber meaning the subscription was not deleted
	if err == nil {
		t.Fatal("subscription still exists in Nats")
	}
}

func SendEvent(natsClient *Nats, data string) error {
	// assumption: the event-type used for publishing is already cleaned from none-alphanumeric characters
	// because the publisher-application should have cleaned it already before publishing
	eventType := eventingtesting.EventType
	eventTime := time.Now().Format(time.RFC3339)
	sampleEvent := NewNatsMessagePayload(data, "id", eventingtesting.EventSource, eventTime, eventType)
	return natsClient.Connection.Publish(eventType, []byte(sampleEvent))
}

func NewNatsMessagePayload(data, id, source, eventTime, eventType string) string {
	jsonCE := fmt.Sprintf("{\"data\":\"%s\",\"datacontenttype\":\"application/json\",\"id\":\"%s\",\"source\":\"%s\",\"specversion\":\"1.0\",\"time\":\"%s\",\"type\":\"%s\"}", data, id, source, eventTime, eventType)
	return jsonCE
}

repository: sayanh/kyma

repo_name: sayanh/kyma


text:
@InProceedings{Lin_zennas_ICCV_2021,
    author    = {Lin, Ming and Wang, Pichao and Sun, Zhenhong and Chen, Hesen and Sun, Xiuyu and Qian, Qi and Li, Hao and Jin, Rong},
    title     = {Zen-NAS: A Zero-Shot NAS for High-Performance Image Recognition},
    booktitle = {Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV)},
    month     = {October},
    year      = {2021},
    pages     = {347-356}
}


text:
package router

import (
	"log"

	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/gostarer/gateway/controller"
	"github.com/gostarer/gateway/docs"
	"github.com/gostarer/gateway/infra/lib"
	"github.com/gostarer/gateway/middleware"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func InitRouter(middlewares ...gin.HandlerFunc) *gin.Engine {
	// programatically set swagger info
	docs.SwaggerInfo.Title = lib.GetStringConf("base.swagger.title")
	docs.SwaggerInfo.Description = lib.GetStringConf("base.swagger.desc")
	docs.SwaggerInfo.Version = "1.0"
	docs.SwaggerInfo.Host = lib.GetStringConf("base.swagger.host")
	docs.SwaggerInfo.BasePath = lib.GetStringConf("base.swagger.base_path")
	docs.SwaggerInfo.Schemes = []string{"http", "https"}

	router := gin.Default()
	router.Use(middlewares...)
	router.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	adminLoginRouter := router.Group("/admin_login")
	store, err := sessions.NewRedisStore(10, "tcp", lib.GetStringConf("base.session.redis_server"), lib.GetStringConf("base.session.redis_password"), []byte("secret"))
	if err != nil {
		log.Fatalf("sessions.NewRedisStore err:%v", err)
	}
	adminLoginRouter.Use(
		sessions.Sessions("mysession", store),
		middleware.RecoveryMiddleware(),
		middleware.RequestLog(),
		middleware.TranslationMiddleware())
	{
		controller.AdminLoginRegister(adminLoginRouter)
	}

	adminRouter := router.Group("/admin")
	adminRouter.Use(
		sessions.Sessions("mysession", store),
		middleware.RecoveryMiddleware(),
		middleware.RequestLog(),
		middleware.SessionAuthMiddleware(),
		middleware.TranslationMiddleware())
	{
		controller.AdminRegister(adminRouter)
	}

	serviceRouter := router.Group("/service")
	serviceRouter.Use(
		sessions.Sessions("mysession", store),
		middleware.RecoveryMiddleware(),
		middleware.RequestLog(),
		middleware.SessionAuthMiddleware(),
		middleware.TranslationMiddleware())
	{
		controller.ServiceRegister(serviceRouter)
	}

	appRouter := router.Group("/app")
	appRouter.Use(
		sessions.Sessions("mysession", store),
		middleware.RecoveryMiddleware(),
		middleware.RequestLog(),
		middleware.SessionAuthMiddleware(),
		middleware.TranslationMiddleware())
	{
		controller.APPRegister(appRouter)
	}

	dashRouter := router.Group("/dashboard")
	dashRouter.Use(
		sessions.Sessions("mysession", store),
		middleware.RecoveryMiddleware(),
		middleware.RequestLog(),
		middleware.SessionAuthMiddleware(),
		middleware.TranslationMiddleware())
	{
		controller.DashboardRegister(dashRouter)
	}

	router.Static("/dist", "./dist")
	return router
}

repository: gostarer/gateway

repo_name: gostarer/gateway


text:
package main

import (
	"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm"
	"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types"
)

func main() {
	proxywasm.SetVMContext(&vmContext{})
}

type vmContext struct {
	types.DefaultVMContext
}

func (*vmContext) NewPluginContext(contextID uint32) types.PluginContext {
	return &pluginLifecycle{}
}

type pluginLifecycle struct {
	types.DefaultPluginContext
	contextID uint32
}

func (ctx *pluginLifecycle) OnPluginStart(pluginConfigurationSize int) types.OnPluginStartStatus {
	proxywasm.LogCriticalf("%s", "ouch, something is wrong")
	proxywasm.LogError("ouch, something is wrong")
	proxywasm.LogWarn("ouch, something is wrong")
	proxywasm.LogInfof("ouch,%s", " something is wrong")
	proxywasm.LogDebug("ouch, something is wrong")
	proxywasm.LogTrace("ouch, something is wrong")
	return types.OnPluginStartStatusOK
}

repository: Xunzhuo/wasm-nginx-module

repo_name: Xunzhuo/wasm-nginx-module


text:
/*
AES CBC PKCS5Padding加/解密

使用 hex.Encode

查看测试文件:
aes_cbc_test.go

*/
package util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
)

const (
	//iv 值
	//16位长度
	iv = "0000000000000000"
)

//AESEncrypt AES CBC encrypt
func AESEncrypt(plainText string, key string) string {
	bKey := []byte(key)
	bIV := []byte(iv)
	bPlainText := PKCS5Padding([]byte(plainText), aes.BlockSize, len(plainText))
	block, _ := aes.NewCipher(bKey)
	cipherText := make([]byte, len(bPlainText))
	mode := cipher.NewCBCEncrypter(block, bIV)
	mode.CryptBlocks(cipherText, bPlainText)
	//注意：此处使用hex编码
	return hex.EncodeToString(cipherText)
}

//PKCS5Padding PKCS5Padding
func PKCS5Padding(cipherText []byte, blockSize int, after int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

//AESDecrypt 解码
func AESDecrypt(decodeStr string, key string) (string, error) {
	bKey := []byte(key)
	bIV := []byte(iv)
	//注意：此处使用使用hex解码
	decodeBytes, err := hex.DecodeString(decodeStr)
	if err != nil {
		return "", err
	}
	block, err := aes.NewCipher(bKey)
	if err != nil {
		return "", err
	}
	blockMode := cipher.NewCBCDecrypter(block, bIV)
	origData := make([]byte, len(decodeBytes))

	blockMode.CryptBlocks(origData, decodeBytes)
	origData = PKCS5UnPadding(origData)
	return string(origData), nil
}

//PKCS5UnPadding PKCS5UnPadding
func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unPadding := int(origData[length-1])
	return origData[:(length - unPadding)]
}

// AES-256-ECB
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
	cipher, _ := aes.NewCipher(generateKey(key))
	decrypted = make([]byte, len(encrypted))
	//
	for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
		cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
	}

	trim := 0
	if len(decrypted) > 0 {
		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
	}

	return decrypted[:trim]
}

func generateKey(key []byte) (genKey []byte) {
	if len(key) == 16 || len(key) == 24 || len(key) == 32 {
		return key
	}
	genKey = make([]byte, 16)
	copy(genKey, key)
	for i := 16; i < len(key); {
		for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
			genKey[j] ^= key[i]
		}
	}
	return genKey
}

repository: gkzy/gow

repo_name: gkzy/gow


text:
// Code generated by go-swagger; DO NOT EDIT.

// Copyright 2017-2020 Authors of Cilium
// SPDX-License-Identifier: Apache-2.0

package storage_v1beta1

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command

import (
	"net/http"

	"github.com/go-openapi/runtime/middleware"
)

// PatchStorageV1beta1CSIDriverHandlerFunc turns a function with the right signature into a patch storage v1beta1 c s i driver handler
type PatchStorageV1beta1CSIDriverHandlerFunc func(PatchStorageV1beta1CSIDriverParams) middleware.Responder

// Handle executing the request and returning a response
func (fn PatchStorageV1beta1CSIDriverHandlerFunc) Handle(params PatchStorageV1beta1CSIDriverParams) middleware.Responder {
	return fn(params)
}

// PatchStorageV1beta1CSIDriverHandler interface for that can handle valid patch storage v1beta1 c s i driver params
type PatchStorageV1beta1CSIDriverHandler interface {
	Handle(PatchStorageV1beta1CSIDriverParams) middleware.Responder
}

// NewPatchStorageV1beta1CSIDriver creates a new http.Handler for the patch storage v1beta1 c s i driver operation
func NewPatchStorageV1beta1CSIDriver(ctx *middleware.Context, handler PatchStorageV1beta1CSIDriverHandler) *PatchStorageV1beta1CSIDriver {
	return &PatchStorageV1beta1CSIDriver{Context: ctx, Handler: handler}
}

/*PatchStorageV1beta1CSIDriver swagger:route PATCH /apis/storage.k8s.io/v1beta1/csidrivers/{name} storage_v1beta1 patchStorageV1beta1CSIDriver

partially update the specified CSIDriver

*/
type PatchStorageV1beta1CSIDriver struct {
	Context *middleware.Context
	Handler PatchStorageV1beta1CSIDriverHandler
}

func (o *PatchStorageV1beta1CSIDriver) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	route, rCtx, _ := o.Context.RouteInfo(r)
	if rCtx != nil {
		r = rCtx
	}
	var Params = NewPatchStorageV1beta1CSIDriverParams()

	if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
		o.Context.Respond(rw, r, route.Produces, route, err)
		return
	}

	res := o.Handler.Handle(Params) // actually handle the request

	o.Context.Respond(rw, r, route.Produces, route, res)

}

repository: cilium/kube-apate

repo_name: cilium/kube-apate


text:
DESCRIPTION = "An Encrypting FUSE Filesystem"
HOMEPAGE = "http://www.arg0.net/#!encfs/c1awt"
SECTION = "universe/otherosfs"
LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "file://COPYING;md5=951b5c8c6c484058f2eafac08b65c272"

S = "${WORKDIR}/git"

DEPENDS = "fuse rlog openssl boost"
RDEPENDS:${PN} = "fuse rlog openssl boost"

SRC_URI = "\
	  git://github.com/vgough/encfs.git;protocol=https \
	  file://cmakelists_correction.patch \
          "

SRCREV = "0426051a3e520c29d261b7fe83461d90b9d54ddf"

inherit cmake


text:
package void_domain

import (
	"errors"
	"payment-gateway-api/api/const/error_constant"
	"payment-gateway-api/api/domain/common_validation"
	"strings"
)

//VoidRequest is the format for the request by the void endpoint
type VoidRequest struct {
	AuthId string `json:"id" binding:"required"`
}

//VoidResponse is the format for the response by the void endpoint
type VoidResponse struct {
	IsSuccess bool    `json:"success"`
	Amount    float32 `json:"amount"`
	Currency  string  `json:"currency"`
}

//ValidateFields strips all spaces from strings and checks their validity
func (v *VoidRequest) ValidateFields() []error {
	var err = make([]error, 0)
	v.AuthId = strings.Replace(v.AuthId, " ", "", -1)
	if !common_validation.IsValidUUID(v.AuthId) {
		err = append(err, errors.New(error_constant.InvalidAuthIdField))
	}
	return err
}


text:
@article{acp-15-13849-2015,
 author = {Fowler, D. and Steadman, C. E. and Stevenson, D. and Coyle, M. and Rees, R. M. and Skiba, U. M. and Sutton, M. A. and Cape, J. N. and Dore, A. J. and Vieno, M. and Simpson, D. and Zaehle, S. and Stocker, B. D. and Rinaldi, M. and Facchini, M. C. and Flechard, C. R. and Nemitz, E. and Twigg, M. and Erisman, J. W. and Butterbach-Bahl, K. and Galloway, J. N.},
 bdsk-url-1 = {http://www.atmos-chem-phys.net/15/13849/2015/},
 bdsk-url-2 = {http://dx.doi.org/10.5194/acp-15-13849-2015},
 doi = {10.5194/acp-15-13849-2015},
 journal = {Atmospheric Chemistry and Physics},
 number = {24},
 pages = {13849--13893},
 title = {Effects of global change during the 21st century on the nitrogen cycle},
 url = {http://www.atmos-chem-phys.net/15/13849/2015/},
 volume = {15},
 year = {2015}
}


text:
DESCRIPTION = "Scripts to support system options on the OpenPandora."
LICENSE = "GPLV2"
LIC_FILES_CHKSUM = "file://${WORKDIR}/LICENSE;md5=b234ee4d69f5fce4486a80fdaf4a4263"

COMPATIBLE_MACHINE = "openpandora"

RDEPENDS_${PN} = "openpandora-scripts"

PR = "r2"

SRC_URI = " \
          file://LICENSE \
          file://op_wifi.sh \
          file://op_wifi.pnd \
          file://nettool.pnd \
          file://op_bluetooth.sh \
          file://op_bluetooth_work.sh \
          file://op_bluetooth-check.desktop \
          file://op_bluetooth.desktop \
"

do_install() {
          install -d ${D}${prefix}/pandora/scripts/
          install -m 0755 ${WORKDIR}/op_wifi.sh ${D}${prefix}/pandora/scripts/
          install -m 0755 ${WORKDIR}/op_bluetooth.sh ${D}${prefix}/pandora/scripts/
          install -m 0755 ${WORKDIR}/op_bluetooth_work.sh ${D}${prefix}/pandora/scripts/

          install -d ${D}${prefix}/pandora/apps/
	  install -m 0755 ${WORKDIR}/op_wifi.pnd ${D}${prefix}/pandora/apps/

	  install -d ${D}${prefix}/pandora/mmenu/
	  install -m 0755 ${WORKDIR}/nettool.pnd ${D}${prefix}/pandora/mmenu/

	  install -d ${D}${datadir}/applications/
          install -m 0644 ${WORKDIR}/op_bluetooth.desktop ${D}${datadir}/applications/

          install -d ${D}${sysconfdir}/xdg/autostart/
          install -m 0644 ${WORKDIR}/op_bluetooth-check.desktop ${D}${sysconfdir}/xdg/autostart/op_bluetooth-check.desktop

}

PACKAGE_ARCH = "${MACHINE_ARCH}"

FILES_${PN} += "${prefix} ${datadir}"

repository: DougBarry/meta-openpandora-vendor

repo_name: DougBarry/meta-openpandora-vendor


text:
package client

import (
	"encoding/hex"
	"reflect"
	"strconv"

	"github.com/broderickhyman/albiondata-client/lib"
	"github.com/broderickhyman/albiondata-client/log"
	"github.com/mitchellh/mapstructure"
)

func decodeRequest(params map[uint8]interface{}) (operation operation, err error) {
	if _, ok := params[253]; !ok {
		return nil, nil
	}

	code := params[253].(int16)

	switch OperationType(code) {
	case opGetGameServerByCluster:
		operation = &operationGetGameServerByCluster{}
	case opAuctionGetOffers:
		operation = &operationAuctionGetOffers{}
	case opAuctionGetItemAverageStats:
		operation = &operationAuctionGetItemAverageStats{}
	case opGetClusterMapInfo:
		operation = &operationGetClusterMapInfo{}
	case opGoldMarketGetAverageInfo:
		operation = &operationGoldMarketGetAverageInfo{}
	case opRealEstateGetAuctionData:
		operation = &operationRealEstateGetAuctionData{}
	case opRealEstateBidOnAuction:
		operation = &operationRealEstateBidOnAuction{}
	default:
		return nil, nil
	}

	err = decodeParams(params, operation)

	return operation, err
}

func decodeResponse(params map[uint8]interface{}) (operation operation, err error) {
	if _, ok := params[253]; !ok {
		return nil, nil
	}

	code := params[253].(int16)

	switch OperationType(code) {
	case opJoin:
		operation = &operationJoinResponse{}
	case opAuctionGetOffers:
		operation = &operationAuctionGetOffersResponse{}
	case opAuctionGetRequests:
		operation = &operationAuctionGetRequestsResponse{}
	case opAuctionBuyOffer:
		operation = &operationAuctionGetRequestsResponse{}
	case opAuctionGetItemAverageStats:
		operation = &operationAuctionGetItemAverageStatsResponse{}
	case opGetMailInfos:
		operation = &operationGetMailInfosResponse{}
	case opReadMail:
		operation = &operationReadMail{}
	case opGetClusterMapInfo:
		operation = &operationGetClusterMapInfoResponse{}
	case opGoldMarketGetAverageInfo:
		operation = &operationGoldMarketGetAverageInfoResponse{}
	case opRealEstateGetAuctionData:
		operation = &operationRealEstateGetAuctionDataResponse{}
	case opRealEstateBidOnAuction:
		operation = &operationRealEstateBidOnAuctionResponse{}
	default:
		return nil, nil
	}

	err = decodeParams(params, operation)

	return operation, err
}

func decodeEvent(params map[uint8]interface{}) (event operation, err error) {
	if _, ok := params[252]; !ok {
		return nil, nil
	}

	eventType := params[252].(int16)

	switch eventType {
	// case evRespawn: //TODO: confirm this eventCode (old 77)
	// 	event = &eventPlayerOnlineStatus{}
	// case evCharacterStats: //TODO: confirm this eventCode (old 114)
	// 	event = &eventSkillData{}
	default:
		return nil, nil
	}

	err = decodeParams(params, event)

	return event, err
}

func decodeParams(params map[uint8]interface{}, operation operation) error {
	convertGameObjects := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) {
		if from == reflect.TypeOf([]int8{}) && to == reflect.TypeOf(lib.CharacterID("")) {
			log.Debug("Parsing character ID from mixed-endian UUID")

			return decodeCharacterID(v.([]int8)), nil
		}

		return v, nil
	}

	config := mapstructure.DecoderConfig{
		DecodeHook: convertGameObjects,
		Result:     operation,
	}

	decoder, err := mapstructure.NewDecoder(&config)
	if err != nil {
		return err
	}

	// Decided that the maps were easier to work with in most places with uint8 keys
	// Therefore we have to convert to a string map in order for the decode to work here
	// Should be negligible performance loss
	stringMap := make(map[string]interface{})
	for k, v := range params {
		stringMap[strconv.Itoa(int(k))] = v
	}

	err = decoder.Decode(stringMap)

	return err
}

func decodeCharacterID(array []int8) lib.CharacterID {
	/* So this is a UUID, which is stored in a 'mixed-endian' format.
	The first three components are stored in little-endian, the rest in big-endian.
	See https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding.
	By default, our int array is read as big-endian, so we need to swap the first
	three components of the UUID
	*/
	b := make([]byte, len(array))

	// First, convert to byte
	for k, v := range array {
		b[k] = byte(v)
	}

	// swap first component
	b[0], b[1], b[2], b[3] = b[3], b[2], b[1], b[0]

	// swap second component
	b[4], b[5] = b[5], b[4]

	// swap third component
	b[6], b[7] = b[7], b[6]

	// format it UUID-style
	var buf [36]byte
	hex.Encode(buf[:], b[:4])
	buf[8] = '-'
	hex.Encode(buf[9:13], b[4:6])
	buf[13] = '-'
	hex.Encode(buf[14:18], b[6:8])
	buf[18] = '-'
	hex.Encode(buf[19:23], b[8:10])
	buf[23] = '-'
	hex.Encode(buf[24:], b[10:])

	return lib.CharacterID(buf[:])
}

repository: broderickhyman/albiondata-client

repo_name: broderickhyman/albiondata-client


text:
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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 api

import (
	"github.com/go-openapi/runtime"
	"github.com/go-openapi/runtime/client"
)

// AddTypeConsumers adds the missing consumers and producers to the
// client.Runtime. Even though a pointer is passed it is returned too.
func AddTypeConsumers(rtime *client.Runtime) *client.Runtime {
	rtime.Consumers["application/zip"] = runtime.ByteStreamConsumer()
	rtime.Producers["application/zip"] = runtime.ByteStreamProducer()
	rtime.Producers["multipart/form-data"] = runtime.ByteStreamProducer()
	return rtime
}

repository: elastic/cloud-sdk-go

repo_name: elastic/cloud-sdk-go


text:
.main-space {
  text-align: center;
  vertical-align: middle;
}
.main-space input[type="email"] {
  margin-bottom: 10px;
}
.main-space .chkbx {
  display: inline-block;
}
.main-space .checkbox-group {
  margin: 10px auto;
}
.main-space .checkbox-group label {
  font-weight: normal;
}
.form-signin-heading {
  text-transform: uppercase;
}

repository: iliasauer/zlogger

repo_name: iliasauer/zlogger

extension: css


text:
# this recipe is only intended for specific users, so don't choose it by default
DEFAULT_PREFERENCE = "-1"

RELEASE = "TIP_FW_L0_0.4.5_GOOGLE2_L1_0.3.4_GOOGLE2"

SRC_URI[bin.sha256sum] = "b5d53d13bf0a59e62b0e11152df2c4a8e08bdb5adfad98773e33e6117ff4c644"

require npcm8xx-tip-fw.inc

repository: HCLOpenBMC/openbmc

repo_name: HCLOpenBMC/openbmc


text:
require midori.inc

SRC_URI[md5sum] = "0b6eebdcedd224b2b9f437b706471762"
SRC_URI[sha256sum] = "3b449713a164d574031843ca38f37be12e3ac40804995b3e5a252562a598482f"


text:
@inproceedings{shen2018deep,
  title = {Adversarial Training Methods for Semi-supervised Text Classification},
  author = {Takeru Miyato and Andrew M Dai and Ian Goodfellow},
  booktitle = {International Conference on Learning Representations},
  year = {2017},
  url = {https://arxiv.org/pdf/1605.07725.pdf}
}

url: https://raw.githubusercontent.com/Hugh-Shi/DL-NLP-Readings/924e4d189e5660c5b5d4854278f3df755ae2231d/Bibtex/Adversarial Training Methods for Semi-supervised Text Classification.bib

repository: Hugh-Shi/DL-NLP-Readings

repo_name: Hugh-Shi/DL-NLP-Readings


text:
@book{linell2004written,
  title={The written language bias in linguistics: Its nature, origins and transformations},
  author={Linell, Per},
  year={2004},
  publisher={Routledge}
}

@misc{rickandmorty,
  title = {Rick and Morty Transcripts},
  howpublished = {\url{http://rickandmorty.wikia.com/}},
  note = {Accessed: 2018-04-22}
}

@inproceedings{norouzi2012hamming,
  title={Hamming distance metric learning},
  author={Norouzi, Mohammad and Fleet, David J and Salakhutdinov, Ruslan R},
  booktitle={Advances in neural information processing systems},
  pages={1061--1069},
  year={2012}
}

@article{gotoh1982improved,
  title={An improved algorithm for matching biological sequences},
  author={Gotoh, Osamu},
  journal={Journal of molecular biology},
  volume={162},
  number={3},
  pages={705--708},
  year={1982},
  publisher={Elsevier}
}

@article{beckner2009language,
  title={Language is a complex adaptive system: Position paper},
  author={Beckner, Clay and Blythe, Richard and Bybee, Joan and Christiansen, Morten H and Croft, William and Ellis, Nick C and Holland, John and Ke, Jinyun and Larsen-Freeman, Diane and Schoenemann, Tom},
  journal={Language learning},
  volume={59},
  number={s1},
  pages={1--26},
  year={2009},
  publisher={Wiley Online Library}
}

@article{medhat2014sentiment,
  title={Sentiment analysis algorithms and applications: A survey},
  author={Medhat, Walaa and Hassan, Ahmed and Korashy, Hoda},
  journal={Ain Shams Engineering Journal},
  volume={5},
  number={4},
  pages={1093--1113},
  year={2014},
  publisher={Elsevier}
}

@inproceedings{sutskever2011generating,
  title={Generating text with recurrent neural networks},
  author={Sutskever, Ilya and Martens, James and Hinton, Geoffrey E},
  booktitle={Proceedings of the 28th International Conference on Machine Learning (ICML-11)},
  pages={1017--1024},
  year={2011}
}

@article{YAN201715,
title = "Towards big topic modeling",
journal = "Information Sciences",
volume = "390",
pages = "15 - 31",
year = "2017",
issn = "0020-0255",
doi = "https://doi.org/10.1016/j.ins.2016.12.014",
author = "JianFeng Yan and Jia Zeng and Zhi-Qiang Liu and Lu Yang and Yang Gao",
keywords = "Big topic modeling, Latent Dirichlet allocation, Communication complexity, Multi-processor architecture, Online belief propagation, Power law"
}

@article{WENYIN20104031,
title = "A short text modeling method combining semantic and statistical information",
journal = "Information Sciences",
volume = "180",
number = "20",
pages = "4031 - 4041",
year = "2010",
issn = "0020-0255",
doi = "https://doi.org/10.1016/j.ins.2010.06.021",
author = "Liu Wenyin and Xiaojun Quan and Min Feng and Bite Qiu",
keywords = "Text similarity, Short text similarity, Information retrieval, Query expansion, Text mining, Question answering"
}

@inproceedings{Goldstein:1999:STD:312624.312665,
 author = {Goldstein, Jade and Kantrowitz, Mark and Mittal, Vibhu and Carbonell, Jaime},
 title = {Summarizing Text Documents: Sentence Selection and Evaluation Metrics},
 booktitle = {Proceedings of the 22Nd Annual International ACM SIGIR Conference on Research and Development in Information Retrieval},
 series = {SIGIR '99},
 year = {1999},
 isbn = {1-58113-096-1},
 location = {Berkeley, California, USA},
 pages = {121--128},
 numpages = {8},
 url = {http://doi.acm.org/10.1145/312624.312665},
 doi = {10.1145/312624.312665},
 acmid = {312665},
 publisher = {ACM},
 address = {New York, NY, USA},
}

@misc{dumais2001methods,
  title={Methods and apparatus for classifying text and for building a text classifier},
  author={Dumais, Susan T and Heckerman, David and Horvitz, Eric and Platt, John Carlton and Sahami, Mehran},
  year={2001},
  month=feb # "~20",
  publisher={Google Patents},
  note={US Patent 6,192,360}
}

@inproceedings{masataki1996variable,
  title={Variable-order N-gram generation by word-class splitting and consecutive word grouping},
  author={Masataki, Hirokazu and Sgisaka, Yoshinori},
  booktitle={Acoustics, Speech, and Signal Processing, 1996. ICASSP-96. Conference Proceedings., 1996 IEEE International Conference on},
  volume={1},
  pages={188--191},
  year={1996},
  organization={IEEE}
}

@article{yujian2007normalized,
  title={A normalized Levenshtein distance metric},
  author={Yujian, Li and Bo, Liu},
  journal={IEEE transactions on pattern analysis and machine intelligence},
  volume={29},
  number={6},
  pages={1091--1095},
  year={2007},
  publisher={IEEE}
}

@inproceedings{conroy2001text,
  title={Text summarization via hidden markov models},
  author={Conroy, John M and O'leary, Dianne P},
  booktitle={Proceedings of the 24th annual international ACM SIGIR conference on Research and development in information retrieval},
  pages={406--407},
  year={2001},
  organization={ACM}
}

@inproceedings{cohen2003comparison,
  title={A comparison of string metrics for matching names and records},
  author={Cohen, William and Ravikumar, Pradeep and Fienberg, Stephen},
  booktitle={Kdd workshop on data cleaning and object consolidation},
  volume={3},
  pages={73--78},
  year={2003}
}

@inproceedings{bird2004nltk,
  title={NLTK: the natural language toolkit},
  author={Bird, Steven and Loper, Edward},
  booktitle={Proceedings of the ACL 2004 on Interactive poster and demonstration sessions},
  pages={31},
  year={2004},
  organization={Association for Computational Linguistics}
}

@inproceedings{johnson2016densecap,
  title={Densecap: Fully convolutional localization networks for dense captioning},
  author={Johnson, Justin and Karpathy, Andrej and Fei-Fei, Li},
  booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
  pages={4565--4574},
  year={2016}
}

@inproceedings{honnibal2015improved,
  title={An improved non-monotonic transition system for dependency parsing},
  author={Honnibal, Matthew and Johnson, Mark},
  booktitle={Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing},
  pages={1373--1378},
  year={2015}
}

@article{DBLP:journals/corr/MikolovSCCD13,
  author    = {Tomas Mikolov and
               Ilya Sutskever and
               Kai Chen and
               Greg Corrado and
               Jeffrey Dean},
  title     = {Distributed Representations of Words and Phrases and their Compositionality},
  journal   = {CoRR},
  volume    = {abs/1310.4546},
  year      = {2013},
  url       = {http://arxiv.org/abs/1310.4546},
  archivePrefix = {arXiv},
  eprint    = {1310.4546},
  timestamp = {Wed, 07 Jun 2017 14:40:03 +0200},
}

@article{BICALHO201766,
title = "A general framework to expand short text for topic modeling",
journal = "Information Sciences",
volume = "393",
pages = "66 - 81",
year = "2017",
issn = "0020-0255",
doi = "https://doi.org/10.1016/j.ins.2017.02.007",
author = "Paulo Bicalho and Marcelo Pita and Gabriel Pedrosa and Anisio Lacerda and Gisele L. Pappa",
keywords = "Topic modeling, Short text, Word vector representation, Pseudo-documents"
}

@article{DBLP:journals/corr/abs-1103-0398,
  author    = {Ronan Collobert and
               Jason Weston and
               L{\'{e}}on Bottou and
               Michael Karlen and
               Koray Kavukcuoglu and
               Pavel P. Kuksa},
  title     = {Natural Language Processing (almost) from Scratch},
  journal   = {CoRR},
  volume    = {abs/1103.0398},
  year      = {2011},
  url       = {http://arxiv.org/abs/1103.0398},
  archivePrefix = {arXiv},
  eprint    = {1103.0398},
  timestamp = {Wed, 07 Jun 2017 14:43:14 +0200},
}

@article{DBLP:journals/corr/ZhangL15,
  author    = {Xiang Zhang and
               Yann LeCun},
  title     = {Text Understanding from Scratch},
  journal   = {CoRR},
  volume    = {abs/1502.01710},
  year      = {2015},
  url       = {http://arxiv.org/abs/1502.01710},
  archivePrefix = {arXiv},
  eprint    = {1502.01710},
  timestamp = {Wed, 07 Jun 2017 14:41:28 +0200},
}


text:
/*
* Copyright 2012-2020 Jason Woods and contributors
*
* 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 harvester

import (
	"bytes"
	"io"
	"testing"
)

func checkLine(t *testing.T, reader *LineReader, expected string, expectedLength int, expectedErr error) {
	line, length, err := reader.ReadItem()
	if line != nil || expectedErr == nil {
		if line == nil {
			t.Error("No line returned")
		} else if expectedLength == 0 {
			t.Errorf("Line data was not expected: [%s]", line)
		} else {
			if message, ok := line["message"].(string); !ok || message != expected {
				t.Errorf("Line data incorrect: [%s] (expected [%s])", message, expected)
			}
		}
	}
	if length != expectedLength {
		t.Errorf("Unexpected length: %d (expected %d)", length, expectedLength)
	}
	if err != expectedErr {
		t.Errorf("Unexpected error: %s", err)
	}
}

func checkBufferedLen(t *testing.T, reader *LineReader, expected int) {
	if reader.BufferedLen() != expected {
		t.Errorf("Incorrected buffered length: found %d != expected %d", reader.BufferedLen(), expected)
	}
}

func TestLineRead(t *testing.T) {
	data := bytes.NewBufferString("12345678901234567890\n12345678901234567890\n")

	// New line read with 100 bytes, enough for the above
	reader := NewLineReader(data, 100, 100)

	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, "", 0, io.EOF)
	checkBufferedLen(t, reader, 0)
}

func TestLineReadEmpty(t *testing.T) {
	data := bytes.NewBufferString("\n12345678901234567890\n")

	// New line read with 100 bytes, enough for the above
	reader := NewLineReader(data, 100, 100)

	checkLine(t, reader, string(""), 1, nil)
	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, "", 0, io.EOF)
	checkBufferedLen(t, reader, 0)
}

func TestLineReadIncomplete(t *testing.T) {
	data := bytes.NewBufferString("\n12345678901234567890\n123456")

	// New line read with 100 bytes, enough for the above
	reader := NewLineReader(data, 100, 100)

	checkLine(t, reader, string(""), 1, nil)
	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, "", 0, io.EOF)
	checkBufferedLen(t, reader, 6)
}

func TestLineReadOverflow(t *testing.T) {
	data := bytes.NewBufferString("12345678901234567890\n123456789012345678901234567890\n12345678901234567890\n")

	// New line read with 21 bytes buffer but 100 max line to trigger overflow
	reader := NewLineReader(data, 21, 100)

	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, string("123456789012345678901234567890"), 31, nil)
	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, "", 0, io.EOF)
	checkBufferedLen(t, reader, 0)
}

func TestLineReadOverflowTooLong(t *testing.T) {
	data := bytes.NewBufferString("12345678901234567890\n123456789012345678901234567890\n12345678901234567890\n")

	// New line read with 10 bytes buffer and 21 max line length
	// This test regression tests a really old bug where when a too long line
	// was received that overflowed in a way specific to these values it would
	// corrupt the entry
	reader := NewLineReader(data, 10, 21)

	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, string("123456789012345678901"), 21, ErrMaxDataSizeTruncation)
	// A continuation from a maxsizeexceeded should return same error so we can tag accordingly it is incomplete
	checkLine(t, reader, string("234567890"), 10, ErrMaxDataSizeTruncation)
	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, "", 0, io.EOF)
	checkBufferedLen(t, reader, 0)
}

func TestLineReadTooLong(t *testing.T) {
	data := bytes.NewBufferString("12345678901234567890\n123456789012345678901234567890\n12345678901234567890\n")

	// New line read with ample buffer and 21 max line length
	reader := NewLineReader(data, 100, 21)

	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, string("123456789012345678901"), 21, ErrMaxDataSizeTruncation)
	// A continuation from a maxsizeexceeded should return same error so we can tag accordingly it is incomplete
	checkLine(t, reader, string("234567890"), 10, ErrMaxDataSizeTruncation)
	checkLine(t, reader, string("12345678901234567890"), 21, nil)
	checkLine(t, reader, "", 0, io.EOF)
	checkBufferedLen(t, reader, 0)
}

repository: driskell/log-courier

repo_name: driskell/log-courier


text:
package challenge5

import (
	"fmt"
	"math/rand"
	"strings"
	"testing"
	"time"
)

func NewRand(t *testing.T) *rand.Rand {
	seed := time.Now().UnixNano()
	t.Logf("Random seed: %d", seed)
	return rand.New(rand.NewSource(seed))
}

func RandomizeString(rnd *rand.Rand, s string) string {
	result := []rune(s)
	for i := len(result) - 1; i > 0; i-- {
		idx := rnd.Int31n(int32(i))
		tmp := result[i]
		result[i] = result[idx]
		result[idx] = tmp
	}
	return string(result)
}

func TestRandomizeString(t *testing.T) {
	rnd := NewRand(t)
	source := "abcd"
	result := RandomizeString(rnd, source)
	if source == result {
		t.Error("String not randomized.")
	} else if len(source) != len(result) {
		t.Error("Randomized string length differs from source length.")
	} else if !strings.ContainsRune(result, 'a') || !strings.ContainsRune(result, 'b') || !strings.ContainsRune(result, 'c') || !strings.ContainsRune(result, 'd') {
		t.Error("Randomized string has different characters from source.")
	}
}

var asciiLetters = []rune("abcdefghijklmnopqrstuvwxyz")

func RandomAsciiRune(rnd *rand.Rand) rune {
	idx := rnd.Int31n(int32(len(asciiLetters)))
	return asciiLetters[idx]
}

func NewRandomAsciiString(rnd *rand.Rand, length int) string {
	result := make([]rune, length)
	for i := 0; i < length; i++ {
		result[i] = RandomAsciiRune(rnd)
	}
	return string(result)
}

func ExpectValid(t *testing.T, source, tester, result string) {
	ch, err := FindExtraLetter(source, tester)
	if err != nil {
		t.Error(err)
	} else if ch != result {
		t.Errorf("Result was not %s: %s", result, ch)
	} else {
		t.Logf("Valid %s vs %s finds %s", source, tester, ch)
	}
}

func ExpectError(t *testing.T, source, tester, error_substring string) {
	_, err := FindExtraLetter(source, tester)
	if err == nil {
		t.Error("No error generated")
	} else if !strings.Contains(err.Error(), error_substring) {
		t.Error("Unexpected error:", err)
	}
}

func TestSimple(t *testing.T) {
	ExpectValid(t, "a", "ab", "b")
}

func Test10As(t *testing.T) {
	ExpectValid(t, "aaaaaaaaaa", "aaaaaaaaaaa", "a")
}

func Test10Randomized(t *testing.T) {
	rnd := NewRand(t)
	source := "abcdefghij"
	tester := RandomizeString(rnd, "abcdefghijk")
	ExpectValid(t, source, tester, "k")
}

func Test1000Randomized(t *testing.T) {
	rnd := NewRand(t)
	source := NewRandomAsciiString(rnd, 1000)
	expect := string(RandomAsciiRune(rnd))
	tester := RandomizeString(rnd, fmt.Sprintf("%s%s", source, expect))
	ExpectValid(t, source, tester, expect)
}

func TestEmptySource(t *testing.T) {
	ExpectValid(t, "", "a", "a")
}

func TestEmptyTester(t *testing.T) {
	ExpectError(t, "a", "", "in source is not in target")
}

func TestSimpleEqual(t *testing.T) {
	ExpectError(t, "aaa", "aaa", "No difference found.")
}

func TestSimpleMultipleExactExtras(t *testing.T) {
	ExpectError(t, "aaa", "aaabb", "Target contains multiple letter")
}

func TestSimpleMultipleDifferentExtras(t *testing.T) {
	ExpectError(t, "aaa", "aaabc", "in target is a second extra. The first was")
}

func Test10RandomizedEqual(t *testing.T) {
	rnd := NewRand(t)
	source := "abcdefghij"
	tester := RandomizeString(rnd, source)
	ExpectError(t, source, tester, "No difference found.")
}

func Test1000RandomizedEqual(t *testing.T) {
	rnd := NewRand(t)
	source := NewRandomAsciiString(rnd, 1000)
	tester := RandomizeString(rnd, source)
	ExpectError(t, source, tester, "No difference found.")
}


text:
package config

import (
	"sync"

	"strings"

	"fmt"
	"os"

	"github.com/fatih/color"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var (
	settings Settings
	mu       sync.RWMutex
)

func init() {
	viper.SetConfigType("yaml")
	viper.SetConfigName(".prettylog")
	viper.AddConfigPath(".")
	viper.AddConfigPath("./..")
	viper.AddConfigPath("$HOME/")
}

func Load(verbose bool) {
	setDefaults()

	err := viper.ReadInConfig()
	if err != nil && verbose {
		fmt.Fprintf(os.Stderr, "error: failed to read configuration file: %v\n", err)
	}

	updateSettings(verbose)

	viper.OnConfigChange(func(e fsnotify.Event) {
		updateSettings(verbose)
	})
	viper.WatchConfig()
}

func updateSettings(verbose bool) {
	mu.Lock()
	defer mu.Unlock()

	err := viper.Unmarshal(&settings)
	if err != nil && verbose {
		fmt.Fprintf(os.Stderr, "error: failed to load configuration file: %v\n", err)
	}
}

func GetSettings() *Settings {
	mu.RLock()
	defer mu.RUnlock()

	return &settings
}

func setDefaults() {
	// Common settings
	setFieldDefaults("timestamp", "ts", true, 0, color.FgYellow, color.Faint)
	setFieldDefaults("logger", "logger", true, 10, color.FgWhite, color.Faint)
	setFieldDefaults("caller", "caller", false, 20, color.FgWhite, color.Faint)
	setFieldDefaults("level", "level", true, 5)
	setFieldDefaults("message", "msg", true, 40)

	// Level-specific settings
	viper.SetDefault("level.colors.debug", []color.Attribute{color.FgMagenta})
	viper.SetDefault("level.colors.info", []color.Attribute{color.FgBlue})
	viper.SetDefault("level.colors.warn", []color.Attribute{color.FgYellow})
	viper.SetDefault("level.colors.error", []color.Attribute{color.FgRed})
	viper.SetDefault("level.colors.fatal", []color.Attribute{color.FgRed, color.Bold})
}

func setFieldDefaults(name string, key string, visible bool, padding int, colorAttrs ...color.Attribute) {
	viper.SetDefault(name+".key", key)
	viper.SetDefault(name+".visible", visible)
	viper.SetDefault(name+".padding", padding)
	viper.SetDefault(name+".color", colorAttrs)
}

type Field struct {
	Key     string
	Visible bool
	Padding int
	Color   []color.Attribute
}

type Settings struct {
	Timestamp TimestampField
	Logger    Field
	Caller    Field
	Level     LevelField
	Message   Field
}

type TimestampField struct {
	Field  `mapstructure:",squash"`
	Format string
}

type LevelField struct {
	Field  `mapstructure:",squash"`
	Colors map[string][]color.Attribute
}

func (f *LevelField) GetColorAttr(level string) []color.Attribute {
	if c, exists := f.Colors[strings.ToLower(level)]; exists {
		return c
	} else {
		return []color.Attribute{}
	}
}

repository: RaphaelVRossi/prettylog

repo_name: RaphaelVRossi/prettylog


text:
package main

import (
	"bytes"
	"fmt"
	"os"

	"golang.org/x/crypto/ssh"
)

// SSHCommand runs a command over ssh
func SSHCommand(user string, password string, host string, port string, app string, command string) string {
	config := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}

	fmt.Println("ssh " + user + "@" + host + ":" + port)

	conn, err := ssh.Dial("tcp", host+":"+port, config)
	if err != nil {
		fmt.Printf("Failed to connect to %v\n", host+":"+port)
		fmt.Println(err)
		os.Exit(2)
	}

	session, err := conn.NewSession()
	if err != nil {
		fmt.Printf("Cannot create SSH session to %v\n", host+":"+port)
		fmt.Println(err)
		os.Exit(2)
	}

	defer session.Close()

	// Create buffers for stdout and stderr
	var o, e bytes.Buffer

	session.Stdout = &o
	session.Stderr = &e

	// Run a command with Run and read stdout and stderr
	if err := session.Run("cd ~/" + app + "&& phenv python2.7 /opt/phantom/bin/compile_app.pyc -i"); err != nil {
		fmt.Println("Error running command", err)
	}

	if e.String() != "" {
		return fmt.Sprintf("Error: %s", e.String())
	}

	return fmt.Sprintf(o.String())
}

repository: ryanplasma/ouija

repo_name: ryanplasma/ouija


text:
require gst-plugins.inc

SRC_URI += "file://0001-opencv-update-to-opencv-2.2-api-for-cvHaarDetectObje.patch"

SRC_URI[archive.md5sum] = "f501336ab1d18d2565f47c36ce653a82"
SRC_URI[archive.sha256sum] = "422badacbda37ac33cb446c6751dabcd0b223c308dbb01024a34ded682fa47e3"

DEPENDS += "opencv orc-native orc libcdaudio gst-plugins-base openssl directfb libmodplug librsvg"

PR = "${INC_PR}.0"

# We don't have vdpau headers in OE and it creates crosscompile badness.
# Also, mpeg2enc and mplex from mjpegtools don't build, because of AC_TRY_RUN.
EXTRA_OECONF += " \
        --disable-mpeg2enc \
        --disable-mplex \
        --disable-vdpau \
"

PACKAGES_DYNAMIC = "\
gst-plugin-adpcmdec* \
gst-plugin-adpcmenc* \
gst-plugin-aiff* \
gst-plugin-apexsink* \
gst-plugin-asfmux* \
gst-plugin-audioparsersbad* \
gst-plugin-autoconvert* \
gst-plugin-bayer* \
gst-plugin-bz2* \
gst-plugin-camerabin* \
gst-plugin-cdxaparse* \
gst-plugin-cog* \
gst-plugin-coloreffects* \
gst-plugin-colorspace* \
gst-plugin-dataurisrc* \
gst-plugin-dccp* \
gst-plugin-debugutilsbad* \
gst-plugin-dfbvideosink* \
gst-plugin-dtmf* \
gst-plugin-dvb* \
gst-plugin-dvbsuboverlay* \
gst-plugin-dvdspu* \
gst-plugin-faac* \
gst-plugin-faad* \
gst-plugin-fbdevsink* \
gst-plugin-festival* \
gst-plugin-freeze* \
gst-plugin-frei0r* \
gst-plugin-gaudieffects* \
gst-plugin-geometrictransform* \
gst-plugin-gsettingselements* \
gst-plugin-gsm* \
gst-plugin-h264parse* \
gst-plugin-hdvparse* \
gst-plugin-id3tag* \
gst-plugin-interlace* \
gst-plugin-invtelecine* \
gst-plugin-ivfparse* \
gst-plugin-jp2k* \
gst-plugin-jp2kdecimator* \
gst-plugin-jpegformat* \
gst-plugin-legacyresample* \
gst-plugin-liveadder* \
gst-plugin-mms* \
gst-plugin-modplug* \
gst-plugin-mpeg4videoparse* \
gst-plugin-mpegdemux* \
gst-plugin-mpegpsmux* \
gst-plugin-mpegtsmux* \
gst-plugin-mpegvideoparse* \
gst-plugin-mve* \
gst-plugin-mxf* \
gst-plugin-nsf* \
gst-plugin-nuvdemux* \
gst-plugin-opencv* \
gst-plugin-pcapparse* \
gst-plugin-pnm* \
gst-plugin-qtmux* \
gst-plugin-rawparse* \
gst-plugin-rfbsrc* \
gst-plugin-rsvg* \
gst-plugin-rtpmux* \
gst-plugin-scaletempoplugin* \
gst-plugin-schro* \
gst-plugin-sdl* \
gst-plugin-sdpelem* \
gst-plugin-segmentclip* \
gst-plugin-shm* \
gst-plugin-siren* \
gst-plugin-sndfile* \
gst-plugin-speed* \
gst-plugin-stereo* \
gst-plugin-subenc* \
gst-plugin-tta* \
gst-plugin-vcdsrc* \
gst-plugin-videomaxrate* \
gst-plugin-videomeasure* \
gst-plugin-videosignal* \
gst-plugin-vmnc* \
gst-plugin-vp8* \
gst-plugin-y4mdec* \
"

repository: balister/openembedded

repo_name: balister/openembedded