text:
// Copyright 2018 vip.com.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package stablestore

import (
	"errors"
	"path"

	"os"

	"github.com/boltdb/bolt"
	"github.com/vipshop/vdl/pkg/glog"
	"github.com/vipshop/vdl/vdlfiu"
	"vipshop.com/distributedstorage/fiu"
)

const (
	VDLMetadataFile = "vdl.db"
	BucketName      = "vdl_metadata"
)

type BoltDBStoreConfig struct {
	//boltdb dir
	Dir string
}

type BoltDBStore struct {
	Conf       *BoltDBStoreConfig
	DB         *bolt.DB
	BucketName []byte
}

func NewBoltDBStore(conf *BoltDBStoreConfig) (*BoltDBStore, error) {
	if conf == nil || len(conf.Dir) == 0 {
		return nil, errors.New("args not available")
	}
	//if dir not exist, make dir
	if isFileExist(conf.Dir) == false {
		err := os.MkdirAll(conf.Dir, 0700)
		if err != nil {
			return nil, err
		}
	}
	dbFilePath := path.Join(conf.Dir, VDLMetadataFile)
	db, err := bolt.Open(dbFilePath, 0600, nil)
	if err != nil {
		glog.Errorf("[stable_bolt.go-NewBoltDBStore]:bolt Open error,err=%s,dbpath=%s", err.Error(), dbFilePath)
		return nil, err
	}

	s := &BoltDBStore{
		Conf:       conf,
		DB:         db,
		BucketName: []byte(BucketName),
	}
	s.initialize()
	return s, nil
}

func (s *BoltDBStore) Put(key []byte, value []byte) error {

	// mock error
	if fiu.IsSyncPointExist(vdlfiu.FiuStableStoreWriteError) {
		return errors.New("Mock FiuStableStoreWriteError")
	}
	// mock error
	if fiu.IsSyncPointExist(vdlfiu.FiuStableStoreWriteDelay) {
		vdlfiu.SleepRandom(2000, 4000)
	}
	return s.DB.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.BucketName)
		err := b.Put(key, value)
		if err != nil {
			glog.Fatalf("[stable_bolt.go-Put]::err=%s,key=%s", err.Error(), string(key))
		}
		return nil
	})
}

func (s *BoltDBStore) Get(key []byte) ([]byte, error) {

	// mock error
	if fiu.IsSyncPointExist(vdlfiu.FiuStableStoreReadError) {
		return nil, errors.New("Mock FiuStableStoreReadError")
	}

	// mock error
	if fiu.IsSyncPointExist(vdlfiu.FiuStableStoreReadDelay) {
		vdlfiu.SleepRandom(2000, 4000)
	}

	tx, err := s.DB.Begin(false)
	if err != nil {
		return nil, err
	}
	defer tx.Rollback()

	bucket := tx.Bucket(s.BucketName)
	val := bucket.Get(key)
	return val, nil
}

func (s *BoltDBStore) Close() error {
	s.DB.Close()
	return nil
}

func isFileExist(filePath string) bool {
	if len(filePath) == 0 {
		return false
	}
	_, err := os.Stat(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
		glog.Errorf("[stable_bolt.go-isFileExist]:stat error:error=%s,dir=%s", err.Error(), filePath)
		return false
	}
	return true
}

// initialize is used to set up all of the buckets.
func (s *BoltDBStore) initialize() error {
	tx, err := s.DB.Begin(true)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// Create bucket
	if _, err := tx.CreateBucketIfNotExists(s.BucketName); err != nil {
		glog.Fatalf("[stable_bolt.go-initialize]:CreateBucketIfNotExists error:error=%s,BucketName=%s",
			err.Error(), string(s.BucketName))
		return err
	}

	return tx.Commit()
}

func (s *BoltDBStore) GetBatch(keys []string) (map[string][]byte, error) {
	result := make(map[string][]byte)
	err := s.DB.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(BucketName))
		for _, key := range keys {
			if len(key) != 0 {
				result[key] = bucket.Get([]byte(key))
			} else {
				glog.Warningf("GetBatch key is nil,keys=%v", keys)
			}
		}
		return nil
	})
	if err != nil {
		glog.Errorf("GetBatch error,err=%s,keys=%v", err.Error(), keys)
		return nil, err
	}
	return result, nil
}

repository: xuxueyun-one/vdl

repo_name: xuxueyun-one/vdl


text:
package dialect

import (
	"regexp"
	"strings"
	"testing"

	"github.com/posener/orm"
	"github.com/posener/orm/dialect/builder"
	"github.com/stretchr/testify/assert"
)

const table = "name"

func TestSelect(t *testing.T) {
	t.Parallel()

	tests := []struct {
		sel      SelectParams
		wantStmt string
		wantArgs []interface{}
	}{
		{
			sel:      SelectParams{Columns: map[string]bool{"col": true}, OrderedColumns: []string{"col"}},
			wantStmt: "SELECT `name`.`col` FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"col": true},
				OrderedColumns: []string{"col"},
				Page:           Page{},
			},
			wantStmt: "SELECT `name`.`col` FROM `name`",
		},
		{
			sel:      SelectParams{Count: true},
			wantStmt: "SELECT COUNT(*) FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"a": true, "b": true, "c": true},
				OrderedColumns: []string{"a", "b", "c"},
				Count:          true,
			},
			wantStmt: "SELECT `name`.`a`, `name`.`b`, `name`.`c`, COUNT(*) FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"a": true, "b": true, "c": true},
				OrderedColumns: []string{"a", "c", "b"},
				Count:          true,
			},
			wantStmt: "SELECT `name`.`a`, `name`.`c`, `name`.`b`, COUNT(*) FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"a": true, "b": true, "c": true},
				OrderedColumns: []string{"a", "c", "b"},
			},
			wantStmt: "SELECT `name`.`a`, `name`.`c`, `name`.`b` FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"col": true},
				OrderedColumns: []string{"col"},
				Page:           Page{},
			},
			wantStmt: "SELECT `name`.`col` FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"col": true},
				OrderedColumns: []string{"col"},
				Page:           Page{Limit: 1},
			},
			wantStmt: "SELECT `name`.`col` FROM `name` LIMIT 1",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"col": true},
				OrderedColumns: []string{"col"},
				Page:           Page{Limit: 1, Offset: 2},
			},
			wantStmt: "SELECT `name`.`col` FROM `name` LIMIT 1 OFFSET 2",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"col": true},
				OrderedColumns: []string{"col"},
				Page:           Page{Offset: 1},
			},
			wantStmt: "SELECT `name`.`col` FROM `name`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"a": true, "b": true, "c": true},
				OrderedColumns: []string{"a", "b", "c"},
				Count:          true,
				Page:           Page{Limit: 1, Offset: 2},
			},
			wantStmt: "SELECT `name`.`a`, `name`.`b`, `name`.`c`, COUNT(*) FROM `name` LIMIT 1 OFFSET 2",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"a": true},
				OrderedColumns: []string{"a"},
				Groups:         Groups{{Column: "a"}, {Column: "b"}},
			},
			wantStmt: "SELECT `name`.`a` FROM `name` GROUP BY `name`.`a`, `name`.`b`",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"c": true},
				OrderedColumns: []string{"c"},
				Orders: Orders{
					{Column: "c", Dir: "ASC"},
					{Column: "d", Dir: "DESC"},
				},
			},
			wantStmt: "SELECT `name`.`c` FROM `name` ORDER BY `name`.`c` ASC, `name`.`d` DESC",
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"k": true},
				OrderedColumns: []string{"k"},
				Where:          NewWhere(orm.OpEq, "k", 3),
			},
			wantStmt: "SELECT `name`.`k` FROM `name` WHERE `name`.`k` = ?",
			wantArgs: []interface{}{3},
		},
		{
			sel: SelectParams{
				Columns:        map[string]bool{"a": true, "b": true, "c": true},
				OrderedColumns: []string{"a", "b", "c"},
				Count:          true,
				Where:          NewWhere(orm.OpGt, "k", 3),
				Groups:         Groups{{Column: "a"}, {Column: "b"}},
				Orders: Orders{
					{Column: "c", Dir: "ASC"},
					{Column: "d", Dir: "DESC"},
				},
				Page: Page{Limit: 1, Offset: 2},
			},
			wantStmt: "SELECT `name`.`a`, `name`.`b`, `name`.`c`, COUNT(*) FROM `name` WHERE `name`.`k` > ? GROUP BY `name`.`a`, `name`.`b` ORDER BY `name`.`c` ASC, `name`.`d` DESC LIMIT 1 OFFSET 2",
			wantArgs: []interface{}{3},
		},
	}

	for _, tt := range tests {
		t.Run(tt.wantStmt, func(t *testing.T) {
			tt.sel.Table = table
			stmt, args := Get("mysql").Select(&tt.sel)
			assert.Equal(t, tt.wantStmt, reduceSpaces(stmt), " ")
			assert.Equal(t, tt.wantArgs, args)
		})
	}
}

func TestInsert(t *testing.T) {
	t.Parallel()

	tests := []struct {
		assign   Assignments
		wantStmt string
		wantArgs []interface{}
	}{
		{
			wantStmt: "INSERT INTO `name` () VALUES ()",
			wantArgs: []interface{}(nil),
		},
		{
			assign:   Assignments{{Column: "c1", ColumnValue: 1}},
			wantStmt: "INSERT INTO `name` (`c1`) VALUES (?)",
			wantArgs: []interface{}{1},
		},
		{
			assign:   Assignments{{Column: "c1", ColumnValue: 1}, {Column: "c2", ColumnValue: ""}},
			wantStmt: "INSERT INTO `name` (`c1`, `c2`) VALUES (?, ?)",
			wantArgs: []interface{}{1, ""},
		},
	}

	for _, tt := range tests {
		t.Run(tt.wantStmt, func(t *testing.T) {
			params := &InsertParams{Table: table, Assignments: tt.assign}
			stmt, args := Get("mysql").Insert(params)
			assert.Equal(t, tt.wantStmt, reduceSpaces(stmt), " ")
			assert.Equal(t, tt.wantArgs, args, " ")
		})
	}
}

