text:
package route

import (
	//"encoding/base64"
	"fmt"
	"github.com/AlexanderChen1989/go-json-rest/rest"
	"golang.org/x/net/context"
	//"json"
	"encoding/json"
	"middleware"
	//"strconv"
	"strings"
	//"net/http"
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"github.com/qiniu/iconv"
	"io"
	"io/ioutil"
	"model"
	"net/http"
	"os"
	"server/osinstallserver/util"
	"time"
	"utils"
)

func DeleteHardwareById(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	var info struct {
		ID          uint
		AccessToken string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	info.AccessToken = strings.TrimSpace(info.AccessToken)
	_, errVerify := VerifyAccessPurview(info.AccessToken, ctx, true, w, r)
	if errVerify != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errVerify.Error()})
		return
	}

	hardware, err := repo.GetHardwareById(info.ID)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	if hardware.IsSystemAdd == "Yes" {
		//w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "系统添加的配置不允许删除!"})
		//return
	}

	mod, err := repo.DeleteHardwareById(info.ID)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": mod})
}

func UpdateHardwareById(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	var info struct {
		ID          uint
		Company     string
		Product     string
		ModelName   string
		Raid        string
		Oob         string
		Bios        string
		Tpl         string
		Data        string
		Source      string
		Version     string
		Status      string
		AccessToken string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	info.AccessToken = strings.TrimSpace(info.AccessToken)
	_, errVerify := VerifyAccessPurview(info.AccessToken, ctx, true, w, r)
	if errVerify != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errVerify.Error()})
		return
	}

	info.Company = strings.TrimSpace(info.Company)
	info.Product = strings.TrimSpace(info.Product)
	info.ModelName = strings.TrimSpace(info.ModelName)
	info.Tpl = strings.TrimSpace(info.Tpl)
	info.Data = strings.TrimSpace(info.Data)
	info.Source = strings.TrimSpace(info.Source)
	info.Version = strings.TrimSpace(info.Version)
	info.Status = strings.TrimSpace(info.Status)

	if info.Company == "" || info.ModelName == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "请将信息填写完整!"})
		return
	}

	count, err := repo.CountHardwareByCompanyAndProductAndNameAndId(info.Company, info.Product, info.ModelName, info.ID)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	if count > 0 {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "该硬件型号已存在!"})
		return
	}

	hardware, err := repo.GetHardwareById(info.ID)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	if hardware.IsSystemAdd == "Yes" {
		//w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "系统添加的配置不允许修改!"})
		//return
	}

	mod, err := repo.UpdateHardwareById(info.ID, info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.Tpl, info.Data, info.Source, info.Version, info.Status)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": mod})
}

func GetHardwareById(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	var info struct {
		ID uint
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	mod, err := repo.GetHardwareById(info.ID)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": mod})
}

func GetCompanyByGroup(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	mod, err := repo.GetCompanyByGroup()
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": mod})
}

func ExportHardware(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	/*
		var info struct {
			Ids []int
		}

			if err := r.DecodeJSONPayload(&info); err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
				return
			}
	*/

	var where string
	where = " and is_system_add = 'Yes' "
	idsParam := r.FormValue("ids")
	if idsParam != "" {
		ids := strings.Split(idsParam, ",")
		if len(ids) > 0 {
			/*
				for _, id := range info.Ids {
					ids = append(ids, strconv.Itoa(id))
				}
			*/
			where += " and id in (" + strings.Join(ids, ",") + ")"
		}
	}

	company := r.FormValue("company")
	if company != "" {
		where += " and company = '" + company + "' "
	}

	product := r.FormValue("product")
	if product != "" {
		where += " and product = '" + product + "' "
	}

	modelName := r.FormValue("modelName")
	if modelName != "" {
		where += " and model_name = '" + modelName + "' "
	}

	mods, err := repo.GetHardwareListWithPage(10000, 0, where)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	var result []map[string]interface{}
	for _, v := range mods {
		result2 := make(map[string]interface{})
		result2["Company"] = v.Company
		result2["Product"] = v.Product
		result2["ModelName"] = v.ModelName
		result2["IsSystemAdd"] = v.IsSystemAdd
		result2["Tpl"] = v.Tpl
		result2["Data"] = v.Data
		result = append(result, result2)
	}

	filename := "idcos-osinstall-hardware.json"
	w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename='%s';filename*=utf-8''%s", filename, filename))
	w.Header().Add("Content-Type", "application/octet-stream")
	err = json.NewEncoder(w).Encode(result)
	if err != nil {
		fmt.Println(err)
	}
}

func GetProductByWhereAndGroup(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	var info struct {
		Company string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	where := " company = '" + info.Company + "'"
	mod, err := repo.GetProductByWhereAndGroup(where)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": mod})
}

func GetModelNameByWhereAndGroup(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	var info struct {
		Company     string
		Product     string
		IsSystemAdd string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}

	where := " company = '" + info.Company + "'"
	if info.Product != "" {
		where += " and product = '" + info.Product + "'"
	}

	if info.IsSystemAdd != "" {
		where += " and is_system_add = '" + info.IsSystemAdd + "'"
	}

	mod, err := repo.GetModelNameByWhereAndGroup(where)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": mod})
}

func GetHardwareList(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	var info struct {
		Limit       uint
		Offset      uint
		Company     string
		Product     string
		ModelName   string
		IsSystemAdd string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	var where string
	if info.Company != "" {
		where += " and company = '" + info.Company + "' "
	}
	if info.Product != "" {
		where += " and product = '" + info.Product + "' "
	}
	if info.ModelName != "" {
		where += " and model_name = '" + info.ModelName + "' "
	}
	if info.IsSystemAdd != "" {
		where += " and is_system_add = '" + info.IsSystemAdd + "' "
	}

	mods, err := repo.GetHardwareListWithPage(info.Limit, info.Offset, where)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	result := make(map[string]interface{})

	type Hardware struct {
		ID          uint
		ShowName    string
		Company     string
		Product     string
		ModelName   string
		Raid        string
		Oob         string
		Bios        string
		IsSystemAdd string
		Tpl         string
		Data        string
		Source      string
		Version     string
		Status      string
	}
	var hardwares []Hardware
	for _, v := range mods {
		var hardware Hardware
		hardware.ID = v.ID
		hardware.ShowName = v.Company + "-" + v.ModelName
		hardware.Company = v.Company
		hardware.Product = v.Product
		hardware.ModelName = v.ModelName
		hardware.Raid = v.Raid
		hardware.Oob = v.Oob
		hardware.Bios = v.Bios
		hardware.IsSystemAdd = v.IsSystemAdd
		hardware.Tpl = v.Tpl
		hardware.Data = v.Data
		hardware.Source = v.Source
		hardware.Version = v.Version
		hardware.Status = v.Status
		hardwares = append(hardwares, hardware)
	}
	result["list"] = hardwares

	//总条数
	count, err := repo.CountHardware(where)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	result["recordCount"] = count

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
}

//添加
func AddHardware(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}
	var info struct {
		Company     string
		Product     string
		ModelName   string
		Raid        string
		Oob         string
		Bios        string
		IsSystemAdd string
		Tpl         string
		Data        string
		Source      string
		Version     string
		Status      string
		AccessToken string
	}
	if err := r.DecodeJSONPayload(&info); err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误"})
		return
	}

	info.Company = strings.TrimSpace(info.Company)
	info.Product = strings.TrimSpace(info.Product)
	info.ModelName = strings.TrimSpace(info.ModelName)
	info.IsSystemAdd = strings.TrimSpace(info.IsSystemAdd)
	info.Tpl = strings.TrimSpace(info.Tpl)
	info.Data = strings.TrimSpace(info.Data)
	info.Source = strings.TrimSpace(info.Source)
	info.Version = strings.TrimSpace(info.Version)
	info.Status = strings.TrimSpace(info.Status)

	info.AccessToken = strings.TrimSpace(info.AccessToken)
	_, errVerify := VerifyAccessPurview(info.AccessToken, ctx, true, w, r)
	if errVerify != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errVerify.Error()})
		return
	}

	if info.Company == "" || info.ModelName == "" {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "请将信息填写完整!"})
		return
	}

	count, err := repo.CountHardwareByCompanyAndProductAndName(info.Company, info.Product, info.ModelName)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	if count > 0 {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "该硬件型号已存在!"})
		return
	}

	_, errAdd := repo.AddHardware(info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.IsSystemAdd, info.Tpl, info.Data, info.Source, info.Version, info.Status)
	if errAdd != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAdd.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功"})
}

func UploadCompanyHardware(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	file, handle, err := r.FormFile("file")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	cd, err := iconv.Open("UTF-8", "GBK")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	defer cd.Close()

	dir := "./upload/"
	if !util.FileExist(dir) {
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}

	list := strings.Split(handle.Filename, ".")
	fix := list[len(list)-1]

	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%s", time.Now().UnixNano()) + handle.Filename))
	cipherStr := h.Sum(nil)
	md5 := fmt.Sprintf("%s", hex.EncodeToString(cipherStr))
	filename := md5 + "." + fix

	result := make(map[string]interface{})
	result["result"] = filename

	if util.FileExist(dir + filename) {
		os.Remove(dir + filename)
	}

	f, err := os.OpenFile(dir+filename, os.O_WRONLY|os.O_CREATE, 0666)
	io.Copy(f, file)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	defer f.Close()
	defer file.Close()

	fileHandle, err := os.Open(dir + filename)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	var data []map[string]interface{}
	bytes, err := ioutil.ReadAll(fileHandle)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	errDecode := json.Unmarshal(bytes, &data)
	if errDecode != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "文件格式错误:" + errDecode.Error()})
		return
	}
	for _, v := range data {
		if v["Company"] == "" || v["ModelName"] == "" {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "文件格式错误!"})
			return
		}
	}

	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	for _, v := range data {
		var info struct {
			Company     string
			Product     string
			ModelName   string
			Raid        string
			Oob         string
			Bios        string
			IsSystemAdd string
			Tpl         string
			Data        string
			Source      string
			Version     string
			Status      string
		}

		info.Company = strings.TrimSpace(v["Company"].(string))
		info.Product = strings.TrimSpace(v["Product"].(string))
		info.ModelName = strings.TrimSpace(v["ModelName"].(string))
		info.IsSystemAdd = "Yes"
		info.Tpl = strings.TrimSpace(v["Tpl"].(string))
		info.Data = strings.TrimSpace(v["Data"].(string))
		info.Source = strings.TrimSpace(info.Source)
		info.Version = strings.TrimSpace(info.Version)
		info.Status = "Pending"

		where := "company = '" + info.Company + "' and product = '" + info.Product + "' and model_name = '" + info.ModelName + "' and is_system_add = 'Yes'"

		count, err := repo.CountHardwareByWhere(where)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if count > 0 {
			hardware, err := repo.GetHardwareByWhere(where)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
			var isUpdate bool
			isUpdate = false
			if hardware.Data != info.Data {
				isUpdate = true
			}
			if hardware.Tpl != info.Tpl {
				isUpdate = true
			}
			if isUpdate == true {
				_, err := repo.UpdateHardwareById(hardware.ID, info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.Tpl, info.Data, info.Source, info.Version, info.Status)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}
			}
		} else {
			_, errAdd := repo.AddHardware(info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.IsSystemAdd, info.Tpl, info.Data, info.Source, info.Version, info.Status)
			if errAdd != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAdd.Error()})
				return
			}
		}
	}
	//delete tmp file
	errDeleteFile := os.Remove(dir + filename)
	if errDeleteFile != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errDeleteFile.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
	return
}

func UploadHardware(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	file, handle, err := r.FormFile("file")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	cd, err := iconv.Open("UTF-8", "GBK")
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "参数错误" + err.Error()})
		return
	}
	defer cd.Close()

	dir := "./upload/"
	if !util.FileExist(dir) {
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}
	}

	list := strings.Split(handle.Filename, ".")
	fix := list[len(list)-1]

	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%s", time.Now().UnixNano()) + handle.Filename))
	cipherStr := h.Sum(nil)
	md5 := fmt.Sprintf("%s", hex.EncodeToString(cipherStr))
	filename := md5 + "." + fix

	result := make(map[string]interface{})
	result["result"] = filename

	if util.FileExist(dir + filename) {
		os.Remove(dir + filename)
	}

	f, err := os.OpenFile(dir+filename, os.O_WRONLY|os.O_CREATE, 0666)
	io.Copy(f, file)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	defer f.Close()
	defer file.Close()

	fileHandle, err := os.Open(dir + filename)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	var data []map[string]interface{}
	bytes, err := ioutil.ReadAll(fileHandle)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}
	errDecode := json.Unmarshal(bytes, &data)
	if errDecode != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "文件格式错误:" + errDecode.Error()})
		return
	}
	for _, v := range data {
		if v["Company"] == "" || v["ModelName"] == "" {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "文件格式错误!"})
			return
		}
	}

	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	for _, v := range data {
		var info struct {
			Company     string
			Product     string
			ModelName   string
			Raid        string
			Oob         string
			Bios        string
			IsSystemAdd string
			Tpl         string
			Data        string
			Source      string
			Version     string
			Status      string
		}

		info.Company = strings.TrimSpace(v["Company"].(string))
		info.Product = strings.TrimSpace(v["Product"].(string))
		info.ModelName = strings.TrimSpace(v["ModelName"].(string))
		info.IsSystemAdd = "Yes"
		info.Tpl = strings.TrimSpace(v["Tpl"].(string))
		info.Data = strings.TrimSpace(v["Data"].(string))
		info.Source = strings.TrimSpace(info.Source)
		info.Version = strings.TrimSpace(info.Version)
		info.Status = "Success"

		where := "company = '" + info.Company + "' and product = '" + info.Product + "' and model_name = '" + info.ModelName + "' and is_system_add = 'Yes'"

		count, err := repo.CountHardwareByWhere(where)
		if err != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
			return
		}

		if count > 0 {
			hardware, err := repo.GetHardwareByWhere(where)
			if err != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
				return
			}
			var isUpdate bool
			isUpdate = false
			if hardware.Data != info.Data {
				isUpdate = true
			}
			if hardware.Tpl != info.Tpl {
				isUpdate = true
			}
			if isUpdate == true {
				_, err := repo.UpdateHardwareById(hardware.ID, info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.Tpl, info.Data, info.Source, info.Version, info.Status)
				if err != nil {
					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
					return
				}
			}
		} else {
			_, errAdd := repo.AddHardware(info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.IsSystemAdd, info.Tpl, info.Data, info.Source, info.Version, info.Status)
			if errAdd != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errAdd.Error()})
				return
			}
		}
	}
	//delete tmp file
	errDeleteFile := os.Remove(dir + filename)
	if errDeleteFile != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errDeleteFile.Error()})
		return
	}

	w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": result})
	return
}

func CheckOnlineUpdate(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	lastestHardware, err := repo.GetLastestVersionHardware()
	type HardwareVersionWithDate struct {
		Version string
		Date    utils.ISOTime
	}
	var hardwareVersionWithDate HardwareVersionWithDate
	hardwareVersionWithDate.Version = lastestHardware.Version
	hardwareVersionWithDate.Date = utils.ISOTime(lastestHardware.CreatedAt)

	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	result := make(map[string]interface{})
	result["Version"] = lastestHardware.Version
	b, err := json.Marshal(result)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	body := bytes.NewBuffer([]byte(b))
	resp, err := http.Post("http://open.idcos.com/api/x86/check-online-update", "application/json;charset=utf-8", body)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "网络连接故障，在线更新配置库失败！", "CurrentVersion": hardwareVersionWithDate})
		return
	}
	reportResult, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	type content struct {
		Version string `json:"Version"`
		Date    string `json:"Date"`
	}
	type Response struct {
		Status  string    `json:"Status"`
		Message string    `json:"Message"`
		Content []content `json:"Content"`
	}
	var response Response
	errJson := json.Unmarshal(reportResult, &response)
	if errJson != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errJson.Error()})
		return
	}
	if response.Status == "success" {
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "", "Content": response.Content, "CurrentVersion": hardwareVersionWithDate})
	} else {
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作失败！"})
	}
}