func TestUpdate(t *testing.T) {
	t.Parallel()

	tests := []struct {
		assign   Assignments
		where    Where
		wantStmt string
		wantArgs []interface{}
	}{
		{
			wantStmt: "UPDATE `name` SET",
			wantArgs: []interface{}(nil),
		},
		{
			assign:   Assignments{{Column: "c1", ColumnValue: 1}},
			wantStmt: "UPDATE `name` SET `c1` = ?",
			wantArgs: []interface{}{1},
		},
		{
			assign:   Assignments{{Column: "c1", ColumnValue: 1}, {Column: "c2", ColumnValue: ""}},
			wantStmt: "UPDATE `name` SET `c1` = ?, `c2` = ?",
			wantArgs: []interface{}{1, ""},
		},
		{
			assign:   Assignments{{Column: "c1", ColumnValue: 1}, {Column: "c2", ColumnValue: ""}},
			where:    NewWhere(orm.OpGt, "k", 3),
			wantStmt: "UPDATE `name` SET `c1` = ?, `c2` = ? WHERE `name`.`k` > ?",
			wantArgs: []interface{}{1, "", 3},
		},
	}

	for _, tt := range tests {
		t.Run(tt.wantStmt, func(t *testing.T) {
			params := &UpdateParams{Table: table, Assignments: tt.assign, Where: tt.where}
			stmt, args := Get("mysql").Update(params)
			assert.Equal(t, tt.wantStmt, reduceSpaces(stmt), " ")
			assert.Equal(t, tt.wantArgs, args)
		})
	}
}

func TestDelete(t *testing.T) {
	t.Parallel()

	tests := []struct {
		where    Where
		wantStmt string
		wantArgs []interface{}
	}{
		{
			wantStmt: "DELETE FROM `name`",
			wantArgs: []interface{}(nil),
		},
		{
			where:    NewWhere(orm.OpGt, "k", 3),
			wantStmt: "DELETE FROM `name` WHERE `name`.`k` > ?",
			wantArgs: []interface{}{3},
		},
	}

	for _, tt := range tests {
		t.Run(tt.wantStmt, func(t *testing.T) {
			params := &DeleteParams{Table: table, Where: tt.where}
			stmt, args := Get("mysql").Delete(params)
			assert.Equal(t, tt.wantStmt, reduceSpaces(stmt), " ")
			assert.Equal(t, tt.wantArgs, args)
		})
	}
}

func TestColumnsJoin(t *testing.T) {
	t.Parallel()
	tests := []struct {
		p        SelectParams
		wantCols string
		wantJoin string
	}{
		{
			p: SelectParams{Table: "table"},
		},
		{
			p:        SelectParams{Table: "table", Count: true},
			wantCols: "COUNT(*)",
		},
		{
			p: SelectParams{
				Table:          "table",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"a", "b"},
			},
			wantCols: "`table`.`a`, `table`.`b`",
		},
		{
			p: SelectParams{
				Table:          "table",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"a", "b"},
				Count:          true,
			},
			wantCols: "`table`.`a`, `table`.`b`, COUNT(*)",
		},
		{
			p: SelectParams{
				Table:          "table",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"b", "a"},
				Count:          true,
			},
			wantCols: "`table`.`b`, `table`.`a`, COUNT(*)",
		},
		{
			p: SelectParams{
				Table:          "table",
				Columns:        map[string]bool{"a": true, "b": true},
				Count:          true,
				OrderedColumns: []string{"a", "b"},
			},
			wantCols: "`table`.`a`, `table`.`b`, COUNT(*)",
		},
		{
			p: SelectParams{
				Table: "A",
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{
							Table: "B",
						},
						Pairings: []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`)",
		},
		{
			p: SelectParams{
				Table: "A",
				Count: true,
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{Table: "B"},
						Pairings:     []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "COUNT(*)",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`)",
		},
		{
			p: SelectParams{
				Table:          "A",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"a", "b"},
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{Table: "B"},
						Pairings:     []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "`A`.`a`, `A`.`b`",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`)",
		},
		{
			p: SelectParams{
				Table: "A",
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{
							Table:          "B",
							Columns:        map[string]bool{"c": true, "d": true},
							OrderedColumns: []string{"c", "d"},
						},
						Pairings: []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "`A_B_B_id`.`c`, `A_B_B_id`.`d`",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`)",
		},
		{
			p: SelectParams{
				Table:          "A",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"a", "b"},
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{
							Table:          "B",
							Columns:        map[string]bool{"c": true, "d": true},
							OrderedColumns: []string{"c", "d"},
						},
						Pairings: []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "`A`.`a`, `A`.`b`, `A_B_B_id`.`c`, `A_B_B_id`.`d`",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`)",
		},
		{
			p: SelectParams{
				Table:          "A",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"a", "b"},
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{
							Table:          "B",
							Columns:        map[string]bool{"c": true, "d": true},
							OrderedColumns: []string{"c", "d"},
						},
						Pairings: []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
					{
						SelectParams: SelectParams{
							Table:          "C",
							Columns:        map[string]bool{"e": true, "f": true},
							OrderedColumns: []string{"e", "f"},
						},
						Pairings: []Pairing{{Column: "C_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "`A`.`a`, `A`.`b`, `A_B_B_id`.`c`, `A_B_B_id`.`d`, `A_C_C_id`.`e`, `A_C_C_id`.`f`",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`) LEFT OUTER JOIN `C` AS `A_C_C_id` ON (`A`.`C_id` = `A_C_C_id`.`id`)",
		},
		{
			p: SelectParams{
				Table:          "A",
				Columns:        map[string]bool{"a": true, "b": true},
				OrderedColumns: []string{"a", "b"},
				Joins: []JoinParams{
					{
						SelectParams: SelectParams{
							Table:          "B",
							Columns:        map[string]bool{"c": true, "d": true},
							OrderedColumns: []string{"c", "d"},
							Joins: []JoinParams{
								{
									SelectParams: SelectParams{
										Table:          "D",
										Columns:        map[string]bool{"g": true, "h": true},
										OrderedColumns: []string{"g", "h"},
									},
									Pairings: []Pairing{{Column: "D_id", JoinedColumn: "id"}},
								},
							},
						},
						Pairings: []Pairing{{Column: "B_id", JoinedColumn: "id"}},
					},
					{
						SelectParams: SelectParams{
							Table:          "C",
							Columns:        map[string]bool{"e": true, "f": true},
							OrderedColumns: []string{"e", "f"},
						},
						Pairings: []Pairing{{Column: "C_id", JoinedColumn: "id"}},
					},
				},
			},
			wantCols: "`A`.`a`, `A`.`b`, `A_B_B_id`.`c`, `A_B_B_id`.`d`, `A_B_B_id_D_D_id`.`g`, `A_B_B_id_D_D_id`.`h`, `A_C_C_id`.`e`, `A_C_C_id`.`f`",
			wantJoin: "LEFT OUTER JOIN `B` AS `A_B_B_id` ON (`A`.`B_id` = `A_B_B_id`.`id`) LEFT OUTER JOIN `D` AS `A_B_B_id_D_D_id` ON (`A_B_B_id`.`D_id` = `A_B_B_id_D_D_id`.`id`) LEFT OUTER JOIN `C` AS `A_C_C_id` ON (`A`.`C_id` = `A_C_C_id`.`id`)",
		},
	}

	for _, tt := range tests {
		t.Run(tt.wantCols, func(t *testing.T) {
			d := Get("mysql").(*dialect)

			b := builder.New(d, "")
			buildSelectColumns(b, &tt.p)
			assert.Equal(t, tt.wantCols, strings.Trim(b.Statement(), " "))

			b = builder.New(d, "")
			buildJoin(b, &tt.p)
			assert.Equal(t, tt.wantJoin, strings.Trim(b.Statement(), " "))
		})
	}
}

func reduceSpaces(s string) string {
	re := regexp.MustCompile("([ ]+)")
	return strings.Trim(re.ReplaceAllString(s, " "), " ")
}

license: MIT

repository: posener/orm

license_type: permissive

repo_name: posener/orm

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: Go

extension: go


text:
# Installs the ADU Agent Service that will auto-start the ADU Agent
# and pass in the IoT Hub connection string located at /boot/iot-con-string.txt.

LICENSE="CLOSED"

SRC_URI = "\
    file://adu-agent.service \
"

SYSTEMD_SERVICE_${PN} = "adu-agent.service"

do_install_append() {
    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${WORKDIR}/adu-agent.service ${D}${systemd_system_unitdir}
}

FILES_${PN} += "${systemd_system_unitdir}/adu-agent.service"

REQUIRED_DISTRO_FEATURES = "systemd"

DEPENDS += "azure-device-update deliveryoptimization-agent-service"
RDEPENDS_${PN} += "azure-device-update deliveryoptimization-agent-service"

inherit allarch systemd

extension: bb


text:
@article{hawkins2017driver,
 author = {Hawkins, AN and Filtness, Ashleigh J},
 journal = {Accident Analysis & Prevention},
 pages = {459--464},
 publisher = {Elsevier},
 title = {Driver sleepiness on YouTube: A content analysis},
 volume = {99},
 year = {2017}
}

license: Unlicense,MIT

detected_licenses: Unlicense MIT

gha_license_id: NOASSERTION

extension: bib


text:
@inproceedings{Harashima2010,
 author    = "Jun Harashima and Sadao Kurohashi",
 title     = "{Summarizing Search Results using PLSI}",
 booktitle = "Proceedings of the 2nd Workshop on NLP Challenges in the Information Explosion Era (NLPIX 2010)",
 pages     = "12-20",
 year      = "2010",
}

gha_language: HTML


text:
package main

import (
	_ "embed"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/kanyways/wechat-robot/config"
	"github.com/kanyways/wechat-robot/model"
	"github.com/kanyways/wechat-robot/router"
	"io"
	"os"
)

func main() {
	fmt.Println("gin.Version: ", gin.Version)
	if config.ServerConfig.Env != model.DevelopmentMode {
		gin.SetMode(gin.ReleaseMode)
		// Disable Console Color, you don't need console color when writing the logs to file.
		gin.DisableConsoleColor()
		// Logging to a file.
		logFile, err := os.OpenFile(config.ServerConfig.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
		if err != nil {
			fmt.Printf(err.Error())
			os.Exit(-1)
		}
		gin.DefaultWriter = io.MultiWriter(logFile)
	}
	app := gin.Default()
	router.Route(app)
	app.Run(":" + fmt.Sprintf("%d", config.ServerConfig.Port))
}

repository: kanyways/wechat-robot

repo_name: kanyways/wechat-robot


text:
#include "stdafx.h"
#include "XmlParser.h"
using namespace std;

unsigned int CObjectFactory::m_initialClassInfoArraySize = 0;
static const char HORIZONTAL_TAB		= (char)0x09;
static const char HT = HORIZONTAL_TAB;
static const char LINE_FEED				= (char)0x0a;
static const char LF = LINE_FEED;
static const char CARRIAGE_RETURN		= (char)0x0d;
static const char CR = CARRIAGE_RETURN;
static const char SPACE_KEY				= (char)0x20;
static const char SP = SPACE_KEY;

XMLabel::XMLabel()
:m_bLabelClose(false)
,m_bLabelHeadClose(false)
,m_bLabelTailClose(false)
,m_pParent(NULL)
{

}

void XMLabel::SetLabelClassName(const string className)
{
	m_labelClassName = className;
}

string XMLabel::GetLabelClassName()
{
	return m_labelClassName;
}

void XMLabel::SetLabelValue(const string value)
{
	m_labelValue = value;
}

string XMLabel::GetLabelValue()
{
	return m_labelValue;
}

void XMLabel::SetLabelId(const string labelId)
{
	m_labelId = labelId;
}

string XMLabel::GetLabelId()
{
	return m_labelId;
}

void XMLabel::SetParent(XMLabel* pParent)
{
	m_pParent = pParent;
}
XMLabel* XMLabel::GetParent()
{
	return m_pParent;
}

void XMLabel::SetLabelHeadClose(bool bClose)
{
	m_bLabelHeadClose = bClose;
}

bool XMLabel::GetLabelHeadClose()
{
	return m_bLabelHeadClose;
}

void XMLabel::SetLabelTailClose(bool bClose)
{
	m_bLabelTailClose = bClose;
}

bool XMLabel::GetLabelTailClose()
{
	return m_bLabelTailClose;
}

//this few functions should be in UEObject Class
XMLERROR XMLabel::AddChild(XMLabel* pChild)
{
	set<XMLabel*>::iterator iter = m_pChildrenSet.find(pChild);

	if (iter != m_pChildrenSet.end()){
		return XML_WRONG_CHILDREN_ID_RECOVER;
	}
	m_pChildrenSet.insert(pChild);
	return XML_SUCCESS;
}

XMLERROR XMLabel::RemoveChildById(string childId)
{
	set<XMLabel*>::iterator iter;
	for (iter=m_pChildrenSet.begin(); m_pChildrenSet.end() != iter; ++iter)
	{
		if ((*iter)->GetLabelId() == childId)
		{
			m_pChildrenSet.erase(iter);
			//Dispatch event
			return XML_SUCCESS;
		}
	}
	return XML_WRONG_CHILDREN_ID_NOTFOUND;
}

XMLERROR XMLabel::SetAttribute(string key, string value)
{
	m_labelAttrMap.insert(std::pair<string, string>(key, value));
	return XML_SUCCESS;
}

string XMLabel::GetAttribute(string key)
{
	map<string, string>::iterator iter = m_labelAttrMap.find(key);
	if (m_labelAttrMap.end() != iter)
		return (*iter).second;

	return NULL;
}

XMLERROR XMLabel::AddAttribute(map<string, string> *paraMap)
{
	string attrKey;
	string attrValue;
	map<string, string>::iterator iter;
	for (iter=paraMap->begin(); iter!=paraMap->end(); ++iter)
	{
		attrKey = iter->first;
		attrValue = iter->second;
		m_labelAttrMap.insert(std::pair<string, string>(attrKey, attrValue));
	}
	return XML_SUCCESS;
}

XMLERROR XMLabel::HandleAttrLabel()
{
	XMLabel* attrObj ;//= m_pChildrenSet.find();
	if (NULL == attrObj)
		return XML_SUCCESS;
	if (attrObj->GetLabelClassName() != "attr")
		return XML_ERROR_UNKNOWN;
	//list<XMLabel>::iterator iter = attrObj->
	return XML_ERROR_UNKNOWN;
}

void XMLabel::SetLabelClose(bool bClose)
{
	m_bLabelClose = bClose;
}
bool XMLabel::GetLabelClose()
{
	return m_bLabelClose;
}
////////////////////////////////////////////////////////////////
//UTF-8是一种变长字节编码方式，第一字节高位连续的1的个数代表了该
//字符占得字节数，其余字节皆以10开头
//1字节 0xxxxxxx (ANSI 字符)
//2字节 110xxxxx 10xxxxxx
//3字节 1110xxxx 10xxxxxx 10xxxxxx
//........
//6字节 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
//注意: 若一个ANSI编码的文本文件中，全部是英文字符，则其文件编码
//与UTF8 无BOM编码一模一样，这种情况下，也认为是UTF8无BOM编码
bool XMLFile::CheckFileEncoding(LPCWSTR pszFilePath)
{//若是UTF8 无 BOM编码，返回文件句柄，避免后面重复openfile
	//BOOL ret = ::PathFileExists(pszFilePath);
	//if (!ret) return FALSE;

	std::ifstream inFile(pszFilePath, ios::in|ios::binary);
	if (!inFile) return false;

	char byteFirst  = 0;
	char byteSecond = 0;
	char byteThird  = 0;

	inFile.read(&byteFirst, sizeof(char));
	inFile.read(&byteSecond, sizeof(char));
	inFile.read(&byteThird, sizeof(char));

	if (0xEF == (BYTE)byteFirst && 0xBB == (BYTE)byteSecond && 0xBF == (BYTE)byteThird)
	{//UTF-8 BOM头为文件前三字节：0xEF、0xBB、0xBF
		inFile.close();
		cout<<"UTF-8 带BOM编码"<<endl;
		return false;//UTF8 带 BOM 编码
	}

	//将文件扫一遍，整个文件的编码若符合UTF8编码规则，则可认为其为UTF8 无 BOM编码
	inFile.seekg(0);
	char byteTmp = 0;
	BYTE byteCount = 0;

	while (!inFile.eof())
	{
		inFile.read(&byteFirst, sizeof(char));
		if ((byteFirst & 0x80) == 0 )
			continue;
		else if ((byteFirst & 0xFC) == 0xFC )
			byteCount = 6;
		else if ((byteFirst & 0xF8) == 0xF8 )
			byteCount = 5;
		else if ((byteFirst & 0xF0) == 0xF0 )
			byteCount = 4;
		else if ((byteFirst & 0xE0) == 0xE0 )
			byteCount = 3;
		else if ((byteFirst & 0xC0) == 0xC0 )
			byteCount = 2;
		else
		{
			inFile.close();
			return false;
		}

		while (--byteCount > 0)
		{
			inFile.read(&byteTmp, sizeof(char));
			if ((byteTmp & 0x80) != 0x80)
			{
				inFile.close();
				return false;
			}
		}
	}

	inFile.close();
	cout<<"UTF-8 无BOM编码"<<endl;
	return true;
}
bool CheckLabelMatch()
{
	return true;
}
bool CompileXml()
{
	//check xml file encoding type, must be UTF-8 without BOM
	//check label match
	return false;
}

//a label name end with 0x20(space)、LF、CR、HT、'/>'、or '>'
//read a whole label(until '>'), if match '/>',then close the label;
//handle the label ID and the label attributes

#define  LABEL_ID_ENDLESS(tmpChar) (SP != tmpChar && CR != tmpChar && HT != tmpChar && LF != tmpChar && '/' != tmpChar)
#define  IS_LETTER(tmpChar) (tmpChar >= 'A' && tmpChar <= 'z')
#define  IS_SPACE_LETTER(tmpChar) (CR == tmpChar || LF == tmpChar)

XMLERROR XMLFile::ReadLabelAttrValue(std::ifstream& inFile, string* attrValueOut, XMLabel* labelObj)
{
	char tmp;
	string attrValue;

	bool bAttrValueComplete = false;
	bool bAttrValueBegin    = false;
	bool bAttrValueEnd      = false;

	XMLabel* tmpXmlObj = new XMLabel();
	while (!inFile.eof())
	{
		inFile.read(&tmp, sizeof(char));
		if ('>' == tmp || '/' == tmp)
		{   //attrValue must end by '\"'
			return XML_ERROR_UNEXPECTTAIL;

		}else if (!bAttrValueComplete)
		{
			if (0 == attrValue.length() && (!LABEL_ID_ENDLESS(tmp) || '=' == tmp))
			{
				continue;
			}else if ('\"' == tmp && !bAttrValueBegin)
			{
				bAttrValueBegin = true;
				continue;
			}
			else if (bAttrValueBegin && !bAttrValueComplete && LABEL_ID_ENDLESS(tmp))
			{
				if (('\"' != tmp))
					attrValue.append(sizeof(char), tmp);
				else
				{
					bAttrValueComplete = true;
					bAttrValueEnd = true;
					break;
				}
			}
		}

		if (bAttrValueComplete)
			if (!bAttrValueBegin || !bAttrValueEnd)
				return XML_ERROR_QUOTES_NOT_MATCH;
	}

	if (!bAttrValueComplete)
		return XML_ERROR_LABELVALUE;

	*attrValueOut = attrValue;
	return XML_SUCCESS;
}
XMLERROR XMLFile::ReadLabelAttrName(std::ifstream& inFile, string* attrNameOut, XMLabel* labelObj)
{
	char tmp;
	string attrName;
	bool bAttrNameComplete  = false;

	while (!inFile.eof())
	{
		inFile.read(&tmp, sizeof(char));
		if ('>' == tmp)
		{
			labelObj->SetLabelHeadClose(true);
			if (attrName.length() > 0)
				return XML_ERROR_UNEXPECTTAIL;
			else
				return XML_SUCCESS;

		}else if ('/' == tmp)
		{
			inFile.read(&tmp, sizeof(char));
			if ('>' != tmp)
				return XML_ERROR_UNEXPECTTAIL;

			labelObj->SetLabelHeadClose(true);
			labelObj->SetLabelClose(true);
			if (attrName.length() > 0)
				return XML_ERROR_UNEXPECTTAIL;
			else
				return XML_SUCCESS;
		}else if (!bAttrNameComplete)
		{
			if (0 == attrName.length() && !LABEL_ID_ENDLESS(tmp))
				continue;
			else if (LABEL_ID_ENDLESS(tmp) && ('=' != tmp))
				attrName.append(sizeof(char), tmp);
			else
			{
				bAttrNameComplete = true;
				break;
			}
		}
	}
	if (!bAttrNameComplete )
		return XML_ERROR_UNEXPECTEND;

	*attrNameOut = attrName;
	return XML_SUCCESS;
}
XMLERROR XMLFile::ReadLabelAttr(std::ifstream& inFile, XMLabel* labelObj)
{
	string attrName;
	string attrValue;
	XMLERROR readAttrNameRet;
	XMLERROR readAttrValueRet;
	map<string, string> attrMap;
	bool bHeadClose= false;
	while(!inFile.eof())
	{
		attrName = "";
		attrValue = "";
		readAttrNameRet = ReadLabelAttrName(inFile, &attrName, labelObj);
		if (readAttrNameRet != XML_SUCCESS)
			return readAttrNameRet;

		bHeadClose = labelObj->GetLabelHeadClose();
		if (bHeadClose)
		{
			if (0 == attrName.length())
			{
				labelObj->AddAttribute(&attrMap);
				return XML_SUCCESS;
			}
			else
				return XML_ERROR_UNKNOWN;
		}

		readAttrValueRet = ReadLabelAttrValue(inFile, &attrValue, labelObj);
		if (readAttrValueRet != XML_SUCCESS)
			return readAttrValueRet;

		bHeadClose = labelObj->GetLabelHeadClose();
		if (bHeadClose)
		{
			if (0 == attrValue.length())
			{
				labelObj->AddAttribute(&attrMap);
				return XML_SUCCESS;
			}
			else
				return XML_ERROR_UNKNOWN;
		}

		if (attrName.length() > 0 && attrValue.length() > 0)
			attrMap.insert(pair<string, string>(attrName, attrValue));
	}

	return XML_SUCCESS;
}
XMLERROR XMLFile::ReadLabelName(std::ifstream& inFile, string* labelNameOut, XMLabel* labelObj)
{
	string labelName;//label class name
	bool bLabelHeadClose = false;
	bool bLabelClose     = false;
	char tmp = 0;

	bool bHeadClose = labelObj->GetLabelHeadClose();
	if (bHeadClose)
		return XML_ERROR_UNKNOWN;

	while (!inFile.eof())
	{
		inFile.read(&tmp, sizeof(char));
		if ('>' == tmp )
		{
			bLabelHeadClose = true;
			break;
		}else if ('/' == tmp)
		{
			inFile.read(&tmp, sizeof(char));
			if ('>' == tmp)
			{
				bLabelHeadClose = true;
				bLabelClose = true;
				break;
			}else
				return XML_ERROR_LABELTAIL;

		}else if (!bLabelHeadClose )
		{
			if (LABEL_ID_ENDLESS(tmp))
				labelNameOut->append(sizeof(char), tmp);
			else
				break;
		}
	}
	//*labelNameOut = labelName;
	labelObj->SetLabelHeadClose(bLabelHeadClose);
	labelObj->SetLabelClose(bLabelClose);

	return XML_SUCCESS;
}
XMLERROR XMLFile::ReadLableTail(std::ifstream& inFile, string* tailName)
{
	string labelTailName;//label class name
	bool bLabelTailClose = false;
	char tmp = 0;

	while (!inFile.eof())
	{
		inFile.read(&tmp, sizeof(char));
		if ('>' == tmp )
		{
			bLabelTailClose = true;
			break;
		}else
		{
			if (IS_LETTER(tmp))
				tailName->append(sizeof(char), tmp);
		}
	}

	if (!bLabelTailClose)
		return XML_ERROR_LABELTAIL;

	return XML_SUCCESS;
}
XMLERROR XMLFile::ReadComment(std::ifstream& inFile)
{
	char commentHeadA;
	char commentHeadB;
	inFile.read(&commentHeadA, sizeof(char));
	inFile.read(&commentHeadB, sizeof(char));

	string comment;
	if (commentHeadA != '-' || commentHeadB != '-')
		return XML_ERROR_COMMENTHEAD;
	char commentChar;
	while (!inFile.eof())
	{
		inFile.read(&commentChar, sizeof(char));

		if ('-' == commentChar)
		{
			char commentTailA;
			char commentTailB;
			inFile.read(&commentTailA, sizeof(char));
			inFile.read(&commentTailB, sizeof(char));

			if ('-' == commentTailA && '>' == commentTailB)
			{
				int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, comment.c_str(), -1, NULL, 0);
				LPWSTR wComment = new WCHAR[unicodeLen + 1];
				MultiByteToWideChar(CP_UTF8, 0, comment.c_str(), -1, wComment, unicodeLen);

				return XML_SUCCESS;
			}
			else
			{
				inFile.seekg(-2, ios::cur);
				comment.append(sizeof(char), commentChar);
			}
		}else if ('>' == commentChar)
			return XML_ERROR_COMMENTTAIL;
		else
			comment.append(sizeof(char), commentChar);
	}
	return XML_ERROR_UNKNOWN;
}
XMLERROR XMLFile::ReadLableHead(std::ifstream& inFile, XMLabel** ppLableObj)
{
	string ret="";
	char tmp;
	unsigned int count=0;
	string labelName;//label class name
	string attrName;
	string attrValue;
	bool bLabelNameComplete = false;
	bool bLabelClose        = false;
	bool bAttrNameComplete  = false;
	bool bAttrValueComplete = false;
	bool bAttrValueBegin    = false;
	bool bAttrValueEnd      = false;
	bool bComplete = false;

	XMLabel* tmpXmlObj = new XMLabel();
	while (!inFile.eof())
	{
		count++;
		inFile.read(&tmp, sizeof(char));
		if ('>' == tmp )
		{
			bLabelNameComplete = true;
			break;
		}else if ('/' == tmp)
		{
			inFile.read(&tmp, sizeof(char));
			if ('>' == tmp)
			{
				bLabelNameComplete = true;
				bLabelClose = true;
				break;
			}else
			{
				delete tmpXmlObj;
				return XML_ERROR_LABELTAIL;
			}
		}else if (!bLabelNameComplete )
		{
			if (LABEL_ID_ENDLESS(tmp))
				labelName.append(sizeof(char), tmp);
			else
			{
				bLabelNameComplete = true;
				tmpXmlObj->SetLabelClassName(labelName);
			}
		}else if (!bAttrNameComplete)
		{
			if (0 == attrName.length() && !LABEL_ID_ENDLESS(tmp))
				continue;
			else if (LABEL_ID_ENDLESS(tmp) && ('=' != tmp))
				attrName.append(sizeof(char), tmp);
			else
			{
				bAttrNameComplete = true;
			}
		}else if (!bAttrValueComplete)
		{
			if (0 == attrValue.length() && (!LABEL_ID_ENDLESS(tmp) || '=' == tmp))
			{
				continue;
			}else if ('\"' == tmp && !bAttrValueBegin)
			{
				bAttrValueBegin = true;
				continue;
			}
			else if (bAttrValueBegin && !bAttrValueComplete && LABEL_ID_ENDLESS(tmp))
			{
				if (('\"' != tmp))
					attrValue.append(sizeof(char), tmp);
				else
				{
					bAttrValueComplete = true;
					bAttrValueEnd = true;
				}
			}
		}

		if (bAttrValueComplete)
			if (!bAttrValueBegin || !bAttrValueEnd)
				return XML_ERROR_QUOTES_NOT_MATCH;

		if (bAttrNameComplete && bAttrValueComplete)
		{
			tmpXmlObj->SetAttribute(attrName, attrValue);
			bAttrNameComplete  = false;
			bAttrValueComplete = false;
			bAttrValueBegin    = false;
			bAttrValueEnd      = false;
			attrName  = "";
			attrValue = "";
		}
	}

	if (!bLabelNameComplete || bAttrNameComplete || bAttrValueComplete)
	{
		delete tmpXmlObj;
		return XML_ERROR_LABELTAIL;
	}

	tmpXmlObj->SetLabelClose(bLabelClose);
	tmpXmlObj->SetLabelClassName(labelName);
	*ppLableObj = tmpXmlObj;
	return XML_SUCCESS;
}