func RunOnlineUpdate(ctx context.Context, w rest.ResponseWriter, r *rest.Request) {
	repo, ok := middleware.RepoFromContext(ctx)
	if !ok {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "内部服务器错误"})
		return
	}

	lastestHardware, err := repo.GetLastestVersionHardware()
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	result := make(map[string]interface{})
	result["Version"] = lastestHardware.Version

	b, err := json.Marshal(result)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	body := bytes.NewBuffer([]byte(b))
	resp, err := http.Post("http://open.idcos.com/api/x86/run-online-update", "application/json;charset=utf-8", body)
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": "网络连接故障，操作失败！您可以通过线下方式分享给我们，谢谢！"})
		return
	}
	reportResult, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": err.Error()})
		return
	}

	type Response struct {
		Status  string           `json:"Status"`
		Message string           `json:"Message"`
		Content []model.Hardware `json:"Content"`
	}
	var response Response
	errJson := json.Unmarshal(reportResult, &response)
	if errJson != nil {
		w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errJson.Error()})
		return
	}
	if response.Status == "success" {
		var fix = "_" + time.Now().Format("20060102")
		errBack := repo.CreateHardwareBackupTable(fix)
		if errBack != nil {
			w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errBack.Error()})
			return
		}

		for _, info := range response.Content {
			info.Company = strings.TrimSpace(info.Company)
			info.Product = strings.TrimSpace(info.Product)
			info.ModelName = strings.TrimSpace(info.ModelName)
			info.IsSystemAdd = strings.TrimSpace(info.IsSystemAdd)
			info.Tpl = strings.TrimSpace(info.Tpl)
			info.Data = strings.TrimSpace(info.Data)
			info.Source = strings.TrimSpace(info.Source)
			info.Version = strings.TrimSpace(info.Version)
			info.Status = strings.TrimSpace(info.Status)

			if info.Status == "Success" {
				if info.Company == "" || info.ModelName == "" {
					continue
				}

				count, err := repo.CountHardwareByCompanyAndProductAndName(info.Company, info.Product, info.ModelName)
				if err != nil {
					errRollback := repo.RollbackHardwareFromBackupTable(fix)
					message := err.Error()
					if errRollback != nil {
						message += errRollback.Error()
					}

					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
					return
				}

				if count > 0 {
					hardwareId, err := repo.GetHardwareIdByCompanyAndProductAndName(info.Company, info.Product, info.ModelName)
					if err != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := err.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
					hardware, err := repo.GetHardwareById(hardwareId)
					if err != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := err.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
					if hardware.IsSystemAdd != "Yes" {
						continue
					}

					_, errUpdate := repo.UpdateHardwareById(hardware.ID, info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.Tpl, info.Data, info.Source, info.Version, info.Status)
					if errUpdate != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := errUpdate.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
				} else {
					_, errAdd := repo.AddHardware(info.Company, info.Product, info.ModelName, info.Raid, info.Oob, info.Bios, info.IsSystemAdd, info.Tpl, info.Data, info.Source, info.Version, info.Status)
					if errAdd != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := errAdd.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
				}
			} else if info.Status == "Deleted" {
				count, err := repo.CountHardwareByCompanyAndProductAndName(info.Company, info.Product, info.ModelName)
				if err != nil {
					errRollback := repo.RollbackHardwareFromBackupTable(fix)
					message := err.Error()
					if errRollback != nil {
						message += errRollback.Error()
					}

					w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
					return
				}

				if count > 0 {
					hardwareId, err := repo.GetHardwareIdByCompanyAndProductAndName(info.Company, info.Product, info.ModelName)
					if err != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := err.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
					hardware, err := repo.GetHardwareById(hardwareId)
					if err != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := err.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
					if hardware.IsSystemAdd != "Yes" {
						continue
					}

					_, errDelete := repo.DeleteHardwareById(hardware.ID)
					if errDelete != nil {
						errRollback := repo.RollbackHardwareFromBackupTable(fix)
						message := errDelete.Error()
						if errRollback != nil {
							message += errRollback.Error()
						}

						w.WriteJSON(map[string]interface{}{"Status": "error", "Message": message})
						return
					}
				}
			}
		}
		/*
			errDrop := repo.DropHardwareBackupTable()
			if errDrop != nil {
				w.WriteJSON(map[string]interface{}{"Status": "error", "Message": errDrop.Error()})
				return
			}
		*/

		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作成功", "Content": response.Content})
	} else {
		w.WriteJSON(map[string]interface{}{"Status": "success", "Message": "操作失败！您可以通过线下方式分享给我们，谢谢！"})
	}
}

repository: wocai/osinstall

repo_name: wocai/osinstall


text:
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 cmd

import (
	"log"

	"github.com/Agenda-Go/entity"
	"github.com/spf13/cobra"
)

// deleteMeetingCmd represents the deleteMeeting command
var deleteMeetingCmd = &cobra.Command{
	Use:   "deleteMeeting",
	Short: "Delete a meeting you sponsored",
	Long:  "Usage：agenda deleteMeeting -t [title]",
	Run: func(cmd *cobra.Command, args []string) {
		nowUser := entity.GetCurrentUser()
		t, _ := cmd.Flags().GetString("title")
		solveResult := entity.DeleteMeeting(t, nowUser)
		if solveResult == 0 {
			log.Println("delete succesfully")
		} else if solveResult == 1 {
			log.Println("you are not the sponsor of the meeting or the meeting title is not exist")
		} else if solveResult == 2 {
			log.Println("delete failed , you haven't logged in")
		}
		entity.UpdateLib()
	},
}

func init() {
	rootCmd.AddCommand(deleteMeetingCmd)
	entity.Init()
	deleteMeetingCmd.Flags().StringP("title", "t", "", "")
}

repository: hollenli/Agenda-Go

license_type: permissive

repo_name: hollenli/Agenda-Go

branch_name: refs/heads/master

extension: go