XMLERROR XMLFile::ReadLableHead(std::ifstream& inFile, XMLabel* labelObj)
{
	string labelName;
	XMLERROR ret = ReadLabelName(inFile, &labelName, labelObj);
	if (ret != XML_SUCCESS)
		return ret;

	labelObj->SetLabelClassName(labelName);
	bool bHeadClose = labelObj->GetLabelHeadClose();
	if (!bHeadClose)
	{
		ret = ReadLabelAttr(inFile, labelObj);
		if (ret != XML_SUCCESS)
			return ret;
	}

	return XML_SUCCESS;

}
XMLERROR XMLFile::ReadLableValue(std::ifstream& inFile, XMLabel* labelObj)
{
	char tmpChar=0;
	string labelValue;
	while (!inFile.eof())
	{
		inFile.read(&tmpChar, sizeof(tmpChar));
		if ('<' == tmpChar)
		{
			inFile.seekg(-1, ios::cur);
			labelObj->SetLabelValue(labelValue);
			return XML_SUCCESS;

		}else if (CR != tmpChar && LF != tmpChar)
		{
			labelValue.append(sizeof(char), tmpChar);
		}
	}
	return XML_ERROR_UNKNOWN;
}

XMLERROR XMLFile::ParseXml(LPCWSTR pszFilePath, XMLabel** rootLabelObj)
{
	//must be ios::binary, because seekg(off, way) do not support text file
	std::ifstream inXmlFile(pszFilePath, ios::binary);
	//Assert(inXmlFile);

	std::stack<XMLabel*> lableObjStack;
	inXmlFile.seekg(0);

	//create a tmp XMLabel and push in lableObjStack, and fill in the obj's attr
	//pop out when match a finish label;
	//and then push the finished obj in XMLFile obj's m_xmlObjVec

	XMLabel* newObj = NULL;
	char tmpChar=0;
	while (!inXmlFile.eof())
	{
		XMLERROR ret = XML_SUCCESS;
		inXmlFile.read(&tmpChar, sizeof(tmpChar));
		if ('<' == tmpChar)
		{
			inXmlFile.read(&tmpChar, sizeof(tmpChar));
			if (IS_LETTER(tmpChar))
			{
				newObj = new XMLabel();
				if (NULL == newObj)
					return XML_ERROR_MEMORY;

				inXmlFile.seekg(-1, ios::cur);
				ret = ReadLableHead(inXmlFile, newObj);

				if (XML_SUCCESS != ret )
					return ret;

				if (!newObj->GetLabelClose())
				{
					ret = ReadLableValue(inXmlFile, newObj);
					if (XML_SUCCESS != ret )
						return ret;

					lableObjStack.push(newObj);
				}else if (!lableObjStack.empty())
				{
					XMLabel* topObj = lableObjStack.top();
					newObj->SetParent(topObj);
					topObj->AddChild(newObj);
				}
			}else if ('!' == tmpChar)
			{
				XMLERROR ret = ReadComment(inXmlFile);
				if (XML_SUCCESS != ret )
					return ret;
			}else if ('/' == tmpChar)
			{
				string labelTailName;
				ret = ReadLableTail(inXmlFile, &labelTailName);
				if (XML_SUCCESS != ret )
					return ret;

				//pop the labelObject in stack, check the labelObject's id with labelTailName
				//then set the labelObject to its parent
				if (lableObjStack.empty())
					return XML_ERROR_UNKNOWN;

				XMLabel* topObj = lableObjStack.top();
				if (NULL == topObj )
					return XML_ERROR_UNKNOWN;

				if (topObj->GetLabelClassName() != labelTailName)
					return XML_MISMATCH;

				topObj->SetLabelClose(true);
				lableObjStack.pop();

				if (!lableObjStack.empty())
				{
					XMLabel* parentObj =  lableObjStack.top();

					topObj->SetParent(parentObj);
					parentObj->AddChild(topObj);
				}else
				{
					*rootLabelObj = topObj;
				}

			}

		}

	}
	return XML_SUCCESS;
}

XMLERROR XMLFile::LoadXmlFile(LPCWSTR pszFilePath)
{
	BOOL ret = ::PathFileExists(pszFilePath);
	if (!ret)
		return XML_WRONG_FILENOTEXISTS;

	if (!XMLFile::CheckFileEncoding(pszFilePath))
		return XML_WRONG_ENCODING_TYPE;

	m_wszXmlFileName = PathFindFileNameW(pszFilePath);
	return ParseXml(pszFilePath, &m_pRootLabel);
}

XMLabel* XMLFile::GetRootObj()
{
	return m_pRootLabel;
}

repository: Johnny-Martin/Gear

repo_name: Johnny-Martin/Gear

extension: cpp


text:
package datastore

import (
    "sync"
    "time"
	"../config"
)
/********************************************************
DataStore API
Make(data string)
 - intializes a datastore storing the inut data
Size()
 - returns the size (number of files) in the datastore
Get(file string)
 - returns the datastore in the file for the corresponding key
********************************************************/

type DataStore struct {
    mu      sync.Mutex
    data    map[string]config.DataType
    n       int
    calls   int64
}

func (d *DataStore) CountCalls() int64 {
    d.mu.Lock()
    defer d.mu.Unlock()
    return d.calls
}

func (d *DataStore) GetFileNames() []string {
    d.mu.Lock()
    defer d.mu.Unlock()
    filenames := make([]string, len(d.data))
    i := 0
    for f, _ := range d.data {
        filenames[i] = f
        i++
    }
    return filenames
}

func MakeDataStore() *DataStore {
    d := &DataStore{}
    d.data = make(map[string]config.DataType)
    d.n = 0
    d.calls = 0
    return d
}

func (d *DataStore) Size() int {
    d.mu.Lock()
    defer d.mu.Unlock()
    return d.n
}

func (d *DataStore) Get(filename string) (config.DataType, bool) {
    time.Sleep(config.DATA_FETCH_TIME)
    d.mu.Lock()
    defer d.mu.Unlock()
    data, ok := d.data[filename]
    d.calls++
    // approx time of fetching from underlying datastore
    return data, ok
}

func (d *DataStore) GetBatch(filenames []string) ([]config.DataType, bool) {
    time.Sleep(config.DATA_FETCH_TIME + config.DATA_COST_TIME * time.Duration(len(filenames)))
    d.mu.Lock()
	defer d.mu.Unlock()
	files := make([]config.DataType, len(filenames))
	valid := true
	for i, name := range filenames {
		file, ok := d.data[name]
		valid = valid && ok
		files[i] = file
	}
    d.calls++
    // approx time of fetching from underlying datastore
    return files, valid
}

func (d *DataStore) Make(filename string, content config.DataType) {
    d.mu.Lock()
    defer d.mu.Unlock()

    // TODO: uncomment if DataType is *os.File
    // f, _ := os.Create(filename) // ignore error if already exists
	// f.Close()
    // d.data[filename], _ = os.Open(filename)

    // TODO: comment out if DataType is *os.File
    d.data[filename] = content
    d.n = len(d.data)
}

func (d *DataStore) Copy() *DataStore {
    d.mu.Lock()
    defer d.mu.Unlock()
    c := &DataStore{}
    c.data = make(map[string]config.DataType)
    for filename, content := range d.data {
        c.data[filename] = content
    }
    c.n = len(c.data)
    c.calls = 0
    return c
}

repository: smart-cache/smart-cache-go

repo_name: smart-cache/smart-cache-go


text:
package models

import (
    i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
    ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e "github.com/microsoft/kiota-abstractions-go/store"
)

// CertificateAuthority
type CertificateAuthority struct {
    // Stores model information.
    backingStore ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore
}
// NewCertificateAuthority instantiates a new certificateAuthority and sets the default values.
func NewCertificateAuthority()(*CertificateAuthority) {
    m := &CertificateAuthority{
    }
    m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();
    m.SetAdditionalData(make(map[string]any))
    return m
}
// CreateCertificateAuthorityFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateCertificateAuthorityFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
    return NewCertificateAuthority(), nil
}
// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *CertificateAuthority) GetAdditionalData()(map[string]any) {
    val , err :=  m.backingStore.Get("additionalData")
    if err != nil {
        panic(err)
    }
    if val == nil {
        var value = make(map[string]any);
        m.SetAdditionalData(value);
    }
    return val.(map[string]any)
}
// GetBackingStore gets the backingStore property value. Stores model information.
func (m *CertificateAuthority) GetBackingStore()(ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore) {
    return m.backingStore
}
// GetCertificate gets the certificate property value. Required. The base64 encoded string representing the public certificate.
func (m *CertificateAuthority) GetCertificate()([]byte) {
    val, err := m.GetBackingStore().Get("certificate")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.([]byte)
    }
    return nil
}
// GetCertificateRevocationListUrl gets the certificateRevocationListUrl property value. The URL of the certificate revocation list.
func (m *CertificateAuthority) GetCertificateRevocationListUrl()(*string) {
    val, err := m.GetBackingStore().Get("certificateRevocationListUrl")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.(*string)
    }
    return nil
}
// GetDeltaCertificateRevocationListUrl gets the deltaCertificateRevocationListUrl property value. The URL contains the list of all revoked certificates since the last time a full certificate revocaton list was created.
func (m *CertificateAuthority) GetDeltaCertificateRevocationListUrl()(*string) {
    val, err := m.GetBackingStore().Get("deltaCertificateRevocationListUrl")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.(*string)
    }
    return nil
}
// GetFieldDeserializers the deserialization information for the current model
func (m *CertificateAuthority) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
    res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))
    res["certificate"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetByteArrayValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetCertificate(val)
        }
        return nil
    }
    res["certificateRevocationListUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetStringValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetCertificateRevocationListUrl(val)
        }
        return nil
    }
    res["deltaCertificateRevocationListUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetStringValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetDeltaCertificateRevocationListUrl(val)
        }
        return nil
    }
    res["isRootAuthority"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetBoolValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetIsRootAuthority(val)
        }
        return nil
    }
    res["issuer"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetStringValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetIssuer(val)
        }
        return nil
    }
    res["issuerSki"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetStringValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetIssuerSki(val)
        }
        return nil
    }
    res["@odata.type"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
        val, err := n.GetStringValue()
        if err != nil {
            return err
        }
        if val != nil {
            m.SetOdataType(val)
        }
        return nil
    }
    return res
}
// GetIsRootAuthority gets the isRootAuthority property value. Required. true if the trusted certificate is a root authority, false if the trusted certificate is an intermediate authority.
func (m *CertificateAuthority) GetIsRootAuthority()(*bool) {
    val, err := m.GetBackingStore().Get("isRootAuthority")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.(*bool)
    }
    return nil
}
// GetIssuer gets the issuer property value. The issuer of the certificate, calculated from the certificate value. Read-only.
func (m *CertificateAuthority) GetIssuer()(*string) {
    val, err := m.GetBackingStore().Get("issuer")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.(*string)
    }
    return nil
}
// GetIssuerSki gets the issuerSki property value. The subject key identifier of the certificate, calculated from the certificate value. Read-only.
func (m *CertificateAuthority) GetIssuerSki()(*string) {
    val, err := m.GetBackingStore().Get("issuerSki")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.(*string)
    }
    return nil
}
// GetOdataType gets the @odata.type property value. The OdataType property
func (m *CertificateAuthority) GetOdataType()(*string) {
    val, err := m.GetBackingStore().Get("odataType")
    if err != nil {
        panic(err)
    }
    if val != nil {
        return val.(*string)
    }
    return nil
}
// Serialize serializes information the current object
func (m *CertificateAuthority) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
    {
        err := writer.WriteByteArrayValue("certificate", m.GetCertificate())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteStringValue("certificateRevocationListUrl", m.GetCertificateRevocationListUrl())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteStringValue("deltaCertificateRevocationListUrl", m.GetDeltaCertificateRevocationListUrl())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteBoolValue("isRootAuthority", m.GetIsRootAuthority())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteStringValue("issuer", m.GetIssuer())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteStringValue("issuerSki", m.GetIssuerSki())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteStringValue("@odata.type", m.GetOdataType())
        if err != nil {
            return err
        }
    }
    {
        err := writer.WriteAdditionalData(m.GetAdditionalData())
        if err != nil {
            return err
        }
    }
    return nil
}
// SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *CertificateAuthority) SetAdditionalData(value map[string]any)() {
    err := m.GetBackingStore().Set("additionalData", value)
    if err != nil {
        panic(err)
    }
}
// SetBackingStore sets the backingStore property value. Stores model information.
func (m *CertificateAuthority) SetBackingStore(value ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore)() {
    m.backingStore = value
}
// SetCertificate sets the certificate property value. Required. The base64 encoded string representing the public certificate.
func (m *CertificateAuthority) SetCertificate(value []byte)() {
    err := m.GetBackingStore().Set("certificate", value)
    if err != nil {
        panic(err)
    }
}
// SetCertificateRevocationListUrl sets the certificateRevocationListUrl property value. The URL of the certificate revocation list.
func (m *CertificateAuthority) SetCertificateRevocationListUrl(value *string)() {
    err := m.GetBackingStore().Set("certificateRevocationListUrl", value)
    if err != nil {
        panic(err)
    }
}
// SetDeltaCertificateRevocationListUrl sets the deltaCertificateRevocationListUrl property value. The URL contains the list of all revoked certificates since the last time a full certificate revocaton list was created.
func (m *CertificateAuthority) SetDeltaCertificateRevocationListUrl(value *string)() {
    err := m.GetBackingStore().Set("deltaCertificateRevocationListUrl", value)
    if err != nil {
        panic(err)
    }
}
// SetIsRootAuthority sets the isRootAuthority property value. Required. true if the trusted certificate is a root authority, false if the trusted certificate is an intermediate authority.
func (m *CertificateAuthority) SetIsRootAuthority(value *bool)() {
    err := m.GetBackingStore().Set("isRootAuthority", value)
    if err != nil {
        panic(err)
    }
}
// SetIssuer sets the issuer property value. The issuer of the certificate, calculated from the certificate value. Read-only.
func (m *CertificateAuthority) SetIssuer(value *string)() {
    err := m.GetBackingStore().Set("issuer", value)
    if err != nil {
        panic(err)
    }
}
// SetIssuerSki sets the issuerSki property value. The subject key identifier of the certificate, calculated from the certificate value. Read-only.
func (m *CertificateAuthority) SetIssuerSki(value *string)() {
    err := m.GetBackingStore().Set("issuerSki", value)
    if err != nil {
        panic(err)
    }
}
// SetOdataType sets the @odata.type property value. The OdataType property
func (m *CertificateAuthority) SetOdataType(value *string)() {
    err := m.GetBackingStore().Set("odataType", value)
    if err != nil {
        panic(err)
    }
}
// CertificateAuthorityable
type CertificateAuthorityable interface {
    i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.AdditionalDataHolder
    ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackedModel
    i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable
    GetBackingStore()(ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore)
    GetCertificate()([]byte)
    GetCertificateRevocationListUrl()(*string)
    GetDeltaCertificateRevocationListUrl()(*string)
    GetIsRootAuthority()(*bool)
    GetIssuer()(*string)
    GetIssuerSki()(*string)
    GetOdataType()(*string)
    SetBackingStore(value ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStore)()
    SetCertificate(value []byte)()
    SetCertificateRevocationListUrl(value *string)()
    SetDeltaCertificateRevocationListUrl(value *string)()
    SetIsRootAuthority(value *bool)()
    SetIssuer(value *string)()
    SetIssuerSki(value *string)()
    SetOdataType(value *string)()
}