text:
@misc{Lentrodt2020b,
	title={Ab initio quantum models for thin-film x-ray cavity QED},
	author={Dominik Lentrodt and Kilian P. Heeg and Christoph H. Keitel and J\"org Evers},
	year={2020},
	eprint={2003.13859},
	archivePrefix={arXiv},
	primaryClass={quant-ph}
}

license: MIT

repository: dlentrodt/academic-kickstart

repo_name: dlentrodt/academic-kickstart

gha_license_id: MIT

extension: bib


text:
require ../../include/gles-control.inc
require ../../include/multimedia-control.inc

DESCRIPTION = "Package Group for multimedia of R-Car Gen2"
LICENSE = "CLOSED"

inherit packagegroup

PACKAGES = "\
    packagegroup-rcar-gen2-multimedia \
    packagegroup-rcar-gen2-multimedia-tp \
    packagegroup-rcar-gen2-dtv \
"

MULTIMEDIA_PACKAGES ="\
    mmngr-kernel-module mmngr-user-module \
    mmngrbuf-kernel-module mmngrbuf-user-module \
    mmngrbuf-user-module-dev \
    fdpm-kernel-module fdpm-user-module \
    vspm-kernel-module vspm-user-module \
    s3ctl-kernel-module s3ctl-user-module \
    uvcs-kernel-module omx-user-module \
    libmemcpy \
"

MULTIMEDIA_PACKAGES_append = " \
    ${@ "vsp2-kernel-module" if "${USE_GLES_WAYLAND}" == "1" else "" } \
"

RDEPENDS_packagegroup-rcar-gen2-multimedia = "\
    ${@ "${MULTIMEDIA_PACKAGES}" if "${USE_MULTIMEDIA}" == "1" else "" } \
    media-ctl \
	gstreamer1.0-meta-base \
	gstreamer1.0-meta-audio \
	gstreamer1.0-meta-video \
    gstreamer1.0-plugins-base-audioconvert \
    gstreamer1.0-plugins-base-audioresample \
    gstreamer1.0-plugins-base-playback \
    gstreamer1.0-plugins-base-videoconvert \
    gstreamer1.0-plugins-base-typefindfunctions \
    gstreamer1.0-plugins-base-videoscale \
    gstreamer1.0-plugins-good-avi \
    gstreamer1.0-plugins-good-audioparsers \
	gstreamer1.0-plugins-good-id3demux \
    gstreamer1.0-plugins-bad-faad \
    gstreamer1.0-plugins-bad-mpegtsdemux \
    gstreamer1.0-plugins-bad-debugutilsbad \
    ${@bb.utils.contains("LICENSE_FLAGS_WHITELIST", "commercial", "gstreamer1.0-omx gstreamer1.0-plugins-ugly-asf", "", d )} \
    ${@base_conditional("USE_GLES_WAYLAND", "1", "gstreamer1.0-plugins-base-vspfilter", "", d )} \
"

MULTIMEDIA_TEST_PACKAGES = "\
    ${MULTIMEDIA_PACKAGES} \
    mmngr-tp-user-module \
    mmngrbuf-tp-user-module \
    fdpm-tp-user-module \
    vspm-tp-user-module \
    s3ctl-tp-user-module \
"

RDEPENDS_packagegroup-rcar-gen2-multimedia-tp = "\
    ${@ '${MULTIMEDIA_TEST_PACKAGES}' if '${USE_MULTIMEDIA}' == '1' and '${USE_MULTIMEDIA_TEST}' == '1' else '' } \
"

DTV_PACKAGES = "\
    ${MULTIMEDIA_PACKAGES} \
    scu-kernel-module ssp-kernel-module \
    dtv \
"

RDEPENDS_packagegroup-rcar-gen2-dtv = "\
    ${@ '${DTV_PACKAGES}' if '${USE_DTV}' == '1' else '' } \
"

gha_language: Python

extension: bb


text:
#ifndef _VECTOR3D_H
#define _VECTOR3D_H

#include <math.h>

class vec2
{
public:
	float x;
	float y;

	inline vec2(void) :
		x(0), y(0)
	{ }

	inline vec2(float f)
	{
		x = y = f;
	}

	inline vec2(float _x, float _y)
	{
		x = _x;  y = _y;
	}

	inline vec2(const float f[2])
	{
		x = f[0];  y = f[1];
	}

	inline const float& operator[](int i) const
	{
		return (&x)[i];
	}

	inline float& operator[](int i)
	{
		return (&x)[i];
	}

	inline vec2& operator += (const vec2& v)
	{
		x += v.x;  y += v.y;
		return *this;
	}

	inline vec2& operator -= (const vec2& v)
	{
		x -= v.x;  y -= v.y;
		return *this;
	}

	inline vec2& operator *= (const vec2& v)
	{
		x *= v.x;  y *= v.y;
		return *this;
	}

	inline vec2& operator /= (const vec2& v)
	{
		x /= v.x;  y /= v.y;
		return *this;
	}

	inline vec2& operator *= (float s)
	{
		x *= s;  y *= s;
		return *this;
	}

	inline vec2& operator /= (float s)
	{
		float a = 1.0f / s;
		x *= a;  y *= a;
		return *this;
	}
};

inline vec2 operator + ( const vec2& v1, const vec2& v2 )
{
	return vec2( v1.x+v2.x, v1.y+v2.y );
}

inline vec2 operator - ( const vec2& v1, const vec2& v2 )
{
	return vec2( v1.x-v2.x, v1.y-v2.y );
}

inline vec2 operator * ( const vec2& v1, const vec2& v2 )
{
	return vec2( v1.x*v2.x, v1.y*v2.y );
}

inline vec2 operator / ( const vec2& v1, const vec2& v2 )
{
	return vec2( v1.x/v2.x, v1.y/v2.y );
}

inline vec2 operator * ( const vec2& v, float s )
{
	return vec2( s*v.x, s*v.y );
}

inline vec2 operator / ( const vec2& v, float s )
{
	float a = 1.0f/s;
	return vec2( v.x*a, v.y*a );
}

inline bool operator == ( const vec2& v1, const vec2& v2 )
{
	return  v1.x == v2.x  &&  v1.y == v2.y;
}

inline bool operator != ( const vec2& v1, const vec2& v2 )
{
	return v1.x != v2.x  ||  v1.y != v2.y;
}

inline float vdot( const vec2& v1, const vec2& v2 )
{
	return v1.x*v2.x + v1.y*v2.y;
}

inline float vlen(const vec2& v)
{
	double dValueX = static_cast<double>(v.x);
	double dValueY = static_cast<double>(v.y);
	return static_cast<float>(sqrt((dValueX * dValueX) + (dValueY * dValueY)));
}

inline float vlen2(const vec2& v)
{
	return v.x * v.x + v.y * v.y;
}

inline vec2 vnorm(const vec2& v)
{
	float M = vlen(v);
	return (M == 0.0) ? v : v * (1.0f / M);
}

// Angle between [0,PI].
inline double vang( const vec2& v1, const vec2& v2 )
{
	vec2 v1Norm = vnorm(v1);
	vec2 v2Norm = vnorm(v2);
	float dot = vdot(v1Norm, v2Norm);
	dot = dot > 1.0f ? 1.0f : dot;
	dot = dot < -1.0f ? -1.0f : dot;
	return acos(dot);
}

#endif

repository: KikeAjani/DragonFires

repo_name: KikeAjani/DragonFires

branch_name: refs/heads/main

extension: h


text:
package acceptance

import (
	"errors"
	"fmt"
	"os"
	"testing"

	. "github.com/databrickslabs/databricks-terraform/access"

	"github.com/databrickslabs/databricks-terraform/common"
	"github.com/databrickslabs/databricks-terraform/internal/acceptance"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
	"github.com/stretchr/testify/assert"
)

func TestAccSecretResource(t *testing.T) {
	if _, ok := os.LookupEnv("CLOUD_ENV"); !ok {
		t.Skip("Acceptance tests skipped unless env 'CLOUD_ENV' is set")
	}
	var secret SecretMetadata
	randomName := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)
	scope := fmt.Sprintf("tf-scope-%s", randomName)
	key := fmt.Sprintf("tf-key-%s", randomName)
	stringValue := "my super secret key"

	acceptance.AccTest(t, resource.TestCase{
		CheckDestroy: testSecretResourceDestroy,
		Steps: []resource.TestStep{
			{
				// use a dynamic configuration with the random name from above
				Config: testSecretResource(scope, key, stringValue),
				// compose a basic test, checking both remote and local values
				Check: resource.ComposeTestCheckFunc(
					// query the API to retrieve the tokenInfo object
					testSecretResourceExists("databricks_secret.my_secret", &secret, t),
					// verify remote values
					testSecretValues(t, &secret, key),
					// verify local values
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "scope", scope),
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "key", key),
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "string_value", stringValue),
				),
			},
			{
				//Deleting and recreating the secret
				PreConfig: func() {
					client := common.CommonEnvironmentClient()
					err := NewSecretsAPI(client).Delete(scope, secret.Key)
					assert.NoError(t, err, err)
				},
				// use a dynamic configuration with the random name from above
				Config: testSecretResource(scope, key, stringValue),
				// compose a basic test, checking both remote and local values
				Check: resource.ComposeTestCheckFunc(
					// query the API to retrieve the tokenInfo object
					testSecretResourceExists("databricks_secret.my_secret", &secret, t),
					// verify remote values
					testSecretValues(t, &secret, key),
					// verify local values
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "scope", scope),
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "key", key),
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "string_value", stringValue),
				),
			},
			{
				//Deleting the scope should recreate the secret
				PreConfig: func() {
					client := common.CommonEnvironmentClient()
					err := NewSecretScopesAPI(client).Delete(scope)
					assert.NoError(t, err, err)
				},
				// use a dynamic configuration with the random name from above
				Config: testSecretResource(scope, key, stringValue),
				// compose a basic test, checking both remote and local values
				Check: resource.ComposeTestCheckFunc(
					// query the API to retrieve the tokenInfo object
					testSecretResourceExists("databricks_secret.my_secret", &secret, t),
					// verify remote values
					testSecretValues(t, &secret, key),
					// verify local values
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "scope", scope),
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "key", key),
					resource.TestCheckResourceAttr("databricks_secret.my_secret", "string_value", stringValue),
				),
			},
		},
	})
}