repository: microsoftgraph/msgraph-sdk-go

repo_name: microsoftgraph/msgraph-sdk-go

branch_name: refs/heads/main


text:
# base recipe: meta/recipes-graphics/xorg-xserver/xserver-xorg_1.20.4.bb
# base branch: warrior
# base commit: 62c9d641092dbbb1ccd6439ac415b195e39f89bd

require ${COREBASE}/meta/recipes-graphics/xorg-xserver/xserver-xorg.inc

# clear SRC_URI
SRC_URI = ""
S = ""
PE = ""
INC_PR = ""

inherit debian-package
require recipes-debian/sources/xorg-server.inc
BPN = "xorg-server"
DEBIAN_PATCH_TYPE = "quilt"
DEBIAN_UNPACK_DIR = "${WORKDIR}/${XORG_PN}-${PV}"
FILESPATH_append = ":${COREBASE}/meta/recipes-graphics/xorg-xserver/xserver-xorg"

SRC_URI += "file://musl-arm-inb-outb.patch \
            file://pkgconfig.patch \
            file://0001-test-xtest-Initialize-array-with-braces.patch \
            "

# Same as debian/patches/06_use-intel-only-on-pre-gen4.diff
# file://0001-xf86pciBus.c-use-Intel-ddx-only-for-pre-gen4-hardwar.patch

# These extensions are now integrated into the server, so declare the migration
# path for in-place upgrades.

RREPLACES_${PN} =  "${PN}-extension-dri \
                    ${PN}-extension-dri2 \
                    ${PN}-extension-record \
                    ${PN}-extension-extmod \
                    ${PN}-extension-dbe \
                   "
RPROVIDES_${PN} =  "${PN}-extension-dri \
                    ${PN}-extension-dri2 \
                    ${PN}-extension-record \
                    ${PN}-extension-extmod \
                    ${PN}-extension-dbe \
                   "
RCONFLICTS_${PN} = "${PN}-extension-dri \
                    ${PN}-extension-dri2 \
                    ${PN}-extension-record \
                    ${PN}-extension-extmod \
                    ${PN}-extension-dbe \
                   "

repository: miraclelinux/meta-debian-extended

repo_name: miraclelinux/meta-debian-extended

branch_name: refs/heads/warrior

gha_language: BitBake