func testSecretResourceDestroy(s *terraform.State) error {
	client := common.CommonEnvironmentClient()
	for _, rs := range s.RootModule().Resources {
		if rs.Type != "databricks_secret" && rs.Type != "databricks_secret_scope" {
			continue
		}
		_, err := NewSecretsAPI(client).Read(rs.Primary.Attributes["scope"], rs.Primary.Attributes["key"])
		if err == nil {
			return errors.New("resource secret is not cleaned up")
		}
		_, err = NewSecretScopesAPI(client).Read(rs.Primary.Attributes["scope"])
		if err == nil {
			return errors.New("resource secret is not cleaned up")
		}
	}
	return nil
}

func testSecretValues(t *testing.T, secret *SecretMetadata, key string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		assert.True(t, secret.Key == key)
		assert.True(t, secret.LastUpdatedTimestamp > 0)
		return nil
	}
}

// testAccCheckTokenResourceExists queries the API and retrieves the matching Widget.
func testSecretResourceExists(n string, secret *SecretMetadata, t *testing.T) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		// find the corresponding state object
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		// retrieve the configured client from the test setup
		conn := common.CommonEnvironmentClient()
		resp, err := NewSecretsAPI(conn).Read(rs.Primary.Attributes["scope"], rs.Primary.Attributes["key"])
		//t.Log(resp)
		if err != nil {
			return err
		}

		// If no error, assign the response Widget attribute to the widget pointer
		*secret = resp
		return nil
		//return fmt.Errorf("Token (%s) not found", rs.Primary.ID)
	}
}

// testAccTokenResource returns an configuration for an Example Widget with the provided name
func testSecretResource(scopeName, key, value string) string {
	return fmt.Sprintf(`
		resource "databricks_secret_scope" "my_scope" {
			name = "%s"
		}
		resource "databricks_secret" "my_secret" {
			key = "%s"
			string_value = "%s"
			scope = databricks_secret_scope.my_scope.name
		}
		`, scopeName, key, value)
}

repository: rivoobmab/terraform-provider-databricks

repo_name: rivoobmab/terraform-provider-databricks


text:
CUDA_PKG = "${BPN}"

require cuda-shared-binaries-${PV}.inc

MAINSUM = "882c05ec6d681980c1a6cc5afacd4c2a58e6d819cb1aa043ae16bb74f97a70f8"
MAINSUM:x86-64 = "16d1ce512b030ada31a5e1ef7324fa5b01758f3249e582e85727decaba8bd255"

DEPENDS = "cuda-cupti"
DEPENDS:append:tegra = " tegra-libraries-cuda"

BBCLASSEXTEND = "native nativesdk"

repository: danielwangksu/meta-tegra

repo_name: danielwangksu/meta-tegra


text:
package mgo

import (
	"github.com/davyxu/cellnet"
	"gopkg.in/mgo.v2"
	"reflect"
)

func (self *mongoDriver) readTask(evq cellnet.EventQueue, usercallback interface{}, execCallback func(*mgo.Database, interface{}) error) {

	callbackType := reflect.TypeOf(usercallback)
	callbackValue := reflect.ValueOf(usercallback)

	resultPtrType := callbackType.In(0)
	// 取回调函数第一个参数类型
	resultType := resultPtrType.Elem()

	// 实例化
	result := reflect.New(resultType)

	db := self.fetch()

	err := execCallback(db, result.Interface())

	self.back(db)

	//将回调函数投递到主线程
	evq.PostData(func() {

		errValue := reflect.ValueOf(&err).Elem()

		// 错误时, 返回空
		if err == nil {

			// http://play.golang.org/p/TZyOLzu2y-
			callbackValue.Call([]reflect.Value{result, errValue})
		} else {
			// http://grokbase.com/t/gg/golang-nuts/13adpw445j/go-nuts-reflect-set-to-nil
			callbackValue.Call([]reflect.Value{reflect.Zero(resultPtrType), errValue})
		}

	})
}

func (self *mongoDriver) writeTask(evq cellnet.EventQueue, usercallback func(error), execCallback func(*mgo.Database) error) {

	db := self.fetch()

	err := execCallback(db)

	self.back(db)

	if usercallback != nil {
		//将回调函数投递到主线程
		evq.PostData(func() {

			usercallback(err)

		})
	}

}

repository: huangsusjtu/cellnet

repo_name: huangsusjtu/cellnet


text:
//
// Alimer is based on the Turso3D codebase.
// Copyright (c) 2018 Amer Koleci and contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "String.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

namespace Alimer
{
	string str::Replace(
		const string& str,
		const string& find,
		const string& replace,
		uint32_t maxReplacements)
	{
		string dest = str;
		size_t pos = 0;
		while ((pos = dest.find(find, pos)) != string::npos)
		{
			dest.replace(dest.find(find), find.size(), replace);
			maxReplacements--;
			pos += replace.size();
			if (maxReplacements == 0)
				break;
		}

		return dest;
	}

	vector<string> str::Split(const string& value, const string& separator, bool keepEmpty)
	{
		assert(!separator.empty());
		vector<string> result;
		string::const_iterator itStart = value.begin(), itEnd;

		for (;;)
		{
			itEnd = search(itStart, value.end(), separator.begin(), separator.end());
			string token(itStart, itEnd);
			if (keepEmpty || !token.empty())
				result.push_back(token);
			if (itEnd == value.end())
				break;
			itStart = itEnd + separator.size();
		}
		return result;
	}

	string str::Join(const vector<string>& collection, const string& glue)
	{
		string result;
		if (!collection.empty())
		{
			result = collection.front();

			for (auto it = collection.begin() + 1; it != collection.end(); it++)
				result += glue + *it;
		}
		return result;
	}

	string str::Trim(const string& source)
	{
		size_t trimStart = 0;
		size_t trimEnd = source.length();

		while (trimStart < trimEnd)
		{
			char c = source[trimStart];
			if (c != ' ' && c != 9)
				break;
			++trimStart;
		}
		while (trimEnd > trimStart)
		{
			char c = source[trimEnd - 1];
			if (c != ' ' && c != 9)
				break;
			--trimEnd;
		}

		return source.substr(trimStart, trimEnd - trimStart);
	}

	std::string str::ToUpper(const std::string& source)
	{
		std::string result(source);

		for (auto it = result.begin(); it != result.end(); ++it)
			*it = Alimer::ToUpper(*it);

		return result;
	}

	string str::ToLower(const string& source)
	{
		string result(source);

		for (auto it = result.begin(); it != result.end(); ++it)
			*it = Alimer::ToLower(*it);

		return result;
	}

	bool str::StartsWith(const string& str, const string& value, bool caseSensitive)
	{
		if (caseSensitive)
			return str.find(value) != string::npos;

		return str::ToLower(str).find(str::ToLower(value)) != string::npos;
	}

	bool str::EndsWith(const std::string& str, const std::string& value, bool caseSensitive)
	{
		size_t pos;
		if (caseSensitive)
		{
			pos = str.find_last_of(value);
		}
		else
		{
			pos = str::ToLower(str).find_last_of(str::ToLower(value));
		}

		return pos != string::npos && pos == str.length() - str.length();
	}

	bool str::ToBool(const char* str)
	{
		const size_t length = strlen(str);

		for (size_t i = 0; i < length; ++i)
		{
			char c = Alimer::ToLower(str[i]);
			if (c == 't' || c == 'y' || c == '1')
				return true;
			else if (c != ' ' && c != '\t')
				break;
		}

		return false;
	}

	int str::ToInt(const char* str)
	{
		if (!str)
			return 0;

		// Explicitly ask for base 10 to prevent source starts with '0' or '0x' from being converted to base 8 or base 16, respectively
		return strtol(str, 0, 10);
	}

	unsigned str::ToUInt(const char* str)
	{
		if (!str)
			return 0;

		return strtoul(str, 0, 10);
	}

	float str::ToFloat(const char* str)
	{
		if (!str)
			return 0;

		return (float)strtod(str, 0);
	}

	int str::Compare(const std::string& str1, const std::string& str2, bool caseSensitive)
	{
		return str::Compare(str1.c_str(), str2.c_str(), caseSensitive);
	}

	int str::Compare(const char* str1, const char* str2, bool caseSensitive)
	{
		if (caseSensitive)
			return strcmp(str1, str2);

#ifdef _MSC_VER
		return _strcmpi(str1, str2);
#else
		return strcasecmp(str1, str2);
#endif
	}

	string str::Format(const char* format, ...)
	{
		va_list args;
		va_start(args, format);
		char buf[256];
		size_t n = std::vsnprintf(buf, sizeof(buf), format, args);
		va_end(args);

		// Static buffer large enough?
		if (n < sizeof(buf)) {
			return { buf, n };
		}

		// Static buffer too small
		string s(n + 1, 0);
		va_start(args, format);
		std::vsnprintf(const_cast<char*>(s.data()), s.size(), format, args);
		va_end(args);
		return s;
	}

	size_t str::ListIndex(const string& value, const string* strings, size_t defaultIndex, bool caseSensitive)
	{
		return str::ListIndex(value.c_str(), strings, defaultIndex, caseSensitive);
	}

	size_t str::ListIndex(const char* value, const string* strings, size_t defaultIndex, bool caseSensitive)
	{
		size_t i = 0;

		while (!strings[i].empty())
		{
			if (!str::Compare(strings[i], value, caseSensitive))
				return i;
			++i;
		}

		return defaultIndex;
	}

	size_t str::ListIndex(const string& value, const char** strings, size_t defaultIndex, bool caseSensitive)
	{
		return ListIndex(value.c_str(), strings, defaultIndex, caseSensitive);
	}

	size_t str::ListIndex(const char* value, const char** strings, size_t defaultIndex, bool caseSensitive)
	{
		size_t i = 0;

		while (strings[i])
		{
			if (!str::Compare(value, strings[i], caseSensitive))
				return i;
			++i;
		}

		return defaultIndex;
	}

	void str::EncodeUTF8(char*& dest, unsigned unicodeChar)
	{
		if (unicodeChar < 0x80)
			*dest++ = (char)unicodeChar;
		else if (unicodeChar < 0x800)
		{
			dest[0] = 0xc0 | ((unicodeChar >> 6) & 0x1f);
			dest[1] = 0x80 | (unicodeChar & 0x3f);
			dest += 2;
		}
		else if (unicodeChar < 0x10000)
		{
			dest[0] = 0xe0 | ((unicodeChar >> 12) & 0xf);
			dest[1] = 0x80 | ((unicodeChar >> 6) & 0x3f);
			dest[2] = 0x80 | (unicodeChar & 0x3f);
			dest += 3;
		}
		else if (unicodeChar < 0x200000)
		{
			dest[0] = 0xf0 | ((unicodeChar >> 18) & 0x7);
			dest[1] = 0x80 | ((unicodeChar >> 12) & 0x3f);
			dest[2] = 0x80 | ((unicodeChar >> 6) & 0x3f);
			dest[3] = 0x80 | (unicodeChar & 0x3f);
			dest += 4;
		}
		else if (unicodeChar < 0x4000000)
		{
			dest[0] = 0xf8 | ((unicodeChar >> 24) & 0x3);
			dest[1] = 0x80 | ((unicodeChar >> 18) & 0x3f);
			dest[2] = 0x80 | ((unicodeChar >> 12) & 0x3f);
			dest[3] = 0x80 | ((unicodeChar >> 6) & 0x3f);
			dest[4] = 0x80 | (unicodeChar & 0x3f);
			dest += 5;
		}
		else
		{
			dest[0] = 0xfc | ((unicodeChar >> 30) & 0x1);
			dest[1] = 0x80 | ((unicodeChar >> 24) & 0x3f);
			dest[2] = 0x80 | ((unicodeChar >> 18) & 0x3f);
			dest[3] = 0x80 | ((unicodeChar >> 12) & 0x3f);
			dest[4] = 0x80 | ((unicodeChar >> 6) & 0x3f);
			dest[5] = 0x80 | (unicodeChar & 0x3f);
			dest += 6;
		}
	}

	string& str::AppendUTF8(string& dest, unsigned unicodeChar)
	{
		char temp[7];
		char* destTemp = temp;
		str::EncodeUTF8(destTemp, unicodeChar);
		*destTemp = 0;
		return dest.append(temp);
	}

	size_t str::CountElements(const char* buffer, char separator)
	{
		if (!buffer)
			return 0;

		const char* endPos = buffer + strlen(buffer);
		const char* pos = buffer;
		size_t ret = 0;

		while (pos < endPos)
		{
			if (*pos != separator)
				break;
			++pos;
		}

		while (pos < endPos)
		{
			const char* start = pos;

			while (start < endPos)
			{
				if (*start == separator)
					break;

				++start;
			}

			if (start == endPos)
			{
				++ret;
				break;
			}

			const char* end = start;

			while (end < endPos)
			{
				if (*end != separator)
					break;

				++end;
			}

			++ret;
			pos = end;
		}

		return ret;
	}
}

license: MIT,Zlib

detected_licenses: MIT Zlib

extension: cpp


text:
package vega

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	downloader "github.com/srijanone/vega/pkg/downloader"
)

// ErrStarterKitNotFoundInRepo is the error returned when a starterkit is not found in a starterkits
var ErrStarterKitNotFoundInRepo = errors.New("starterkit not found")

type StarterKitRepo struct {
	Name string
	Path string // local absolute path to repo
	Home Home
	URL  string
	Dir  string // starterkits directory name at source/remote
}

type StarterKitRepos []StarterKitRepo

// RepoList list of all the local Repositories
func RepoList(path string) ([]StarterKitRepo, error) {
	var repositories StarterKitRepos

	files, err := ioutil.ReadDir(path)
	if err != nil {
		return nil, err
	}
	for _, file := range files {
		if file.IsDir() {
			repository := &StarterKitRepo{
				Name: file.Name(),
				Path: filepath.ToSlash(filepath.Join(path, file.Name())),
			}
			repositories = append(repositories, *repository)
		}
	}
	return repositories, nil
}

// StarterKitList Gets the list of all StarterKits for given repo.
func (repo *StarterKitRepo) StarterKitList() (StarterKits, error) {
	var starterkits StarterKits

	switch fileInfo, err := os.Stat(repo.Path); {
	case err != nil:
		if os.IsNotExist(err) {
			return nil, errors.New(fmt.Sprintf("No repo found with name %s", repo.Name))
		}
	case !fileInfo.IsDir():
		return nil, errors.New(fmt.Sprintf("%s is not a starterkit repo", repo.Path))
	}

	files, err := ioutil.ReadDir(repo.Path)
	if err != nil {
		return nil, err
	}
	for _, file := range files {
		if file.IsDir() {
			starterkit := &StarterKit{
				Name: file.Name(),
				Path: filepath.ToSlash(filepath.Join(repo.Path, file.Name())),
			}
			starterkits = append(starterkits, *starterkit)
		}
	}
	return starterkits, nil
}