text:
@article{Gorbunova:2007is,
 author = {Gorbunova, Vera and Seluanov, Andrei and Mao, Zhiyong and Hine, Christpher},
 date-added = {2019-05-20T01:27:45GMT},
 date-modified = {2019-05-20T01:46:13GMT},
 doi = {10.1093/nar/gkm756},
 journal = {Nucleic Acids Research},
 language = {English},
 month = {December},
 number = {22},
 pages = {7466--7474},
 rating = {0},
 title = {Changes in DNA repair during aging},
 uri = {r̆lpapers3://publication/doi/10.1093/nar/gkm756},
 url = {https://academic.oup.com/nar/article-lookup/doi/10.1093/nar/gkm756},
 volume = {35},
 year = {2007}
}


text:
package cmc

import (
	"github.com/douyu/jupiter/pkg/store/gorm"
)

var (
	Cmc *cmc
)

type cmc struct {
	*gorm.DB
}

func InitCmc(db *gorm.DB) {
	Cmc = &cmc{
		db,
	}
	return
}

repository: link-duan/juno

repo_name: link-duan/juno


text:
require gst-rtsp.inc
SRC_URI[md5sum] = "b511af07000595f63c3a705946221643"
SRC_URI[sha256sum] = "9915887cf8515bda87462c69738646afb715b597613edc7340477ccab63a6617"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"time"
)

func demoText() {
	var cd ChineseDict
	cd.Init()
	ReadDict("/Users/anyu/goproj/Xindict/dictdemo.txt", &cd)

	for _, cw := range cd.chs2Word {
		fmt.Println(cw.toDesc())
	}
}

func readDictFile() {
	var cd ChineseDict
	cd.Init()
	ReadDict("/Users/anyu/goproj/Xindict/cedict.u8", &cd)

	singlecount := 0
	for _, cw := range cd.chs2Word {

		if cw.IsSingle2() {
			//fmt.Println(cw.toDesc())
			singlecount++
		}
	}

	fmt.Printf("Hanzi Count: %d\n", singlecount)
}

// VerboseMode
const (
	Brief    = 2
	Verbose  = 3
	VerbMore = 4
	Unknown  = 1
)

func findQscByChars() {
	if len(os.Args) <= 1 {
		fmt.Printf("Usage: %s --find \"keyword\" --length [d] "+
			" -p [d] [--v] [--vv]\n", os.Args[0])
		fmt.Println("-p: pattern (1: Prefix, 2: Suffix, 3: Any, Other: invalid)")
		return
	}

	//fmt.Printf("[DBG]Args: %d\n", len(os.Args))

	var tofind string
	var length int
	var verbose bool
	var verbmore bool
	var pattern int

	flag.StringVar(&tofind, "find", "", "keyword to find")
	flag.IntVar(&length, "length", 0, "Sentence length")
	flag.BoolVar(&verbose, "v", false, "verbose mode")
	flag.BoolVar(&verbmore, "vv", false, "more verbose mode")
	flag.IntVar(&pattern, "p", POS_ANY, "match pattern (1: Prefix, 2: Suffix, 3: Any, Other: invalid)")

	flag.Parse()

	log.Printf("[INFO]%s\n", getCommandLine())

	starttime := time.Now()

	verbmode := Brief
	if verbose {
		if verbmore {
			log.Printf("WARN: Invalid parameters: %v and %v.\n", verbose, verbmore)
			return
		} else {
			verbmode = Verbose
		}
	} else if verbmore {
		verbmode = VerbMore
	}

	findQscKeyword(tofind, pattern, length, verbmode)
	//FindKeysInDbs(tofind, ignores, inBook, verbmode, pattern)

	elapsed := time.Since(starttime)
	log.Printf("Looking up took %s.\n", elapsed)
}

func findRelatedKeyword() {
	if len(os.Args) == 0 {
		fmt.Printf("Usage: %s --find \"keyword\" [--v] [--vv]\n", os.Args[0])
		return
	}

	var tofind string
	var verbose bool
	var verbmore bool

	flag.StringVar(&tofind, "find", "", "keyword to find")
	flag.BoolVar(&verbose, "v", false, "verbose mode")
	flag.BoolVar(&verbmore, "vv", false, "more verbose mode")

	flag.Parse()

	log.Printf("[INFO]%s\n", getCommandLine())
	log.Printf("[INFO]Keyword: %s.\n", tofind)

	starttime := time.Now()

	verbmode := Brief
	if verbose {
		if verbmore {
			log.Printf("WARN: Invalid parameters: %v and %v.\n", verbose, verbmore)
			return
		} else {
			verbmode = Verbose
		}
	} else if verbmore {
		verbmode = VerbMore
	}

	findRelated(tofind, verbmode)
	elapsed := time.Since(starttime)
	log.Printf("Looking up took %s.\n", elapsed)
}

func getCommandLine() string {
	s := ""
	for _, v := range os.Args {
		s += v + " "
	}
	return s
}

func main() {
	//findKeywords(`端午 客`)

	findRepeatChChars()

	//findRelated(`黄叶`)
	//findRelatedKeyword()

	//readQts()
	//loadPoetryFile(`./quantangshi/005.json`)
	//loadFileDemo(`./quantangshi/005.json`)
	//LoadPoetries(`./quantangshi/`)
	//printHans(`allhans.txt`)

	//analyseQsc()
	//findQscByChars()

	//cipaiDemo()

	//ExportPoetry(`D:\tmp\poem\chinese-poetry-master\ci`, `D:\tmp\poem\exportdemo`)

	//ExportQsc(`D:\Projects\GitHubSync\XinShiCi\qsc.txt`, `D:\tmp\xsc`)

	//GenerateWordCloud(`D:\Projects\XinShiCi\qsc.txt`)

	//qscRank()

	//var qc QscZht
	//qc.convertFile(`D:\Err2.txt`)
	//qc.convertFile(`D:\Projects\GitHubSync\XinShiCi\qsc_zht.txt`)

	//var qc QscZhtLoader
	//qc.convertFile(`D:\Projects\GitHubSync\XinShiCi\qsc_zht_fmt.txt`)
}

repository: rainrambler/XinShiCi

repo_name: rainrambler/XinShiCi


text:
// Copyright (c) Csaba Molnar & Daniel Butum. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"

#include "UI/General/SoUITypes.h"

#include "SoUIChallenges.generated.h"

class USoUIButtonArray;
class USoUIButton;
class USoUICommandTooltipArray;
class USoUIConfirmPanel;
class UImage;
class UTextBlock;
class UFMODEvent;

/**
 * Shows the save slots of the game
 */
UCLASS()
class SORB_API USoUIChallenges : public UUserWidget, public ISoUIEventHandler
{
	GENERATED_BODY()

public:
	//
	// UUserWidget Interface
	//
	void SynchronizeProperties() override;
	void NativeConstruct() override;
	void NativeDestruct() override;

	//
	// ISoUIEventHandler Interface
	//
	bool OnUICommand_Implementation(ESoUICommand Command) override;
	void Open_Implementation(bool bOpen) override;
	bool IsOpened_Implementation() const override { return bOpened; }
	bool CanBeInterrupted_Implementation() const override { return true; }

	//
	// Own methods
	//

	// No animation
	void InstantOpen(bool bOpen);

	UFUNCTION(BlueprintNativeEvent)
	void OnEpisodeChanged(int32 EpisodeButtonIndex);

	// Refreshes the command tooltips depending on the currently selected index.
	UFUNCTION(BlueprintCallable)
	void RefreshCommandTooltips();

	// Start the new challenge
	void StartEpisode(FName EpisodeName);

protected:
	void CreateDefaultChallenges();
	void CreateChallengesFromWorldStateChallenges();

	FName GetSelectedEpisodeName() const;

protected:
	UPROPERTY(BlueprintReadWrite, Category = ">Widgets", meta = (BindWidget))
	USoUIButtonArray* ChallengeButtons = nullptr;

	// Show the actions (shortcuts) possible on each challenge
	UPROPERTY(BlueprintReadWrite, Category = ">Widgets", meta = (BindWidget))
	USoUICommandTooltipArray* CommandTooltips = nullptr;

	UPROPERTY(BlueprintReadWrite, Category = ">Widgets", meta = (BindWidget))
	UImage* ChallengeImage;

	UPROPERTY(BlueprintReadWrite, Category = ">Widgets", meta = (BindWidget))
	UTextBlock* DescriptionValue;

	// UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
	// UPanelWidget* CheckpointContainer;

	// UPROPERTY(BlueprintReadWrite, meta = (BindWidget))
	// UTextBlock* CheckpointValue;

	UPROPERTY(BlueprintReadWrite, Category = ">Widgets", meta = (BindWidget))
	UTextBlock* StatusValue;

	// Number of challenge buttons
	UPROPERTY(BlueprintReadOnly, Category = ">Challenge")
	int32 NumEpisodes = 3;

	// Maps from
	// Key: The episode button index
	// Value: Episode Name
	TArray<FName> MapEpisodeButtonToEpisodeName;

	// Are the save slots still opened?
	bool bOpened = false;

	// Actions for the save  slots
	static constexpr ESoUICommand UICommand_StartEpisode = ESoUICommand::EUC_Action0;

	//
	// SFX
	//

	UPROPERTY(EditAnywhere, Category = ">SFX")
	UFMODEvent* SFXOpenSelected = nullptr;
};

repository: Jusedawg/WarriOrb

repo_name: Jusedawg/WarriOrb

extension: h


text:
package service

import (
    mgRct "mingle/reactor"
)

type proxyProc struct {
    proc mgRct.EventProcessor
    dt *mgRct.DepthTracker
}

func newProxyProc( proc mgRct.EventProcessor ) *proxyProc {
    return &proxyProc{ proc, mgRct.NewDepthTracker() }
}

func ( p *proxyProc ) isDone() bool { return p.dt.Depth() == 0 }

func ( p *proxyProc ) ProcessEvent( ev mgRct.Event ) error {
    if err := p.dt.ProcessEvent( ev ); err != nil { return err }
    return p.proc.ProcessEvent( ev )
}

repository: dladanyi/bitgirder-main

repo_name: dladanyi/bitgirder-main


text:
package websearch

//go:generate mockgen -destination=../../mocks/mock_iwebsearcher.go -package=mocks github.com/telegram-go-bot/go_bot/app/common/web_search Searcher

// Searcher - search for image url, or some text
type Searcher interface {
	MaxResponseItemsCount() int
	//SearchImage - search for a query string, returns list of image URLs max as searchDepth value
	SearchImage(query string, searchDepth int) []string
}


text:
package configuration

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"testing"

	"github.com/jinzhu/configor"
	"github.com/stretchr/testify/assert"
	"gopkg.in/yaml.v2"
)

type Pair struct {
	Is     interface{}
	Should interface{}
}

func TestMain(m *testing.M) {
	testMode = true
	m.Run()
	cleanUp()
	os.Exit(0)
}

func TestConfiguration_GetMinimal(t *testing.T) {
	err := writeMinimalConfig()
	if err != nil {
		fmt.Println("Could not write minimal config: ", err)
		os.Exit(1)
	}

	validateConfig(t)
}

func TestConfiguration_GetValid(t *testing.T) {
	assert := assert.New(t)

	err := writeValidConfig()
	if err != nil {
		fmt.Println("Could not write valid config: ", err)
		os.Exit(1)
	}

	validateConfig(t)

	config := Get()

	expectedValues := make(map[string]Pair)
	expectedValues["config.Admin.MatrixID"] = Pair{config.Admin.MatrixID, "000000"}
	expectedValues["config.Matrix.Username"] = Pair{config.Matrix.Username, "default-username"}
	expectedValues["config.Matrix.Password"] = Pair{config.Matrix.Password, "default-password"}

	for name, pair := range expectedValues {
		assert.Equalf(pair.Is, pair.Should, fmt.Sprintf("%s should be %v but is %v", name, pair.Should, pair.Is))
	}
}

func TestConfiguration_GetEmpty(t *testing.T) {
	err := writeEmptyConfig()
	if err != nil {
		fmt.Println("Could not write empty config: ", err)
		os.Exit(1)
	}

	assert.Panicsf(t, func() { Get() }, "Get() did not panic altough config is empty")
}

func TestConfiguration_GetInvalid(t *testing.T) {
	err := writeInvalidConfig()
	if err != nil {
		fmt.Println("Could not write empty config: ", err)
		os.Exit(1)
	}

	assert.Panicsf(t, func() { Get() }, "Get() did not panic altough config is empty")
}

func TestConfiguaration_ConfigFiles(t *testing.T) {
	files := configFiles()

	assert.Greater(t, len(files), 0)
	for _, file := range files {
		assert.Truef(t, strings.HasSuffix(file, ".yml"), "%s is no yaml file", file)
	}
}

// Checks if the values in the configuration are plausible
func validateConfig(t *testing.T) {
	assert := assert.New(t)
	assert.NotPanicsf(func() { Get() }, "Get configuration should not panic")

	config := Get()
	asGreater := make(map[string]Pair)
	asGreater["config.Crypto.Argon2.Memory"] = Pair{config.Crypto.Argon2.Memory, uint32(0)}
	asGreater["config.Crypto.Argon2.Iterations"] = Pair{config.Crypto.Argon2.Iterations, uint32(0)}
	asGreater["config.Crypto.Argon2.SaltLength"] = Pair{config.Crypto.Argon2.SaltLength, uint32(0)}
	asGreater["config.Crypto.Argon2.KeyLength"] = Pair{config.Crypto.Argon2.KeyLength, uint32(0)}
	asGreater["config.Crypto.Argon2.Parallelism"] = Pair{config.Crypto.Argon2.Parallelism, uint8(0)}
	asGreater["config.HTTP.Port"] = Pair{config.HTTP.Port, 0}
	for name, pair := range asGreater {
		assert.Greaterf(pair.Is, pair.Should, fmt.Sprintf("%s should be > %v but is %v", name, pair.Should, pair.Is))
	}

	asFalse := make(map[string]bool)
	asFalse["config.Formatting.ColoredTitle"] = config.Formatting.ColoredTitle
	asFalse["config.Debug"] = config.Debug
	asFalse["config.Security.CheckHIBP"] = config.Security.CheckHIBP
	for name, value := range asFalse {
		assert.Falsef(value, fmt.Sprintf("%s should be false but is %t", name, value))
	}
}