// Find returns the starterkits matching with the given name
func (repo *StarterKitRepo) Find(name string) ([]StarterKit, error) {
	var starterkits StarterKits

	starterkitList, err := repo.StarterKitList()
	if err != nil {
		return nil, err
	}
	for _, starterkit := range starterkitList {
		// Trying to match exact name first
		if starterkit.Name == name {
			starterkits = nil
			starterkits = append(starterkits, starterkit)
			break
		}
		if strings.HasPrefix(starterkit.Name, name) {
			starterkits = append(starterkits, starterkit)
		}
	}
	return starterkits, nil
}

// Add adds repo and starterkits to vega
func (repo *StarterKitRepo) Add() {
	d := downloader.Downloader{}
	if repo.Dir == "" {
		repo.Dir = Home("").StarterKits()
	}
	sourceRepo := fmt.Sprintf("%s//%s", repo.URL, repo.Dir)
	fmt.Println("Downloading starterkits...")
	if repo.Path == "" {
		repo.Path = filepath.Join(repo.Home.StarterKits(), repo.Name)
	}
	d.Download(sourceRepo, repo.Path)
}

// Delete deletes the starterkit repo
func (repo StarterKitRepo) Delete() {
	if repo.Dir == "" {
		repo.Dir = repo.Home.StarterKits()
	}
	// TODO
}

repository: WSMathias/vega

repo_name: WSMathias/vega

branch_name: refs/heads/develop


text:
SUMMARY = "JSON for modern C++"
HOMEPAGE = "https://nlohmann.github.io/json/"
SECTION = "libs"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE.MIT;md5=f969127d7b7ed0a8a63c2bbeae002588"

CVE_PRODUCT = "json-for-modern-cpp"

SRC_URI = "git://github.com/nlohmann/json.git;nobranch=1;protocol=https \
           "

SRCREV = "bc889afb4c5bf1c0d8ee29ef35eaaf4c8bef8a5d"

S = "${WORKDIR}/git"

inherit cmake

EXTRA_OECMAKE += "-DJSON_BuildTests=OFF"

# nlohmann-json is a header only C++ library, so the main package will be empty.
ALLOW_EMPTY:${PN} = "1"
RDEPENDS:${PN}-dev = ""

BBCLASSEXTEND = "native nativesdk"

# other packages commonly reference the file directly as "json.hpp"
# create symlink to allow this usage
do_install:append() {
    ln -s nlohmann/json.hpp ${D}${includedir}/json.hpp
}

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake


text:
DESCRIPTION = "ARB2 base image"
IMAGE_INSTALL = "packagegroup-core-boot packagegroup-machine-base pciutils imx-test ${ROOTFS_PKGMANAGE_BOOTSTRAP}"
inherit core-image

# NOTE: this function runs twice, once after building the rootfs
# initially, then once again after the kernel has bundled the
# initramfs, if initramfs was wanted, so always test for existence of
# files first.
srec () {
   if [ -e ${DEPLOY_DIR_IMAGE}/u-boot-arb2.imx ]; then
      ${CROSS_COMPILE}objcopy \
        --change-addresses 0x08001000 -I binary -O srec \
	${DEPLOY_DIR_IMAGE}/u-boot-arb2.imx \
	${DEPLOY_DIR_IMAGE}/u-boot-arb2.imx.srec
   fi
   if [ -e ${DEPLOY_DIR_IMAGE}/zImage-imx6dl-arb2.dtb ]; then
      ${CROSS_COMPILE}objcopy \
        --change-addresses 0x080E0000 -I binary -O srec \
	${DEPLOY_DIR_IMAGE}/zImage-imx6dl-arb2.dtb \
	${DEPLOY_DIR_IMAGE}/zImage-imx6dl-arb2.dtb.srec
   fi
   if [ -e ${DEPLOY_DIR_IMAGE}/zImage-initramfs-arb2.bin ]; then
      ${CROSS_COMPILE}objcopy \
        --change-addresses 0x08100000 -I binary -O srec \
	${DEPLOY_DIR_IMAGE}/zImage-initramfs-arb2.bin \
	${DEPLOY_DIR_IMAGE}/zImage-initramfs-arb2.bin.srec
   fi
}

IMAGE_POSTPROCESS_COMMAND += "srec; "


text:
require ${BPN}.inc

SRC_URI += "\
    file://0001-OptionsCommon.cmake-don-t-mix-CXX_FLAGS-into-C_FLAGS.patch \
    file://0002-WebKitHelpers.cmake-Add-Wno-error-deprecated-declara.patch \
    file://0003-FEBlendNEON.h-fix-missing-semicolon.patch \
    file://0004-Fix-the-build-with-EFL-1.12-https-bugs.webkit.org-sh.patch \
"
SRC_URI[md5sum] = "90fa970ebf8646319d292c2bb5bff5db"
SRC_URI[sha256sum] = "d8d21e27f4a21cd77c41914548c184ddb98693ba23851aa66c8e51c0be4b90b7"

branch_name: refs/heads/fido


text:
DEFAULT_PREFERENCE = "-1"
SECTION = "base"
PR = "r1"
HOMEPAGE = "http://www.freedesktop.org/Software/dbus"
DESCRIPTION = "message bus system for applications to talk to one another"
LICENSE = "GPL"
DEPENDS = "expat glib-2.0 virtual/libintl"
PROVIDES = "dbus-glib"

SRC_URI = "http://repository.maemo.org/pool/maemo/ossw/source/d/${PN}/${PN}_${PV}.tar.gz \
	   file://cross.patch \
	   file://tmpdir.patch \
	   file://gettext.patch \
           file://0.23.1.diff \
           file://dbus-monitor.patch \
           file://dbussend.patch;striplevel=0 \
           file://spawn-priority.diff \
           file://config.diff;striplevel=0 \
           file://dbus-quiesce-startup-errors.patch \
           file://tools.diff;striplevel=0 \
	   file://dbus-1.init"

inherit autotools pkgconfig update-rc.d gettext

S = "${WORKDIR}/dbus-0.23.1"

INITSCRIPT_NAME = "dbus-1"
INITSCRIPT_PARAMS = "defaults"

CONFFILES_${PN} = "${sysconfdir}/dbus-1/system.conf ${sysconfdir}/dbus-1/session.conf"

FILES_${PN} = "${bindir}/dbus-daemon-1 ${bindir}/dbus-launch ${bindir}/dbus-cleanup-sockets ${bindir}/dbus-send ${bindir}/dbus-monitor ${sysconfdir} ${datadir}/dbus-1/services ${libdir}/lib*.so.*"
FILES_${PN}-dev += "${libdir}/dbus-1.0/include ${bindir}/dbus-glib-tool"

pkg_postinst_dbus() {
#!/bin/sh

# can't do adduser stuff offline
if [ "x$D" != "x" ]; then
  exit 1
fi

MESSAGEUSER=messagebus
MESSAGEHOME=/var/run/dbus

mkdir -p $MESSAGEHOME || true
chgrp "$MESSAGEUSER" "$MESSAGEHOME" 2>/dev/null || addgroup "$MESSAGEUSER"
chown "$MESSAGEUSER"."$MESSAGEUSER" "$MESSAGEHOME" 2>/dev/null || adduser --system --home "$MESSAGEHOME" --no-create-home --disabled-password --ingroup "$MESSAGEUSER" "$MESSAGEUSER"
}

EXTRA_OECONF = "--disable-qt --disable-gtk --disable-tests \
		--disable-checks --disable-xml-docs --disable-doxygen-docs \
		--with-xml=expat --without-x"

do_stage () {
	oe_libinstall -so -C dbus libdbus-1 ${STAGING_LIBDIR}
	oe_libinstall -so -C glib libdbus-glib-1 ${STAGING_LIBDIR}

	autotools_stage_includes

	mkdir -p ${STAGING_LIBDIR}/dbus-1.0/include/dbus/
	install -m 0644 dbus/dbus-arch-deps.h ${STAGING_LIBDIR}/dbus-1.0/include/dbus/
}

do_install_append () {
	install -d ${D}${sysconfdir}/init.d
	install -m 0755 ${WORKDIR}/dbus-1.init ${D}${sysconfdir}/init.d/dbus-1
}

python populate_packages_prepend () {
	if (bb.data.getVar('DEBIAN_NAMES', d, 1)):
		bb.data.setVar('PKG_dbus', 'dbus-1', d)
}

SRC_URI[md5sum] = "151c42600940d5fab7e8c6ab9f07f5fb"
SRC_URI[sha256sum] = "dc8022037b58a7240f5c70072cd8c14038b8d47dd3c6c9b5b5c2eb9f917ff076"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
#include "catch.hpp"
#include "transptableentry.h"

TEST_CASE("Transposition table entries work as expected") {
  Board board;

  SECTION("Transposition table entries store depth, score and flags") {
    board.setToStartPos();

    Move move(a2, a3, PAWN);
    TranspTableEntry ttEntry(1, 2, TranspTableEntry::EXACT, move);

    REQUIRE(ttEntry.getScore() == 1);
    REQUIRE(ttEntry.getDepth() == 2);
    REQUIRE(ttEntry.getFlag() == TranspTableEntry::EXACT);
    REQUIRE(ttEntry.getBestMove() == move);
  }
}

repository: GunshipPenguin/shallow-blue

repo_name: GunshipPenguin/shallow-blue

extension: cc


text:
SUMMARY = "C library for lightweight websocket clients and servers"
DESCRIPTION = "Libwebsockets is a lightweight pure C library built \
               to use minimal CPU and memory resources, and provide \
               fast throughput in both directions."
HOMEPAGE = "http://libwebsockets.org"

LICENSE = "LGPL-2.1"
LIC_FILES_CHKSUM = "file://${S}/LICENSE;md5=041a1dec49ec8a22e7f101350fd19550"

SRC_URI = "http://git.libwebsockets.org/cgi-bin/cgit/${PN}/snapshot/${PN}-${PV}-chrome32-firefox24.tar.gz"
SRC_URI[md5sum] = "b39c559c62192128bf4c3d8eedd992a8"
SRC_URI[sha256sum] = "8d94a75ed1b69571d251e79512a424de51a411bafd57a66ccbe690b560a41359"

S = "${WORKDIR}/${PN}-${PV}-chrome32-firefox24"

DEPENDS += "openssl"

inherit cmake

do_configure() {
  # This line allows to tell openssl where its confog files are located
  export OPENSSL_CONF=${TMPDIR}/sysroots/x86_64-linux/usr/lib/ssl/openssl.cnf
  cmake_do_configure
}

PACKAGES += "${PN}-tests"

FILES_${PN}-tests += "${bindir}/libwebsockets-test* \
                      ${datadir}/libwebsockets-test-server/* \
                     "

repository: TeamElevate/edison

repo_name: TeamElevate/edison


text:
package actor_test

import (
	"fmt"
	"log"
	"sync"

	"github.com/AsynkronIT/protoactor-go/actor"
)

// Spawn creates instances of actors, similar to 'new' or 'make' but for actors.
func ExampleSpawnNamed() {
	var wg sync.WaitGroup
	wg.Add(1)

	// create root context
	context := actor.EmptyRootContext

	// define the actor props
	// props define the creation process of an actor
	props := actor.PropsFromFunc(func(ctx actor.Context) {
		// check if the message is a *actor.Started message
		// this is the first message all actors get
		// actor.Started is received async and can be used
		// to initialize your actors initial state
		if _, ok := ctx.Message().(*actor.Started); ok {
			fmt.Println("hello world")
			wg.Done()
		}
	})

	// spawn the actor based on the props
	_, err := context.SpawnNamed(props, "my-actor")
	if err != nil {
		log.Fatal("The actor name is already in use")
	}
	wg.Wait()
	// Output: hello world
}

repository: dennis-tra/protoactor-go

repo_name: dennis-tra/protoactor-go

branch_name: refs/heads/dev

gha_language: Go


text:
package bootstrap

import (
	"net"
	"os"
	"time"

	"github.com/pkg/errors"

	"github.com/kumahq/kuma/pkg/config"
	config_types "github.com/kumahq/kuma/pkg/config/types"
)

var _ config.Config = &BootstrapServerConfig{}

type BootstrapServerConfig struct {
	// Parameters of bootstrap configuration
	Params *BootstrapParamsConfig `json:"params"`
}

func (b *BootstrapServerConfig) Sanitize() {
	b.Params.Sanitize()
}

func (b *BootstrapServerConfig) Validate() error {
	if err := b.Params.Validate(); err != nil {
		return errors.Wrap(err, "Params validation failed")
	}
	return nil
}

func DefaultBootstrapServerConfig() *BootstrapServerConfig {
	return &BootstrapServerConfig{
		Params: DefaultBootstrapParamsConfig(),
	}
}

var _ config.Config = &BootstrapParamsConfig{}

type BootstrapParamsConfig struct {
	// Address of Envoy Admin
	AdminAddress string `json:"adminAddress" envconfig:"kuma_bootstrap_server_params_admin_address"`
	// Port of Envoy Admin
	AdminPort uint32 `json:"adminPort" envconfig:"kuma_bootstrap_server_params_admin_port"`
	// Path to access log file of Envoy Admin
	AdminAccessLogPath string `json:"adminAccessLogPath" envconfig:"kuma_bootstrap_server_params_admin_access_log_path"`
	// Host of XDS Server. By default it is the same host as the one used by kuma-dp to connect to the control plane
	XdsHost string `json:"xdsHost" envconfig:"kuma_bootstrap_server_params_xds_host"`
	// Port of XDS Server. By default it is autoconfigured from KUMA_XDS_SERVER_GRPC_PORT
	XdsPort uint32 `json:"xdsPort" envconfig:"kuma_bootstrap_server_params_xds_port"`
	// Connection timeout to the XDS Server
	XdsConnectTimeout config_types.Duration `json:"xdsConnectTimeout" envconfig:"kuma_bootstrap_server_params_xds_connect_timeout"`
}

func (b *BootstrapParamsConfig) Sanitize() {
}

func (b *BootstrapParamsConfig) Validate() error {
	if b.AdminAddress == "" {
		return errors.New("AdminAddress cannot be empty")
	}
	if net.ParseIP(b.AdminAddress) == nil {
		return errors.New("AdminAddress should be a valid IP address")
	}
	if b.AdminPort > 65535 {
		return errors.New("AdminPort must be in the range [0, 65535]")
	}
	if b.AdminAccessLogPath == "" {
		return errors.New("AdminAccessLogPath cannot be empty")
	}
	if b.XdsPort > 65535 {
		return errors.New("AdminPort must be in the range [0, 65535]")
	}
	if b.XdsConnectTimeout.Duration < 0 {
		return errors.New("XdsConnectTimeout cannot be negative")
	}
	return nil
}

func DefaultBootstrapParamsConfig() *BootstrapParamsConfig {
	return &BootstrapParamsConfig{
		AdminAddress:       "127.0.0.1", // by default, Envoy Admin interface should listen on loopback address
		AdminPort:          9901,
		AdminAccessLogPath: os.DevNull,
		XdsHost:            "", // by default, it is the same host as the one used by kuma-dp to connect to the control plane
		XdsPort:            0,  // by default, it is autoconfigured from KUMA_XDS_SERVER_GRPC_PORT
		XdsConnectTimeout:  config_types.Duration{Duration: 1 * time.Second},
	}
}

repository: kumahq/kuma

repo_name: kumahq/kuma