type MinimalConfiguration struct {
	Admin struct {
		MatrixID string
	}
	Matrix struct {
		Username string
		Password string
	}
}

type InvalidConfiguration struct {
	Debug int
	HTTP  struct {
		ListenAddress bool
	}
	Admin struct {
		Name int
	}
	Formatting string
}

// Writes a minimal config to config.yml
func writeMinimalConfig() error {
	cleanUp()
	config := MinimalConfiguration{}
	config.Admin.MatrixID = "000000"
	config.Matrix.Username = "default-username"
	config.Matrix.Password = "default-password"

	configString, err := yaml.Marshal(&config)
	if err != nil {
		return err
	}

	return ioutil.WriteFile("config_unittest.yml", configString, 0644)
}

// Writes a config with default values to config.yml
func writeValidConfig() error {
	cleanUp()

	// Load minimal config to get default values
	writeMinimalConfig()
	config := &Configuration{}
	err := configor.New(&configor.Config{
		Environment:          "production",
		ENVPrefix:            "PUSHBITS",
		ErrorOnUnmatchedKeys: true,
	}).Load(config, "config_unittest.yml")
	if err != nil {
		return err
	}

	config.Admin.MatrixID = "000000"
	config.Matrix.Username = "default-username"
	config.Matrix.Password = "default-password"

	configString, err := yaml.Marshal(&config)
	if err != nil {
		return err
	}

	return ioutil.WriteFile("config_unittest.yml", configString, 0644)
}

// Writes a config that is empty
func writeEmptyConfig() error {
	cleanUp()
	return ioutil.WriteFile("config_unittest.yml", []byte(""), 0644)
}

// Writes a config with invalid entries
func writeInvalidConfig() error {
	cleanUp()
	config := InvalidConfiguration{}
	config.Debug = 1337
	config.HTTP.ListenAddress = true
	config.Admin.Name = 23
	config.Formatting = "Nice"

	configString, err := yaml.Marshal(&config)
	if err != nil {
		return err
	}

	return ioutil.WriteFile("config_unittest.yml", configString, 0644)
}

func cleanUp() error {
	return os.Remove("config_unittest.yml")
}

license: ISC

repository: kamilr/server

repo_name: kamilr/server


text:
package gs

import (
	"context"
	"github.com/viant/afs/option"
	"github.com/viant/afs/storage"
	"path"
	"strings"
)

//Delete removes an resource
func (s *storager) Delete(ctx context.Context, location string, options ...storage.Option) (err error) {
	location = strings.Trim(location, "/")
	if location == "" {
		call := s.Buckets.Delete(s.bucket)
		call.Context(ctx)
		err = call.Do()
		return err
	}
	call := s.Objects.Delete(s.bucket, location)
	call.Context(ctx)
	s.setGeneration(func(generation int64) {
		call.IfGenerationMatch(generation)
	}, func(generation int64) {
		call.IfGenerationNotMatch(generation)
	}, options)

	call.Context(ctx)
	err = runWithRetries(ctx, func() error {
		return call.Do()
	}, s)

	if isNotFound(err) {
		objectKind := &option.ObjectKind{}
		if _, ok := option.Assign(options, &objectKind); ok && objectKind.File {
			return err
		}
		notFound := err
		infoList, err := s.List(ctx, location)
		if err != nil {
			return err
		}
		if len(infoList) > 1 {
			for i := 1; i < len(infoList); i++ {
				if err = s.Delete(ctx, path.Join(location, infoList[i].Name())); err != nil {
					return err
				}
			}
			return nil
		} else {
			return notFound
		}
	}
	return err
}

repository: viant/afsc

repo_name: viant/afsc


text:
package link_cqrs

import (
	"context"

	"github.com/shortlink-org/shortlink/internal/pkg/notify"
	link "github.com/shortlink-org/shortlink/internal/services/link/domain/link/v1"
	metadata "github.com/shortlink-org/shortlink/internal/services/metadata/domain/metadata/v1"
)

func (s *Service) EventHandlers() {
	// Subscribe to Event
	// Link
	notify.Subscribe(link.METHOD_ADD, s)
	notify.Subscribe(link.METHOD_UPDATE, s)
	notify.Subscribe(link.METHOD_DELETE, s)

	// Metadata
	notify.Subscribe(metadata.METHOD_ADD, s)
	notify.Subscribe(metadata.METHOD_UPDATE, s)
	notify.Subscribe(metadata.METHOD_DELETE, s)

	// Proxy
}

func (s *Service) Notify(ctx context.Context, event uint32, payload any) notify.Response[any] {
	switch event {
	case link.METHOD_ADD:
		{
			_, err := s.cqsStore.LinkAdd(ctx, payload.(*link.Link))
			if err != nil {
				s.logger.ErrorWithContext(ctx, err.Error())
			}

			return notify.Response[any]{}
		}
	case link.METHOD_UPDATE:
		{
			_, err := s.cqsStore.LinkUpdate(ctx, payload.(*link.Link))
			if err != nil {
				s.logger.ErrorWithContext(ctx, err.Error())
			}

			return notify.Response[any]{}
		}
	case link.METHOD_DELETE:
		{
			err := s.cqsStore.LinkDelete(ctx, payload.(string))
			if err != nil {
				s.logger.ErrorWithContext(ctx, err.Error())
			}

			return notify.Response[any]{}
		}
	case metadata.METHOD_ADD:
		fallthrough
	case metadata.METHOD_UPDATE:
		{
			_, err := s.cqsStore.MetadataUpdate(ctx, payload.(*metadata.Meta))
			if err != nil {
				s.logger.ErrorWithContext(ctx, err.Error())
			}

			return notify.Response[any]{}
		}
	default:
		return notify.Response[any]{}
	}
}

repository: shortlink-org/shortlink

repo_name: shortlink-org/shortlink


text:
SUMMARY = "QT5 LedScreen"
DESCRIPTION = "This is LedScreen Qt5 QML component"
HOMEPAGE = "http://quitcoding.com/?page=work#cinex"
LICENSE = "CC-BY-3.0"
LIC_FILES_CHKSUM = "file://README.txt;md5=fe07f4a0be40fe88f8c7ceaca63a28b5"

DEPENDS = "qtdeclarative qtgraphicaleffects"

SRC_URI = "http://quitcoding.com/download/ledscreen_1.0.tgz"
SRC_URI[md5sum] = "8fc482d5a8b16f43f022c9a282f305b8"
SRC_URI[sha256sum] = "fa4759b70a5fa148a901a3f9a659f7bd2503d73774022012bded880dffa0d15c"

S = "${WORKDIR}/ledscreen_1.0"

do_install() {
    install -d ${D}${datadir}/${P}
    #install -m 0755 ${B}/QUItBattery ${D}${datadir}/${P}
    cp -R --no-dereference --preserve=mode,links ${S}/* ${D}${datadir}/${P}
}

FILES_${PN}-dbg += "${datadir}/${P}/.debug"
FILES_${PN} += "${datadir}"

RDEPENDS_${PN} = "qtdeclarative-qmlplugins qtgraphicaleffects-qmlplugins"


text:
#NOTE: We need the device API to call kernels when using oneAPI
if (TARGET device)
    message("target device has already been added!")
else()
    add_subdirectory(root)
endif()

set(KERNEL_SOURCE_FILES subroutinesONEAPI.cpp)
add_library(${TARGET_NAME} SHARED ${KERNEL_SOURCE_FILES})
target_link_libraries(${TARGET_NAME} PUBLIC stdc++fs)

target_compile_options(${TARGET_NAME} PRIVATE ${EXTRA_FLAGS} -Wall -Wpedantic -std=c++17 -O3)
target_compile_definitions(${TARGET_NAME} PRIVATE DEVICE_${DEVICE_BACKEND}_LANG REAL_SIZE=${REAL_SIZE_IN_BYTES})

target_include_directories(${TARGET_NAME} PUBLIC root)
target_link_libraries(${TARGET_NAME} PUBLIC device)

if (${DEVICE_BACKEND} STREQUAL "hipsycl")
    if(NOT DEFINED HIPSYCL_TARGETS)
        set(HIPSYCL_TARGETS "cuda:sm_${DEVICE_ARCH}")
    endif()

    find_package(hipSYCL CONFIG REQUIRED)
    add_sycl_to_target(TARGET ${TARGET_NAME} SOURCES ${DEVICE_SOURCE_FILES})
else()
    set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/root/cmake" "${CMAKE_ROOT}/Modules")
    find_package(DpcppFlags REQUIRED)
    target_link_libraries(${TARGET_NAME} PRIVATE dpcpp::device_flags)
endif()

repository: SeisSol/Device

repo_name: SeisSol/Device

extension: cmake


text:
@inproceedings{kanojia-etal-2020-commentaries,
    title = "Strategies of Effective Digitization of Commentaries and Sub
commentaries Towards the Construction of Textual History",
    author = "Kanojia, Diptesh and Ghodekar, Sayali and Kulkarni, Malhar and Kahrs, Eivind and Bhattacharyya, Pushpak"

    booktitle = "Proceedings of the International Conference on Tradition of Commentaries and Flow of Knowledge",
    month = jan,
    year = "2020",
    address = "Veraval, Gujrat, India",
    publisher = "Shree Somnath Sanskrit University",
    isbn = "978-93-83097-43-2"
    pages = "477--489",
    editor = "Gopabandhu Mishra"
    abstract = "This paper describes additional aspects of a digital tool called the ‘Textual History Tool’. We describe its various salient features with special reference to those of its features that may help the philologist digitize commentaries and sub-commentaries on a text. This tool captures the historical evolution of a text through various temporal stages, and interrelated data culled from various types of related texts. We use the text of the Kāśikāvṛtti (KV) as a sample text, and with the help of philologists, we digitize the commentaries available to us. We digitize the Nyāsa (Ny), the Padamañjarī (Pm) and sub commentaries on the KV text known as the Tantrapradīpa (Tp), and the Makaranda (Mk). We divide each commentary and sub-commentary into functional units and describe the methodology and motivation behind the functional unit division. Our functional unit division helps generate more accurate phylogenetic trees for the text, based on distance methods using the data entered in the tool.",
}

repository: dipteshkanojia/academic-kickstart

repo_name: dipteshkanojia/academic-kickstart