text:
#include "cbase.h"
#include "nb_select_marine_panel.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/Panel.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/ImagePanel.h"
#include "nb_skill_panel.h"
#include "vgui_controls/Label.h"
#include "asw_marine_profile.h"
#include "nb_select_marine_entry.h"
#include "asw_briefing.h"
#include "vgui_bitmapbutton.h"
#include "nb_main_panel.h"
#include "nb_header_footer.h"
#include "nb_button.h"
#include <vgui/ILocalize.h>
#include "asw_gamerules.h"
#include "c_asw_campaign_save.h"
#include "c_asw_game_resource.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

CNB_Select_Marine_Panel::CNB_Select_Marine_Panel( vgui::Panel *parent, const char *name ) : BaseClass( parent, name )
{
	// == MANAGED_MEMBER_CREATION_START: Do not edit by hand ==
	m_pHeaderFooter = new CNB_Header_Footer( this, "HeaderFooter" );
	m_pTitle = new vgui::Label( this, "Title", "" );
	m_pMarineNameLabel = new vgui::Label( this, "MarineNameLabel", "" );
	m_pBioTitle = new vgui::Label( this, "BioTitle", "" );
	m_pBioLabel = new vgui::Label( this, "BioLabel", "" );
	m_pSkillPanel0 = new CNB_Skill_Panel( this, "SkillPanel0" );
	m_pSkillPanel1 = new CNB_Skill_Panel( this, "SkillPanel1" );
	m_pSkillPanel2 = new CNB_Skill_Panel( this, "SkillPanel2" );
	m_pSkillPanel3 = new CNB_Skill_Panel( this, "SkillPanel3" );
	m_pSkillPanel4 = new CNB_Skill_Panel( this, "SkillPanel4" );
	m_pPortraitsBackground = new vgui::ImagePanel( this, "PortraitsBackground" );
	m_pPortraitsLowerBackground = new vgui::ImagePanel( this, "PortraitsLowerBackground" );
	// == MANAGED_MEMBER_CREATION_END ==
	m_pAcceptButton = new CNB_Button( this, "AcceptButton", "", this, "AcceptButton" );
	m_pBackButton = new CNB_Button( this, "BackButton", "", this, "BackButton" );
	m_pSkillPointsLabel = new vgui::Label( this, "SkillPointsLabel", "" );
	m_pSkillPointsLabel->SetVisible( false );

	m_pHeaderFooter->SetHeaderEnabled( false );
	m_pHeaderFooter->SetBackgroundStyle( NB_BACKGROUND_BLUE );

	m_nHighlightedEntry = -1;
	m_nInitialProfileIndex = -1;
	m_nPreferredLobbySlot = -1;
}

CNB_Select_Marine_Panel::~CNB_Select_Marine_Panel()
{

}

void CNB_Select_Marine_Panel::InitMarineList()
{
	// create entry panels for our horizontal list
	if ( !MarineProfileList() )
	{
		Warning( "Failed to get marine profile list\n" );
		MarkForDeletion();
		return;
	}

	int nProfiles = MarineProfileList()->m_NumProfiles;
	for ( int i = 0; i < nProfiles; i++ )
	{
		CNB_Select_Marine_Entry *pEntry = new CNB_Select_Marine_Entry( this, "Entry" );

		//Assert( NELEMS( s_nProfileOrder ) == nProfiles );		// if this assert fails, then s_nProfileOrder needs to be updated to match the new profile list
		int nProfileIndex = i;//s_nProfileOrder[ i ];
		vgui::PHandle handle;
		handle = pEntry;
		pEntry->SetProfileIndex( nProfileIndex );
		pEntry->m_nPreferredLobbySlot = m_nPreferredLobbySlot;
		pEntry->InvalidateLayout( true, true );
		m_Entries.AddToTail( handle );
	}
	m_nHighlightedEntry = m_nInitialProfileIndex;
	if ( m_nHighlightedEntry == -1 )
		m_nHighlightedEntry = 0;
	InvalidateLayout( true, true );
}

void CNB_Select_Marine_Panel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	LoadControlSettings( "resource/ui/nb_select_marine_panel.res" );

	//m_pHorizList->m_pBackgroundImage->SetImage( "briefing/select_marine_list_bg" );
	//m_pHorizList->m_pForegroundImage->SetImage( "briefing/horiz_list_fg" );
}

void CNB_Select_Marine_Panel::PerformLayout()
{
	BaseClass::PerformLayout();

	int titlex, titley, titlew, titleh;
	m_pTitle->GetBounds( titlex, titley, titlew, titleh );

	// stack up children side by side
	int curx = titlex;
	int cury = YRES( 25 ); //titley + titleh + YRES( 6 );
	int padding = 0;
	int maxh = 0;
	for ( int i = 0; i < m_Entries.Count(); i++ )
	{
		m_Entries[i]->SetPos( curx, cury );
		m_Entries[i]->InvalidateLayout( true );

		int w, h;
		m_Entries[i]->GetSize( w, h );
		maxh = MAX( maxh, h );

		curx += w + padding;
		if ( i == 3 )
		{
			curx = titlex;
			cury += YRES( 131 ); //h;// + YRES( 6 );
		}
	}
	//SetSize( curx - padding, maxh );		// stretch container to fit all children

	// set our height from the tallest entry
	//int sw, sh;
	//GetSize( sw, sh );
	//SetSize( sw, maxh );
	//m_pBackgroundImage->SetSize( sw, maxh );
	//m_pForegroundImage->SetSize( sw, maxh );
}

void CNB_Select_Marine_Panel::OnThink()
{
	BaseClass::OnThink();

	for ( int i = 0; i < m_Entries.Count(); i++ )
	{
		if ( m_Entries[i]->IsCursorOver() )
		{
			vgui::Panel *pPanel = m_Entries[i];
			CNB_Select_Marine_Entry *pCursorOver = dynamic_cast<CNB_Select_Marine_Entry*>( pPanel );
			if ( pCursorOver && pCursorOver->m_pPortraitImage->IsCursorOver() )
			{
				SetHighlight( i );
				break;
			}
		}
	}

	bool bShowSpareSkillPoints = false;
	CNB_Select_Marine_Entry *pHighlighted = dynamic_cast<CNB_Select_Marine_Entry*>( GetHighlightedEntry() );
	if ( pHighlighted )
	{
		int nProfileIndex = pHighlighted->GetProfileIndex();
		CASW_Marine_Profile *pProfile = Briefing()->GetMarineProfileByProfileIndex( nProfileIndex );
		if ( pProfile )
		{
			m_pMarineNameLabel->SetText( pProfile->GetShortName() );
			m_pBioLabel->SetText( pProfile->m_Bio );
			m_pSkillPanel0->SetSkillDetails( nProfileIndex, 0, Briefing()->GetProfileSkillPoints( nProfileIndex, 0 ) );
			m_pSkillPanel1->SetSkillDetails( nProfileIndex, 1, Briefing()->GetProfileSkillPoints( nProfileIndex, 1 ) );
			m_pSkillPanel2->SetSkillDetails( nProfileIndex, 2, Briefing()->GetProfileSkillPoints( nProfileIndex, 2 ) );
			m_pSkillPanel3->SetSkillDetails( nProfileIndex, 3, Briefing()->GetProfileSkillPoints( nProfileIndex, 3 ) );
			m_pSkillPanel4->SetSkillDetails( nProfileIndex, 4, Briefing()->GetProfileSkillPoints( nProfileIndex, 4 ) );

			if ( ASWGameRules() && ASWGameRules()->IsCampaignGame() && ASWGameRules()->GetCampaignSave() && !ASWGameRules()->GetCampaignSave()->UsingFixedSkillPoints() )
			{
				int nSkillPoints = Briefing()->GetProfileSkillPoints( nProfileIndex, ASW_SKILL_SLOT_SPARE );
				if ( nSkillPoints > 0 )
				{
					wchar_t buffer[128];
					char sparebuffer[8];
					Q_snprintf(sparebuffer, sizeof(sparebuffer), "%d", nSkillPoints);
					wchar_t wsparebuffer[8];
					g_pVGuiLocalize->ConvertANSIToUnicode(sparebuffer, wsparebuffer, sizeof( wsparebuffer ));

					g_pVGuiLocalize->ConstructString( buffer, sizeof(buffer),
						g_pVGuiLocalize->Find("#asw_unspent_points"), 1,
						wsparebuffer);

					m_pSkillPointsLabel->SetText( buffer );
					bShowSpareSkillPoints = true;
				}
			}
		}

		m_pAcceptButton->SetEnabled( !Briefing()->IsProfileSelectedBySomeoneElse( nProfileIndex ) );
	}
	else
	{

	}

	m_pSkillPointsLabel->SetVisible( bShowSpareSkillPoints );
}

vgui::Panel* CNB_Select_Marine_Panel::GetHighlightedEntry()
{
	if ( m_nHighlightedEntry < 0 || m_nHighlightedEntry >= m_Entries.Count() )
		return NULL;

	return m_Entries[ m_nHighlightedEntry ].Get();
}

void CNB_Select_Marine_Panel::OnCommand( const char *command )
{
	if ( !Q_stricmp( command, "BackButton" ) )
	{
		Briefing()->SetChangingWeaponSlot( 0 );
		MarkForDeletion();

		CLocalPlayerFilter filter;
		C_BaseEntity::EmitSound( filter, -1, "ASWComputer.MenuBack" );

		return;
	}
	else if ( !Q_stricmp( command, "AcceptButton" ) )
	{
		CNB_Select_Marine_Entry *pHighlighted = dynamic_cast<CNB_Select_Marine_Entry*>( GetHighlightedEntry() );
		if ( pHighlighted )
		{
			int nProfileIndex = pHighlighted->GetProfileIndex();
			if ( !Briefing()->IsProfileSelectedBySomeoneElse( nProfileIndex ) )
			{
				Briefing()->SelectMarine( 0, nProfileIndex, m_nPreferredLobbySlot );

				// is this the first marine we've selected?
				if ( Briefing()->IsOfflineGame() && ASWGameResource() && ASWGameResource()->GetNumMarines( NULL ) <= 0 )
				{
					//Briefing()->AutoSelectFullSquadForSingleplayer( nProfileIndex );
				}

				bool bHasPointsToSpend = Briefing()->IsCampaignGame() && !Briefing()->UsingFixedSkillPoints() && ( Briefing()->GetProfileSkillPoints( nProfileIndex, ASW_SKILL_SLOT_SPARE ) > 0 );

				if ( bHasPointsToSpend )
				{
					CNB_Main_Panel *pPanel = dynamic_cast<CNB_Main_Panel*>( GetParent() );
					if ( pPanel )
					{
						pPanel->SpendSkillPointsOnMarine( nProfileIndex );
					}
				}
				else
				{
					MarkForDeletion();
					Briefing()->SetChangingWeaponSlot( 0 );
				}

				CASW_Marine_Profile* pProfile = Briefing()->GetMarineProfileByProfileIndex( nProfileIndex );
				if ( pProfile )
				{
					engine->ClientCmd_Unrestricted(VarArgs("exec configloader/chars/%s\n", pProfile->m_PortraitName));
					switch (pProfile->GetMarineClass())
					{
					case MARINE_CLASS_NCO:
						engine->ClientCmd_Unrestricted("exec configloader/chars/Officer\n");
						break;
					case MARINE_CLASS_SPECIAL_WEAPONS:
						engine->ClientCmd_Unrestricted("exec configloader/chars/SpecialWeapons\n");
						break;
					case MARINE_CLASS_MEDIC:
						engine->ClientCmd_Unrestricted("exec configloader/chars/Medic\n");
						break;
					case MARINE_CLASS_TECH:
						engine->ClientCmd_Unrestricted("exec configloader/chars/Tech\n");
						break;
					default:
						Assert(0);
					}
				}
			}
			else
			{
				CLocalPlayerFilter filter;
				C_BaseEntity::EmitSound( filter, -1, "ASWComputer.TimeOut" );
			}
		}
		return;
	}
	BaseClass::OnCommand( command );
}

void CNB_Select_Marine_Panel::SetHighlight( int nEntryIndex )
{
	if ( nEntryIndex < 0 || nEntryIndex >= m_Entries.Count() )
		return;

	m_nHighlightedEntry = nEntryIndex;
}

extension: cpp


text:
// for go1.16

package forceexport

import (
	"fmt"
	"reflect"
	"runtime"
	"unsafe"
)

// GetFunc gets the function defined by the given fully-qualified name. The
// outFuncPtr parameter should be a pointer to a function with the appropriate
// type (e.g. the address of a local variable), and is set to a new function
// value that calls the specified function. If the specified function does not
// exist, outFuncPtr is not set and an error is returned.
func GetFunc(outFuncPtr interface{}, name string) error {
	codePtr, err := FindFuncWithName(name)
	if err != nil {
		return err
	}
	CreateFuncForCodePtr(outFuncPtr, codePtr)
	return nil
}

// Convenience struct for modifying the underlying code pointer of a function
// value. The actual struct has other values, but always starts with a code
// pointer.
type Func struct {
	codePtr uintptr
}

// CreateFuncForCodePtr is given a code pointer and creates a function value
// that uses that pointer. The outFun argument should be a pointer to a function
// of the proper type (e.g. the address of a local variable), and will be set to
// the result function value.
func CreateFuncForCodePtr(outFuncPtr interface{}, codePtr uintptr) {
	outFuncVal := reflect.ValueOf(outFuncPtr).Elem()
	// Use reflect.MakeFunc to create a well-formed function value that's
	// guaranteed to be of the right type and guaranteed to be on the heap
	// (so that we can modify it). We give a nil delegate function because
	// it will never actually be called.
	newFuncVal := reflect.MakeFunc(outFuncVal.Type(), nil)
	// Use reflection on the reflect.Value (yep!) to grab the underling
	// function value pointer. Trying to call newFuncVal.Pointer() wouldn't
	// work because it gives the code pointer rather than the function value
	// pointer. The function value is a struct that starts with its code
	// pointer, so we can swap out the code pointer with our desired value.
	funcValuePtr := reflect.ValueOf(newFuncVal).FieldByName("ptr").Pointer()
	funcPtr := (*Func)(unsafe.Pointer(funcValuePtr))
	funcPtr.codePtr = codePtr
	outFuncVal.Set(newFuncVal)
}

// FindFuncWithName searches through the moduledata table created by the linker
// and returns the function's code pointer. If the function was not found, it
// returns an error. Since the data structures here are not exported, we copy
// them below (and they need to stay in sync or else things will fail
// catastrophically).
func FindFuncWithName(name string) (uintptr, error) {
	for moduleData := &Firstmoduledata; moduleData != nil; moduleData = moduleData.next {
		for _, ftab := range moduleData.ftab {
			if int(ftab.funcoff) >= len(moduleData.pclntable) {
				continue
			}
			f := (*runtime.Func)(unsafe.Pointer(&moduleData.pclntable[ftab.funcoff]))
			funcName, err := getFuncName(f)
			if err == nil && funcName == name {
				return f.Entry(), nil
			}
		}
	}
	return 0, fmt.Errorf("Invalid function name: %s", name)
}

func GetAllFuncName() (names []string) {
	for moduleData := &Firstmoduledata; moduleData != nil; moduleData = moduleData.next {
		for _, ftab := range moduleData.ftab {
			if int(ftab.funcoff) >= len(moduleData.pclntable) {
				continue
			}
			f := (*runtime.Func)(unsafe.Pointer(&moduleData.pclntable[ftab.funcoff]))
			funcName, err := getFuncName(f)
			if err == nil {
				names = append(names, funcName)
			}
		}
	}
	return
}

// Everything below is taken from the runtime package, and must stay in sync
// with it.

//go:linkname Firstmoduledata runtime.firstmoduledata
var Firstmoduledata Moduledata

type Moduledata struct {
	pcHeader     *pcHeader
	funcnametab  []byte
	cutab        []uint32
	filetab      []byte
	pctab        []byte
	pclntable    []byte
	ftab         []functab
	findfunctab  uintptr
	minpc, maxpc uintptr

	text, etext           uintptr
	noptrdata, enoptrdata uintptr
	data, edata           uintptr
	bss, ebss             uintptr
	noptrbss, enoptrbss   uintptr
	end, gcdata, gcbss    uintptr
	types, etypes         uintptr

	textsectmap []textsect
	typelinks   []int32 // offsets from types
	itablinks   []*itab

	ptab []ptabEntry

	pluginpath string
	pkghashes  []modulehash

	modulename   string
	modulehashes []modulehash

	hasmain uint8 // 1 if module contains the main function, 0 otherwise

	gcdatamask, gcbssmask bitvector

	typemap map[typeOff]*_type // offset to *_rtype in previous module

	bad bool // module failed to load and should be ignored

	next *Moduledata
}

// pcHeader holds data used by the pclntab lookups.
type pcHeader struct {
	magic          uint32  // 0xFFFFFFFA
	pad1, pad2     uint8   // 0,0
	minLC          uint8   // min instruction size
	ptrSize        uint8   // size of a ptr in bytes
	nfunc          int     // number of functions in the module
	nfiles         uint    // number of entries in the file tab.
	funcnameOffset uintptr // offset to the funcnametab variable from pcHeader
	cuOffset       uintptr // offset to the cutab variable from pcHeader
	filetabOffset  uintptr // offset to the filetab variable from pcHeader
	pctabOffset    uintptr // offset to the pctab varible from pcHeader
	pclnOffset     uintptr // offset to the pclntab variable from pcHeader
}

type functab struct {
	entry   uintptr
	funcoff uintptr
}

type textsect struct {
	vaddr    uintptr // prelinked section vaddr
	length   uintptr // section length
	baseaddr uintptr // relocated section address
}

type itab struct {
	inter *interfacetype
	_type *_type
	hash  uint32 // copy of _type.hash. Used for type switches.
	_     [4]byte
	fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}

type interfacetype struct {
	typ     _type
	pkgpath name
	mhdr    []imethod
}

type _type struct {
	size       uintptr
	ptrdata    uintptr // size of memory prefix holding all pointers
	hash       uint32
	tflag      tflag
	align      uint8
	fieldAlign uint8
	kind       uint8
	// function for comparing objects of this type
	// (ptr to object A, ptr to object B) -> ==?
	equal func(unsafe.Pointer, unsafe.Pointer) bool
	// gcdata stores the GC type data for the garbage collector.
	// If the KindGCProg bit is set in kind, gcdata is a GC program.
	// Otherwise it is a ptrmask bitmap. See mbitmap.go for details.
	gcdata    *byte
	str       nameOff
	ptrToThis typeOff
}

type name struct {
	bytes *byte
}

type imethod struct {
	name nameOff
	ityp typeOff
}

type tflag uint8
type nameOff int32
type typeOff int32

type ptabEntry struct {
	name nameOff
	typ  typeOff
}

type modulehash struct {
	modulename   string
	linktimehash string
	runtimehash  *string
}

type bitvector struct {
	n        int32 // # of bits
	bytedata *uint8
}

func getFuncName(f *runtime.Func) (funcName string, err error) {
	// f.Name() may panic because runtime.findmoduledatap may return nil
	defer func() {
		if r := recover(); r != nil {
			switch e := r.(type) {
			case error:
				err = e
			default:
				panic("unexpect")
			}
		}
	}()
	funcName = f.Name()
	return funcName, err
}

license: MIT

repository: AlaxLee/go-forceexport

license_type: permissive

repo_name: AlaxLee/go-forceexport

branch_name: refs/heads/master

gha_license_id: MIT

extension: go


text:
package config

import (
	"encoding/json"
	"fmt"
	"gitdeployer/helpers"
	"io/ioutil"
	"time"
)

type Commit struct {
	DeployDate int64
	CommitHash string
}

func AddCommit(hash string) *Commit {
	result := CreateCommit(hash)

	commits := getCommits()
	commits = append(commits, result)
	saveCommits(commits)

	return result
}

func CreateCommit(hash string) *Commit {
	result := new(Commit)

	result.DeployDate = time.Now().Unix()
	result.CommitHash = hash

	return result
}

func IsCommitDeployed(hash string) bool {
	result := false

	commits := getCommits()
	for _, commit := range commits {
		if commit.CommitHash == hash {
			result = true
		}
	}

	return result
}

func saveCommits(commits []*Commit) bool {
	result := false

	if ts, err := json.Marshal(commits); err == nil {
		ioutil.WriteFile(CommitFilePath, ts, 0777)
		result = true
	}

	return result
}

func getCommits() []*Commit {
	var result []*Commit

	if helpers.IsPathExists(CommitFilePath) {
		if tokensStr, err := ioutil.ReadFile(CommitFilePath); err == nil {
			if err := json.Unmarshal(tokensStr, &result); err != nil {
				fmt.Println(err)
			}
		}
	}

	return result
}

repository: SergioMadness/gitdeployer

repo_name: SergioMadness/gitdeployer

branch_name: refs/heads/dev

gha_language: Go


text:
@TECHREPORT{denardi2013rn,
  AUTHOR =        {R. De Nardi},
  TITLE =         {The QRSim Quadrotor Simulator},
  NUMBER =        {RN/13/08},
  INSTITUTION =   {Department of Computer Science, University College London},
  ADDRESS =       {Gower Street, London UK},
  MONTH =         {March},
  YEAR  =         {2013},
}

@online{qrsim_github,
  author = {University College London},
  title = {QrSim: Multiplatform quadrotor simulator },
  year = {2014},
  url = {https://github.com/UCL-CompLACS/qrsim},
  urldate = {2018-06-02},
}

@online{gps_accuracy,
  author = {GPS.gov},
  title = {GPS accuracy},
  year = {2017},
  url = {https://www.gps.gov/systems/gps/performance/accuracy/},
  urldate = {2018-06-15},
}

@online{mydroneservices,
  author = {My Drone Services },
  title = {What Really Happened with Drones in 2017},
  year = {2018},
  url = {https://mydroneservices.com/what-really-happened-with-drones-in-2017/},
  urldate = {2018-06-12}
}

@article{NASA_UAV_mission_parameters,
  title={UAV Over-the-Horizon Disaster Management Demonstration Projects},
  author={Steve Wegener},
  year={2000},
  publisher={NASA Ames Research Center},
  url = {https://geo.arc.nasa.gov/sge/UAVFiRE/whitepaper.pdf}
  urldate = {2018-06-14}
}

@article{rothery1992car,
  title={Car following models},
  author={Rothery, Richard W},
  journal={Trac Flow Theory},
  year={1992},
  publisher={Citeseer}
}

@online{qrsim_github_manual,
  author = {University College London},
  title = {QrSim: Multiplatform quadrotor simulator Manual},
  year = 2014,
  url = {https://github.com/UCL-CompLACS/qrsim/raw/master/doc/manual.pdf},
  urldate = {2018-06-02},
}

@online{fspl_formulae,
  author = {Adrio Communications Ltd},
  title = {Free Space Path Loss: Details, Formula, Calculator},
  url = {http://www.radio-electronics.com/info/propagation/path-loss/free-space-formula-equation.php},
  urldate = {2018-06-02},
}

@online{wilink,
  author = {Texas Instruments},
  title = {WL18xxMOD WiLink \texttrademark 8 Single-Band Combo Module – Wi-Fi \textregistered, Bluetooth \textregistered, and Bluetooth \textregistered Low Energy (LE)},
  url = {http://www.ti.com/lit/ds/symlink/wl1805mod.pdf},
  urldate = {2018-06-02},
}

@article{OUBBATI201729,
title = "A survey on position-based routing protocols for Flying Ad hoc Networks (FANETs)",
journal = "Vehicular Communications",
volume = "10",
pages = "29 - 56",
year = "2017",
issn = "2214-2096",
doi = "https://doi.org/10.1016/j.vehcom.2017.10.003",
url = "http://www.sciencedirect.com/science/article/pii/S2214209617300529",
author = "Omar Sami Oubbati and Abderrahmane Lakas and Fen Zhou and Mesut Güneş and Mohamed Bachir Yagoubi",
keywords = "Flying Ad hoc Networks (FANETs), Vehicular Ad hoc Networks (VANET), Routing protocols, Unmanned Aerial Vehicles (UAVs), Geographical position"
}

@article{BEKMEZCI20131254,
title = "Flying Ad-Hoc Networks (FANETs): A survey",
journal = "Ad Hoc Networks",
volume = "11",
number = "3",
pages = "1254 - 1270",
year = "2013",
issn = "1570-8705",
doi = "https://doi.org/10.1016/j.adhoc.2012.12.004",
url = "http://www.sciencedirect.com/science/article/pii/S1570870512002193",
author = "İlker Bekmezci and Ozgur Koray Sahingoz and Şamil Temel",
keywords = "Ad-hoc networks, MANET, VANET, Multi-UAV"
}

@ARTICLE{6238283,
author={F. Cadger and K. Curran and J. Santos and S. Moffett},
journal={IEEE Communications Surveys Tutorials},
title={A Survey of Geographical Routing in Wireless Ad-Hoc Networks},
year={2013},
volume={15},
number={2},
pages={621-653},
keywords={mobile ad hoc networks;mobility management (mobile radio);quality of service;routing protocols;ubiquitous computing;QoS;contextawareness;geographic routing protocols;mobility management;mobility prediction;routing process;survey;topology-dependent routing paradigms;ubiquitous computing;wireless ad-hoc networks;Ad hoc networks;Geometric routing;Routing;Routing protocols;Wireless communication;Wireless networks;Wireless sensor networks;Geographic routing;geometric routing;location-aware routing;wireless networks},
doi={10.1109/SURV.2012.062612.00109},
ISSN={1553-877X},
month={Second},}

@article{Stojmenovic:2002:PRA:2288474.2290160,
 author = {Stojmenovic, I.},
 title = {Position-based Routing in Ad Hoc Networks},
 journal = {Comm. Mag.},
 issue_date = {July 2002},
 volume = {40},
 number = {7},
 month = jul,
 year = {2002},
 issn = {0163-6804},
 pages = {128--134},
 numpages = {7},
 url = {http://dx.doi.org/10.1109/MCOM.2002.1018018},
 doi = {10.1109/MCOM.2002.1018018},
 acmid = {2290160},
 publisher = {IEEE Press},
 address = {Piscataway, NJ, USA},
}

@ARTICLE{967595,
author={M. Mauve and J. Widmer and H. Hartenstein},
journal={IEEE Network},
title={A survey on position-based routing in mobile ad hoc networks},
year={2001},
volume={15},
number={6},
pages={30-39},
keywords={land mobile radio;network topology;packet radio networks;protocols;telecommunication network routing;ad hoc routing protocols;distance routing effect algorithm;location services;mobile ad hoc networks;network node;network topology;packet destination geographical location;position-based packet forwarding;position-based routing;Europe;Floods;Intelligent networks;Mobile ad hoc networks;National electric code;Network servers;Network topology;Proposals;Routing protocols;Taxonomy},
doi={10.1109/65.967595},
ISSN={0890-8044},
month={Nov},}

@inproceedings{Basagni:1998:DRE:288235.288254,
 author = {Basagni, Stefano and Chlamtac, Imrich and Syrotiuk, Violet R. and Woodward, Barry A.},
 title = {A Distance Routing Effect Algorithm for Mobility (DREAM)},
 booktitle = {Proceedings of the 4th Annual ACM/IEEE International Conference on Mobile Computing and Networking},
 series = {MobiCom '98},
 year = {1998},
 isbn = {1-58113-035-X},
 location = {Dallas, Texas, USA},
 pages = {76--84},
 numpages = {9},
 url = {http://doi.acm.org/10.1145/288235.288254},
 doi = {10.1145/288235.288254},
 acmid = {288254},
 publisher = {ACM},
 address = {New York, NY, USA},
}

@inproceedings{Li:2000:SLS:345910.345931,
 author = {Li, Jinyang and Jannotti, John and De Couto, Douglas S. J. and Karger, David R. and Morris, Robert},
 title = {A Scalable Location Service for Geographic Ad Hoc Routing},
 booktitle = {Proceedings of the 6th Annual International Conference on Mobile Computing and Networking},
 series = {MobiCom '00},
 year = {2000},
 isbn = {1-58113-197-6},
 location = {Boston, Massachusetts, USA},
 pages = {120--130},
 numpages = {11},
 url = {http://doi.acm.org/10.1145/345910.345931},
 doi = {10.1145/345910.345931},
 acmid = {345931},
 publisher = {ACM},
 address = {New York, NY, USA},
}

@ARTICLE{769770,
author={Z. J. Haas and B. Liang},
journal={IEEE/ACM Transactions on Networking},
title={Ad hoc mobility management with uniform quorum systems},
year={1999},
volume={7},
number={2},
pages={228-240},
keywords={land mobile radio;telecommunication network management;telecommunication network reliability;telecommunication traffic;ad hoc networks;average cost;balanced incomplete block designs;call arrival;call loss;database disconnections;design parameter;distributed HLR;distributed mobility management;dynamic HLR;flat network structure;home location register;location databases;location update;mobility patterns;network nodes;network partitioning;network traffic patterns;quorum intersection size;self-organizing virtual backbone;system reliability;uniform quorum systems;Ad hoc networks;Communication standards;Costs;Databases;Density functional theory;Information retrieval;Mobile radio mobility management;Spine;Steady-state;Telecommunication traffic},
doi={10.1109/90.769770},
ISSN={1063-6692},
month={Apr},}

@ARTICLE{4448977,
author={F. Kuhn and R. Wattenhofer and A. Zollinger},
journal={IEEE/ACM Transactions on Networking},
title={An Algorithmic Approach to Geographic Routing in Ad Hoc and Sensor Networks},
year={2008},
volume={16},
number={1},
pages={51-62},
keywords={ad hoc networks;computational complexity;graph theory;routing protocols;wireless sensor networks;geographic routing algorithm;greedy forwarding-face routing approach;lower bound graph;routing protocols;wireless ad hoc networks;wireless sensor networks;Algorithmic analysis;routing;stretch;wireless networks},
doi={10.1109/TNET.2007.900372},
ISSN={1063-6692},
month={Feb},}

@INPROCEEDINGS{4721268,
author={S. Liu and T. Fevens and A. E. Abdallah},
booktitle={2008 The 4th International Conference on Mobile Ad-hoc and Sensor Networks},
title={Hybrid Position-Based Routing Algorithms for 3D Mobile Ad Hoc Networks},
year={2008},
volume={},
number={},
pages={177-186},
keywords={ad hoc networks;graph theory;greedy algorithms;least squares approximations;mobile radio;telecommunication network routing;3D mobile ad hoc network;MANET;adaptive least-square projective algorithm;face routing algorithm;hybrid greedy-face-greedy routing;hybrid position-based routing algorithm;projection plane;shortest path length;Acoustic sensors;Ad hoc networks;Computer science;Mobile ad hoc networks;Mobile computing;Routing protocols;Sensor phenomena and characterization;Software algorithms;Software engineering;Wireless sensor networks;Mobile Ad Hoc Network;Routing Algorithm;Three Dimensions;Unit Ball Graph},
doi={10.1109/MSN.2008.43},
ISSN={},
month={Dec},}

@INPROCEEDINGS{4509730,
author={R. Flury and R. Wattenhofer},
booktitle={IEEE INFOCOM 2008 - The 27th Conference on Computer Communications},
title={Randomized 3D Geographic Routing},
year={2008},
volume={},
number={},
pages={},
keywords={ad hoc networks;greedy algorithms;telecommunication network routing;telecommunication network topology;3D network topologies;greedy-face-greedy approach;memoryless routing algorithms;randomized 3D geographic routing;wireless ad hoc networks;Ad hoc networks;Algorithm design and analysis;Communications Society;Computer networks;Hardware;IP networks;Laboratories;Mobile ad hoc networks;Peer to peer computing;Routing protocols},
doi={10.1109/INFOCOM.2008.135},
ISSN={0743-166X},
month={April},}

@Article{Durocher2010,
author="Durocher, Stephane
and Kirkpatrick, David
and Narayanan, Lata",
title="On routing with guaranteed delivery in three-dimensional ad hoc wireless networks",
journal="Wireless Networks",
year="2010",
month="Jan",
day="01",
volume="16",
number="1",
pages="227--235",
abstract="We study the problem of routing in three-dimensional ad hoc networks. We are interested in routing algorithms that guarantee delivery and are k-local, i.e., each intermediate node v's routing decision only depends on knowledge of the labels of the source and destination nodes, of the subgraph induced by nodes within distance k of v, and of the neighbour of v from which the message was received. We model a three-dimensional ad hoc network by a unit ball graph, where nodes are points in three-dimensional space, and for each node v, there is an edge between v and every node u contained in the unit-radius ball centred at v. The question of whether there is a simple local routing algorithm that guarantees delivery in unit ball graphs has been open for some time. In this paper, we answer this question in the negative: we show that for any fixed k, there can be no k-local routing algorithm that guarantees delivery on all unit ball graphs. This result is in contrast with the two-dimensional case, where 1-local routing algorithms that guarantee delivery are known. Specifically, we show that guaranteed delivery is possible if the nodes of the unit ball graph are contained in a slab of thickness                                                                           {\$}{\$}1/{\backslash}sqrt{\{}2{\}}.{\$}{\$}                 However, there is no k-local routing algorithm that guarantees delivery for the class of unit ball graphs contained in thicker slabs, i.e., slabs of thickness                                                                           {\$}{\$}1/{\backslash}sqrt{\{}2{\}} + {\backslash}epsilon{\$}{\$}                 for some                                                                           {\$}{\$} {\backslash}epsilon > 0.{\$}{\$}                 The algorithm for routing in thin slabs derives from a transformation of unit ball graphs contained in thin slabs into quasi unit disc graphs, which yields a 2-local routing algorithm. We also show several results that further elaborate on the relationship between these two classes of graphs.",
issn="1572-8196",
doi="10.1007/s11276-008-0126-1",
url="https://doi.org/10.1007/s11276-008-0126-1"
}

@ARTICLE{7437029,
author={H. Huang and H. Yin and Y. Luo and X. Zhang and G. Min and Q. Fan},
journal={IEEE Network},
title={Three-dimensional geographic routing in wireless mobile ad hoc and sensor networks},
year={2016},
volume={30},
number={2},
pages={82-90},
keywords={mobile ad hoc networks;routing protocols;wireless sensor networks;3D geographic routing;3D networks;3DGR protocols;geographic routing protocols;three-dimensional geographic routing;wireless mobile ad hoc networks;wireless sensor networks;Ad hoc networks;Geographic routing systems;Relays;Routing protocols;Three-dimensional displays;Wireless communication},
doi={10.1109/MNET.2016.7437029},
ISSN={0890-8044},
month={March},}

@INPROCEEDINGS{6133499,
author={T. Biswas and R. Dutta},
booktitle={2011 IEEE Global Telecommunications Conference - GLOBECOM 2011},
title={Spatially Diffuse Pathsets for Robust Routing in Ad Hoc Networks},
year={2011},
volume={},
number={},
pages={1-6},
keywords={ad hoc networks;telecommunication network reliability;telecommunication network routing;ad hoc wireless networks;diverse multiple paths;interfering transmissions;malicious jamming;multiple diverse paths;node mobility;ondemand routing;packet delivery ratio;periodic updates;petal routing;radio links;random uncertainty;single path;spatially diffuse pathsets;traffic overhead reduction;tunable parameters;Delay;Jamming;Network coding;Peer to peer computing;Reliability;Routing;Wireless networks},
doi={10.1109/GLOCOM.2011.6133499},
ISSN={1930-529X},
month={Dec},}

@INPROCEEDINGS{5735774,
author={Z. Wang and M. Hassan and T. Moors},
booktitle={IEEE Local Computer Network Conference},
title={A study of spatial packet loss correlation in 802.11 wireless networks},
year={2010},
volume={},
number={},
pages={568-575},
keywords={Gaussian distribution;correlation theory;entropy;radio broadcasting;wireless LAN;Gaussian cumulative distribution function;IEEE 802.11 wireless networks;broadcast communications;entropy correlation coefficient;information theory;receivers;signal strength;spatial packet loss correlation;Correlation;Entropy;IEEE 802.11 Standards;Loss measurement;Propagation losses;Receivers},
doi={10.1109/LCN.2010.5735774},
ISSN={0742-1303},
month={Oct},}

@INPROCEEDINGS{1378257,
author={R. Ramaswamy and Ning Weng and T. Wolf},
booktitle={Global Telecommunications Conference, 2004. GLOBECOM '04. IEEE},
title={Characterizing network processing delay},
year={2004},
volume={3},
number={},
pages={1629-1634 Vol.3},
keywords={Internet;computational complexity;delays;packet switching;Internet;communication infrastructure;computer networks;content adaptation;encryption;firewalling;forwarding;long-distance propagation delay;network processing delay;packet classification;packet processing cost;payload modifications;Computer networks;Costs;Cryptography;Delay effects;IP networks;Network address translation;Payloads;Propagation delay;Virtual private networks;Wire},
doi={10.1109/GLOCOM.2004.1378257},
ISSN={},
month={Nov},}

@inproceedings{Ko:1998:LRM:288235.288252,
 author = {Ko, Young-Bae and Vaidya, Nitin H.},
 title = {Location-aided Routing (LAR) in Mobile Ad Hoc Networks},
 booktitle = {Proceedings of the 4th Annual ACM/IEEE International Conference on Mobile Computing and Networking},
 series = {MobiCom '98},
 year = {1998},
 isbn = {1-58113-035-X},
 location = {Dallas, Texas, USA},
 pages = {66--75},
 numpages = {10},
 url = {http://doi.acm.org/10.1145/288235.288252},
 doi = {10.1145/288235.288252},
 acmid = {288252},
 publisher = {ACM},
 address = {New York, NY, USA},
}

@INPROCEEDINGS{8080382,
author={A. Arputha Babu John and R. Dutta},
booktitle={2017 IEEE 38th Sarnoff Symposium},
title={Cooperative trajectory planning in an intercommunicating group of UAVs for convex plume wrapping},
year={2017},
volume={},
number={},
pages={1-6},
keywords={air pollution control;autonomous aerial vehicles;collision avoidance;contamination;environmental factors;mobile robots;path planning;position control;remotely operated vehicles;Plume wrapping problem;Unmanned Aerial Vehicle communication;airborne networks;collision avoidance;convex plume wrapping;cooperative trajectory planning;environment contamination tracking;fire detection;guidance algorithms;intelligent task assignment;intercommunicating UAV group;path planning;plume shape tracking;plume tracking algorithms;position estimation;volcanic eruptions;Contamination;Heuristic algorithms;Planning;Rough surfaces;Shape;Trajectory;Wrapping;UAV;multi-UAV communication;plume wrapping;trajectory planning},
doi={10.1109/SARNOF.2017.8080382},
ISSN={},
month={Sept},}

@ARTICLE{7463007,
author={S. Hayat and E. Yanmaz and R. Muzaffar},
journal={IEEE Communications Surveys Tutorials},
title={Survey on Unmanned Aerial Vehicle Networks for Civil Applications: A Communications Viewpoint},
year={2016},
volume={18},
number={4},
pages={2624-2661},
keywords={air traffic;aircraft communication;autonomous aerial vehicles;quality of service;telecommunication network reliability;UAV network;aerial networking reliability;air traffic;civil application;coordinated aerial vehicle;network-relevant mission parameter;quality of service requirement;unmanned aerial vehicle network;Adaptation models;Protocols;Quality of service;Reliability;Vehicles;Wireless communication;Wireless sensor networks;UAVs;aerial networks;communication;cooperative UAVs;delivery of goods;network infrastructure;quality of service;search and rescue;swarms},
doi={10.1109/COMST.2016.2560343},
ISSN={1553-877X},
month={Fourthquarter},}

extension: bib


text:
package dnszone

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
	"github.com/aws/aws-sdk-go/service/route53"
	"github.com/golang/mock/gomock"
	"github.com/openshift/hive/pkg/awsclient/mock"
	log "github.com/sirupsen/logrus"
	"github.com/stretchr/testify/assert"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes/scheme"

	"github.com/openshift/hive/pkg/apis"
	hivev1 "github.com/openshift/hive/pkg/apis/hive/v1alpha1"
)

func init() {
	apis.AddToScheme(scheme.Scheme)
}

// TestNewAWSActuator tests that a new AWSActuator object can be created.
func TestNewAWSActuator(t *testing.T) {
	cases := []struct {
		name    string
		dnsZone *hivev1.DNSZone
		secret  *corev1.Secret
	}{
		{
			name:    "Successfully create new zone",
			dnsZone: validDNSZone(),
			secret:  validAWSSecret(),
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			// Arrange
			mocks := setupDefaultMocks(t)
			expectedAWSActuator := &AWSActuator{
				logger:  log.WithField("controller", controllerName),
				dnsZone: tc.dnsZone,
			}

			// Act
			zr, err := NewAWSActuator(
				expectedAWSActuator.logger,
				tc.secret,
				tc.dnsZone,
				fakeAWSClientBuilder(mocks.mockAWSClient),
			)
			expectedAWSActuator.awsClient = zr.awsClient // Function pointers can't be compared reliably. Don't compare.

			// Assert
			assert.Nil(t, err)
			assert.NotNil(t, zr.awsClient)
			assert.Equal(t, expectedAWSActuator, zr)
		})
	}
}

func mockAWSZoneExists(expect *mock.MockClientMockRecorder, zone *hivev1.DNSZone) {

	if zone.Status.AWS == nil || aws.StringValue(zone.Status.AWS.ZoneID) == "" {
		expect.GetResourcesPages(gomock.Any(), gomock.Any()).
			Do(func(input *resourcegroupstaggingapi.GetResourcesInput, f func(*resourcegroupstaggingapi.GetResourcesOutput, bool) bool) {
				f(&resourcegroupstaggingapi.GetResourcesOutput{
					ResourceTagMappingList: []*resourcegroupstaggingapi.ResourceTagMapping{
						{
							ResourceARN: aws.String("arn:aws:route53:::hostedzone/1234"),
						},
					},
				}, true)
			}).Return(nil).Times(1)
	}
	expect.GetHostedZone(gomock.Any()).Return(&route53.GetHostedZoneOutput{
		HostedZone: &route53.HostedZone{
			Id:   aws.String("1234"),
			Name: aws.String("blah.example.com"),
		},
	}, nil).Times(1)
}

func mockAWSZoneDoesntExist(expect *mock.MockClientMockRecorder, zone *hivev1.DNSZone) {
	if zone.Status.AWS != nil && aws.StringValue(zone.Status.AWS.ZoneID) != "" {
		expect.GetHostedZone(gomock.Any()).
			Return(nil, awserr.New(route53.ErrCodeNoSuchHostedZone, "doesnt exist", fmt.Errorf("doesnt exist"))).Times(1)
		return
	}
	expect.GetResourcesPages(gomock.Any(), gomock.Any()).Return(nil).Times(1)
}

func mockCreateAWSZone(expect *mock.MockClientMockRecorder) {
	expect.CreateHostedZone(gomock.Any()).Return(&route53.CreateHostedZoneOutput{
		HostedZone: &route53.HostedZone{
			Id:   aws.String("1234"),
			Name: aws.String("blah.example.com"),
		},
	}, nil).Times(1)
}

func mockCreateAWSZoneDuplicateFailure(expect *mock.MockClientMockRecorder) {
	expect.CreateHostedZone(gomock.Any()).Return(nil, awserr.New(route53.ErrCodeHostedZoneAlreadyExists, "already exists", fmt.Errorf("already exists"))).Times(1)
}

func mockNoExistingAWSTags(expect *mock.MockClientMockRecorder) {
	expect.ListTagsForResource(gomock.Any()).Return(&route53.ListTagsForResourceOutput{
		ResourceTagSet: &route53.ResourceTagSet{
			ResourceId: aws.String("1234"),
			Tags:       []*route53.Tag{},
		},
	}, nil).Times(1)
}

func mockExistingAWSTags(expect *mock.MockClientMockRecorder) {
	expect.ListTagsForResource(gomock.Any()).Return(&route53.ListTagsForResourceOutput{
		ResourceTagSet: &route53.ResourceTagSet{
			ResourceId: aws.String("1234"),
			Tags: []*route53.Tag{
				{
					Key:   aws.String(hiveDNSZoneAWSTag),
					Value: aws.String("ns/dnszoneobject"),
				},
				{
					Key:   aws.String("foo"),
					Value: aws.String("bar"),
				},
			},
		},
	}, nil).Times(1)
}

func mockSyncAWSTags(expect *mock.MockClientMockRecorder) {
	expect.ChangeTagsForResource(gomock.Any()).Return(&route53.ChangeTagsForResourceOutput{}, nil).AnyTimes()
}

func mockAWSGetNSRecord(expect *mock.MockClientMockRecorder) {
	expect.ListResourceRecordSets(gomock.Any()).Return(&route53.ListResourceRecordSetsOutput{
		ResourceRecordSets: []*route53.ResourceRecordSet{
			{
				Type: aws.String("NS"),
				Name: aws.String("blah.example.com."),
				ResourceRecords: []*route53.ResourceRecord{
					{
						Value: aws.String("ns1.example.com"),
					},
					{
						Value: aws.String("ns2.example.com"),
					},
				},
			},
		},
	}, nil)
}

func mockListAWSZonesByNameFound(expect *mock.MockClientMockRecorder, zone *hivev1.DNSZone) {
	expect.ListHostedZonesByName(gomock.Any()).Return(&route53.ListHostedZonesByNameOutput{
		HostedZones: []*route53.HostedZone{
			{
				Id:              aws.String("1234"),
				Name:            aws.String("blah.example.com"),
				CallerReference: aws.String(string(zone.UID)),
			},
		},
	}, nil).Times(1)
}

func mockDeleteAWSZone(expect *mock.MockClientMockRecorder) {
	expect.DeleteHostedZone(gomock.Any()).Return(nil, nil).Times(1)
}

repository: LalatenduMohanty/hive

repo_name: LalatenduMohanty/hive


text:
package driver

import (
	"fmt"
	"os"
	"regexp"
	"strings"
	"time"

	"github.com/jmoiron/sqlx"
	"github.com/olekukonko/tablewriter"
	migrate "github.com/rubenv/sql-migrate"

	"github.com/justpark/auth/hydra/client"
	"github.com/justpark/auth/hydra/consent"
	"github.com/justpark/auth/hydra/jwk"
	"github.com/justpark/auth/hydra/oauth2"
	"github.com/justpark/auth/hydra/x"
	"github.com/ory/x/dbal"
	"github.com/ory/x/sqlcon"
	"github.com/ory/x/urlx"
)

type RegistrySQL struct {
	*RegistryBase
	db          *sqlx.DB
	dbalOptions []sqlcon.OptionModifier
}

var _ Registry = new(RegistrySQL)

var multiSpace = regexp.MustCompile("\\s+")

func init() {
	dbal.RegisterDriver(NewRegistrySQL())
}

type schemaCreator interface {
	CreateSchemas(dbName string) (int, error)
	PlanMigration(dbName string) ([]*migrate.PlannedMigration, error)
}

func NewRegistrySQL() *RegistrySQL {
	r := &RegistrySQL{
		RegistryBase: new(RegistryBase),
	}
	r.RegistryBase.with(r)
	return r
}

func (m *RegistrySQL) WithDB(db *sqlx.DB) Registry {
	m.db = db
	return m
}

func (m *RegistrySQL) Init() error {
	if m.db != nil {
		return nil
	}

	options := append([]sqlcon.OptionModifier{}, m.dbalOptions...)
	if m.Tracer().IsLoaded() {
		options = append(options, sqlcon.WithDistributedTracing(), sqlcon.WithOmitArgsFromTraceSpans())
	}

	connection, err := sqlcon.NewSQLConnection(m.c.DSN(), m.Logger(), options...)
	if err != nil {
		return err
	}

	m.db, err = connection.GetDatabaseRetry(time.Second*5, time.Minute*5)
	if err != nil {
		return err
	}

	return err
}

func (m *RegistrySQL) DB() *sqlx.DB {
	if m.db == nil {
		if err := m.Init(); err != nil {
			m.Logger().WithError(err).Fatalf("Unable to initialize database.")
		}
	}

	return m.db
}

func (m *RegistrySQL) SchemaMigrationPlan(dbName string) (*tablewriter.Table, error) {
	names := map[int]string{
		0: "JSON Web Keys",
		1: "OAuth 2.0 Clients",
		2: "Login &Consent",
		3: "OAuth 2.0",
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
	table.SetCenterSeparator("|")
	table.SetAutoMergeCells(true)
	table.SetRowLine(true)
	table.SetColMinWidth(4, 20)
	table.SetHeader([]string{
		"Driver",
		"Module",
		"ID",
		"#",
		"Query",
	})

	for _, s := range []schemaCreator{
		m.KeyManager().(schemaCreator),
		m.ClientManager().(schemaCreator),
		m.ConsentManager().(schemaCreator),
		m.OAuth2Storage().(schemaCreator),
	} {
		plans, err := s.PlanMigration(dbName)
		if err != nil {
			return nil, err
		}

		for _, plan := range plans {
			for k, up := range plan.Up {
				up = strings.Replace("\n", "", strings.TrimSpace(up), -1)
				up = strings.Join(strings.Fields(up), " ")
				if len(up) > 0 {
					table.Append([]string{m.db.DriverName(), names[k], plan.Id + ".sql", fmt.Sprintf("%d", k), up})
				}
			}
		}
	}

	return table, nil
}

func (m *RegistrySQL) CreateSchemas(dbName string) (int, error) {
	var total int

	m.Logger().Debugf("Applying %s SQL migrations...", dbName)
	for k, s := range []schemaCreator{
		m.KeyManager().(schemaCreator),
		m.ClientManager().(schemaCreator),
		m.ConsentManager().(schemaCreator),
		m.OAuth2Storage().(schemaCreator),
	} {
		m.Logger().Debugf("Applying %s SQL migrations for manager: %T (%d)", dbName, s, k)
		if c, err := s.CreateSchemas(dbName); err != nil {
			return c, err
		} else {
			m.Logger().Debugf("Successfully applied %d %s SQL migrations from manager: %T (%d)", c, dbName, s, k)
			total += c
		}
	}
	m.Logger().Debugf("Applied %d %s SQL migrations", total, dbName)

	return total, nil
}

func (m *RegistrySQL) CanHandle(dsn string) bool {
	s := dbal.Canonicalize(urlx.ParseOrFatal(m.l, dsn).Scheme)
	return s == dbal.DriverMySQL || s == dbal.DriverPostgreSQL || s == dbal.DriverCockroachDB
}

func (m *RegistrySQL) Ping() error {
	return m.DB().Ping()
}

func (m *RegistrySQL) ClientManager() client.Manager {
	if m.cm == nil {
		m.cm = client.NewSQLManager(m.DB(), m)
	}
	return m.cm
}

func (m *RegistrySQL) ConsentManager() consent.Manager {
	if m.com == nil {
		m.com = consent.NewSQLManager(m.DB(), m)
	}
	return m.com
}

func (m *RegistrySQL) OAuth2Storage() x.FositeStorer {
	if m.fs == nil {
		m.fs = oauth2.NewFositeSQLStore(m.DB(), m.r, m.c)
	}
	return m.fs
}

func (m *RegistrySQL) KeyManager() jwk.Manager {
	if m.km == nil {
		m.km = jwk.NewSQLManager(m.DB(), m)
	}
	return m.km
}

repository: justpark/auth

repo_name: justpark/auth


text:
package array

// removeDuplicates 删除数组中的重复项
// 【双指针】，【数组】
// https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
func removeDuplicates(nums []int) int {
	var (
		k int
	)

	// [0,1,2,3,4k,2,2,3,3,4]i

	if len(nums) == 0 {
		return k
	}
	for i := 0; i < len(nums); i++ {
		if nums[k] != nums[i] {
			nums[k+1] = nums[i]
			k++
		}
	}

	return k + 1
}

func RemoveDuplicatesII(nums []int) int {
	// 快慢指针
	// p1 是唯一元素的个数
	// p2 是当前遍历的进度
	// 1，2，3，4，5，5，5，6
	p := 0
	for i := 1; i < len(nums); i++ {
		// 如果一样，i++
		// 如果不一样，p++，i位置覆盖到p位置
		if nums[p] == nums[i] {
			continue
		}

		p++
		if p != i {
			nums[p] = nums[i]
		}
	}
	p++
	return p
}

repository: EmbraceUU/caesar-go

repo_name: EmbraceUU/caesar-go


text:
package sidecar

import (
	"context"

	"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/core"

	"github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/utils"

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core/template"

	"github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery"
	pluginsCore "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core"
	"github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/flytek8s"
	"github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/k8s"

	"github.com/flyteorg/flyteplugins/go/tasks/errors"
	"github.com/flyteorg/flyteplugins/go/tasks/logs"
	k8sv1 "k8s.io/api/core/v1"
)

const (
	sidecarTaskType     = "sidecar"
	primaryContainerKey = "primary_container_name"
)

type sidecarResourceHandler struct{}

// This method handles templatizing primary container input args, env variables and adds a GPU toleration to the pod
// spec if necessary.
func validateAndFinalizePod(
	ctx context.Context, taskCtx pluginsCore.TaskExecutionContext, primaryContainerName string, pod k8sv1.Pod) (*k8sv1.Pod, error) {
	var hasPrimaryContainer bool

	finalizedContainers := make([]k8sv1.Container, len(pod.Spec.Containers))
	resReqs := make([]k8sv1.ResourceRequirements, 0, len(pod.Spec.Containers))
	for index, container := range pod.Spec.Containers {
		if container.Name == primaryContainerName {
			hasPrimaryContainer = true
			container.Resources = *flytek8s.ApplyResourceOverrides(ctx, container.Resources)
			if taskCtx.TaskExecutionMetadata().GetOverrides() != nil && taskCtx.TaskExecutionMetadata().GetOverrides().GetResources() != nil {
				resOverrides := taskCtx.TaskExecutionMetadata().GetOverrides().GetResources()
				flytek8s.MergeResources(*resOverrides, &container.Resources)
			}
		}
		modifiedCommand, err := template.Render(ctx, container.Command, template.Parameters{
			TaskExecMetadata: taskCtx.TaskExecutionMetadata(),
			Inputs:           taskCtx.InputReader(),
			OutputPath:       taskCtx.OutputWriter(),
			Task:             taskCtx.TaskReader(),
		})
		if err != nil {
			return nil, err
		}
		container.Command = modifiedCommand

		modifiedArgs, err := template.Render(ctx, container.Args, template.Parameters{
			TaskExecMetadata: taskCtx.TaskExecutionMetadata(),
			Inputs:           taskCtx.InputReader(),
			OutputPath:       taskCtx.OutputWriter(),
			Task:             taskCtx.TaskReader(),
		})
		if err != nil {
			return nil, err
		}
		container.Args = modifiedArgs
		container.Env = flytek8s.DecorateEnvVars(ctx, container.Env, taskCtx.TaskExecutionMetadata().GetTaskExecutionID())
		resReqs = append(resReqs, container.Resources)
		finalizedContainers[index] = container
	}
	if !hasPrimaryContainer {
		return nil, errors.Errorf(errors.BadTaskSpecification,
			"invalid Sidecar task, primary container [%s] not defined", primaryContainerName)

	}
	pod.Spec.Containers = finalizedContainers
	flytek8s.UpdatePod(taskCtx.TaskExecutionMetadata(), resReqs, &pod.Spec)
	return &pod, nil
}

// Why, you might wonder do we recreate the generated go struct generated from the plugins.SidecarJob proto? Because
// although we unmarshal the task custom json, the PodSpec itself is not generated from a  proto definition,
// but a proper go struct defined in k8s libraries. Therefore we only unmarshal the sidecar as a json, rather than jsonpb.
type sidecarJob struct {
	PodSpec              *k8sv1.PodSpec
	PrimaryContainerName string
	Annotations          map[string]string
	Labels               map[string]string
}

func (sidecarResourceHandler) GetProperties() k8s.PluginProperties {
	return k8s.PluginProperties{}
}

func getPrimaryContainerNameFromConfig(task *core.TaskTemplate) (string, error) {
	if len(task.GetConfig()) == 0 {
		return "", errors.Errorf(errors.BadTaskSpecification,
			"invalid TaskSpecification, config needs to be non-empty and include missing [%s] key", primaryContainerKey)
	}
	primaryContainerName, ok := task.GetConfig()[primaryContainerKey]
	if !ok {
		return "", errors.Errorf(errors.BadTaskSpecification,
			"invalid TaskSpecification, config missing [%s] key in [%v]", primaryContainerKey, task.GetConfig())
	}
	return primaryContainerName, nil
}

type podSpecResource struct {
	podSpec              k8sv1.PodSpec
	primaryContainerName string
	annotations          map[string]string
	labels               map[string]string
}

func newPodSpecResource() podSpecResource {
	return podSpecResource{
		annotations: make(map[string]string),
		labels:      make(map[string]string),
	}
}

// Handles pod tasks when they are defined as Sidecar tasks and marshal the podspec using k8s proto.
func buildResourceV0(task *core.TaskTemplate) (podSpecResource, error) {
	res := newPodSpecResource()
	sidecarJob := sidecarJob{}
	err := utils.UnmarshalStructToObj(task.GetCustom(), &sidecarJob)
	if err != nil {
		return podSpecResource{}, errors.Errorf(errors.BadTaskSpecification,
			"invalid TaskSpecification [%v], Err: [%v]", task.GetCustom(), err.Error())
	}
	if sidecarJob.PodSpec == nil {
		return podSpecResource{}, errors.Errorf(errors.BadTaskSpecification,
			"invalid TaskSpecification, nil PodSpec [%v]", task.GetCustom())
	}
	res.podSpec = *sidecarJob.PodSpec
	res.primaryContainerName = sidecarJob.PrimaryContainerName
	if sidecarJob.Annotations != nil {
		res.annotations = sidecarJob.Annotations
	}

	if sidecarJob.Labels != nil {
		res.labels = sidecarJob.Labels
	}

	return res, nil
}

// Handles pod tasks that marshal the pod spec to the task custom.
func buildResourceV1(task *core.TaskTemplate) (podSpecResource, error) {
	res := newPodSpecResource()
	err := utils.UnmarshalStructToObj(task.GetCustom(), &res.podSpec)
	if err != nil {
		return podSpecResource{}, errors.Errorf(errors.BadTaskSpecification,
			"Unable to unmarshal task custom [%v], Err: [%v]", task.GetCustom(), err.Error())
	}
	res.primaryContainerName, err = getPrimaryContainerNameFromConfig(task)
	if err != nil {
		return podSpecResource{}, err
	}
	return res, nil
}

// Handles pod tasks that marshal the pod spec to the k8s_pod task target.
func buildResourceV2(task *core.TaskTemplate) (podSpecResource, error) {
	res := newPodSpecResource()
	if task.GetK8SPod() == nil || task.GetK8SPod().PodSpec == nil {
		return podSpecResource{}, errors.Errorf(errors.BadTaskSpecification,
			"Pod tasks with task type version > 1 should specify their target as a K8sPod with a defined pod spec")
	}
	err := utils.UnmarshalStructToObj(task.GetK8SPod().PodSpec, &res.podSpec)
	if err != nil {
		return podSpecResource{}, errors.Errorf(errors.BadTaskSpecification,
			"Unable to unmarshal task custom [%v], Err: [%v]", task.GetCustom(), err.Error())
	}
	res.primaryContainerName, err = getPrimaryContainerNameFromConfig(task)
	if err != nil {
		return podSpecResource{}, err
	}
	if task.GetK8SPod().Metadata != nil {
		if task.GetK8SPod().Metadata.Annotations != nil {
			res.annotations = task.GetK8SPod().Metadata.Annotations
		}
		if task.GetK8SPod().Metadata.Labels != nil {
			res.labels = task.GetK8SPod().Metadata.Labels
		}
	}
	return res, nil
}

func (sidecarResourceHandler) BuildResource(ctx context.Context, taskCtx pluginsCore.TaskExecutionContext) (client.Object, error) {
	task, err := taskCtx.TaskReader().Read(ctx)
	if err != nil {
		return nil, errors.Errorf(errors.BadTaskSpecification,
			"TaskSpecification cannot be read, Err: [%v]", err.Error())
	}
	var podSpecResource podSpecResource
	switch task.TaskTypeVersion {
	case 0:
		podSpecResource, err = buildResourceV0(task)
		if err != nil {
			return nil, err
		}
	case 1:
		podSpecResource, err = buildResourceV1(task)
		if err != nil {
			return nil, err
		}
	default:
		podSpecResource, err = buildResourceV2(task)
		if err != nil {
			return nil, err
		}
	}

	pod := flytek8s.BuildPodWithSpec(&podSpecResource.podSpec)
	// Set the restart policy to *not* inherit from the default so that a completed pod doesn't get caught in a
	// CrashLoopBackoff after the initial job completion.
	pod.Spec.RestartPolicy = k8sv1.RestartPolicyNever

	pod.Spec.ServiceAccountName = flytek8s.GetServiceAccountNameFromTaskExecutionMetadata(taskCtx.TaskExecutionMetadata())

	pod, err = validateAndFinalizePod(ctx, taskCtx, podSpecResource.primaryContainerName, *pod)
	if err != nil {
		return nil, err
	}

	pod.Annotations = podSpecResource.annotations
	pod.Annotations[primaryContainerKey] = podSpecResource.primaryContainerName
	pod.Labels = podSpecResource.labels
	return pod, nil
}

func (sidecarResourceHandler) BuildIdentityResource(_ context.Context, _ pluginsCore.TaskExecutionMetadata) (
	client.Object, error) {
	return flytek8s.BuildIdentityPod(), nil
}

func (sidecarResourceHandler) GetTaskPhase(ctx context.Context, pluginContext k8s.PluginContext, r client.Object) (pluginsCore.PhaseInfo, error) {
	pod := r.(*k8sv1.Pod)

	transitionOccurredAt := flytek8s.GetLastTransitionOccurredAt(pod).Time
	info := pluginsCore.TaskInfo{
		OccurredAt: &transitionOccurredAt,
	}
	if pod.Status.Phase != k8sv1.PodPending && pod.Status.Phase != k8sv1.PodUnknown {
		taskLogs, err := logs.GetLogsForContainerInPod(ctx, pod, 0, " (User)")
		if err != nil {
			return pluginsCore.PhaseInfoUndefined, err
		}
		info.Logs = taskLogs
	}
	switch pod.Status.Phase {
	case k8sv1.PodSucceeded:
		return flytek8s.DemystifySuccess(pod.Status, info)
	case k8sv1.PodFailed:
		code, message := flytek8s.ConvertPodFailureToError(pod.Status)
		return pluginsCore.PhaseInfoRetryableFailure(code, message, &info), nil
	case k8sv1.PodPending:
		return flytek8s.DemystifyPending(pod.Status)
	case k8sv1.PodReasonUnschedulable:
		return pluginsCore.PhaseInfoQueued(transitionOccurredAt, pluginsCore.DefaultPhaseVersion, "pod unschedulable"), nil
	case k8sv1.PodUnknown:
		return pluginsCore.PhaseInfoUndefined, nil
	}

	// Otherwise, assume the pod is running.
	primaryContainerName, ok := r.GetAnnotations()[primaryContainerKey]
	if !ok {
		return pluginsCore.PhaseInfoUndefined, errors.Errorf(errors.BadTaskSpecification,
			"missing primary container annotation for pod")
	}
	primaryContainerPhase := flytek8s.DeterminePrimaryContainerPhase(primaryContainerName, pod.Status.ContainerStatuses, &info)

	if primaryContainerPhase.Phase() == pluginsCore.PhaseRunning && len(info.Logs) > 0 {
		return pluginsCore.PhaseInfoRunning(pluginsCore.DefaultPhaseVersion+1, primaryContainerPhase.Info()), nil
	}
	return primaryContainerPhase, nil
}

func init() {
	pluginmachinery.PluginRegistry().RegisterK8sPlugin(
		k8s.PluginEntry{
			ID:                  sidecarTaskType,
			RegisteredTaskTypes: []pluginsCore.TaskType{sidecarTaskType},
			ResourceToWatch:     &k8sv1.Pod{},
			Plugin:              sidecarResourceHandler{},
			IsDefault:           false,
			DefaultForTaskTypes: []pluginsCore.TaskType{sidecarTaskType},
		})
}

repository: clairemcginty/flyteplugins

repo_name: clairemcginty/flyteplugins


text:
#pragma once

#include "..\System\Xml\IHasXmlChildNode.h"
#include "..\System\Xml\XmlLinkedNode.h"

namespace rust
{
	class Enumerator : public Object // 0x0
	{
	public:
		System::Xml::IHasXmlChildNode* parent; // 0x10 (size: 0x8, flags: 0x1, type: 0x12)
		System::Xml::XmlLinkedNode* currentChild; // 0x18 (size: 0x8, flags: 0x1, type: 0x12)
		bool passedLastNode; // 0x20 (size: 0x1, flags: 0x1, type: 0x2)
	}; // size = 0x28
}

extension: h


text:
package commands

import (
	"context"

	"github.com/christianalexander/kvdb"
)

// noop is a command that does nothing.
type noop struct{}

// Execute satisfies the command interface.
func (q noop) Execute(ctx context.Context) error {
	return nil
}

func (q noop) Undo(ctx context.Context) error {
	return nil
}

func (q noop) ShouldAutoTransact() bool {
	return false
}

// NewNoop creates a new noop command.
func NewNoop() kvdb.Command {
	return noop{}
}

repository: chemdrew/kvdb

repo_name: chemdrew/kvdb


text:
#include "image.hpp"
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <png.h>
#include <sstream>

Image::Image()
  : m_width(0), m_height(0), m_elements(0), m_data(0)
{
}

Image::Image(int width, int height, int elements)
  : m_width(width), m_height(height), m_elements(elements),
    m_data(new double[m_width * m_height * m_elements])
{
}

Image::Image(const Image& other)
  : m_width(other.m_width), m_height(other.m_height), m_elements(other.m_elements),
    m_data(other.m_data ? new double[m_width * m_height * m_elements] : 0)
{
  if (m_data) {
    std::memcpy(m_data, other.m_data,
                m_width * m_height * m_elements * sizeof(double));
  }
}

Image::~Image()
{
  delete [] m_data;
}

Image& Image::operator=(const Image& other)
{
  delete [] m_data;

  m_width = other.m_width;
  m_height = other.m_height;
  m_elements = other.m_elements;
  m_data = (other.m_data ? new double[m_width * m_height * m_elements] : 0);

  if (m_data) {
    std::memcpy(m_data,
                other.m_data,
                m_width * m_height * m_elements * sizeof(double));
  }

  return *this;
}

int Image::width() const
{
  return m_width;
}

int Image::height() const
{
  return m_height;
}

int Image::elements() const
{
  return m_elements;
}

double Image::operator()(int x, int y, int i) const
{
  return m_data[m_elements * (m_width * y + x) + i];
}

double& Image::operator()(int x, int y, int i)
{
  return m_data[m_elements * (m_width * y + x) + i];
}

bool Image::savePng(const std::string& filename)
{
  FILE* fout = std::fopen(filename.c_str(), "wb");
  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  png_infop info_ptr = png_create_info_struct(png_ptr);
  setjmp(png_jmpbuf(png_ptr));

  /* Setup PNG I/O */
  png_init_io(png_ptr, fout);

  /* Optionally setup a callback to indicate when a row has been
   * written. */

  /* Setup filtering. Use Paeth filtering */
  png_set_filter(png_ptr, 0, PNG_FILTER_PAETH);

  /* Setup compression level. */
  //png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);

  /* Setup PNG header information and write it to the file */

  int color_type;
  switch (m_elements) {
  case 1:
    color_type = PNG_COLOR_TYPE_GRAY;
    break;
  case 2:
    color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
    break;
  case 3:
    color_type = PNG_COLOR_TYPE_RGB;
    break;
  case 4:
    color_type = PNG_COLOR_TYPE_RGBA;
    break;
  default:
    return false;
  }

  png_set_IHDR(png_ptr, info_ptr,
               m_width, m_height,
               8,
               color_type,
               PNG_INTERLACE_NONE,
               PNG_COMPRESSION_TYPE_DEFAULT,
               PNG_FILTER_TYPE_DEFAULT);
  png_write_info(png_ptr, info_ptr);

  // Actual writing
  png_byte* tempLine = new png_byte[m_width * m_elements];

  for (int i = 0; i < m_height; i++) {
    for (int j = 0; j < m_width; j++) {
      for (int k = 0; k < m_elements; k++) {
        // Clamp the value
        double value = std::min(1.0, std::max(0.0, (*this)(j, i, k)));

        // Write it out
        tempLine[m_elements * j + k] = static_cast<png_byte>(value * 255.0);
      }
    }
    png_write_row(png_ptr, tempLine);
  }

  delete [] tempLine;

  // closing and freeing the structs
  png_write_end(png_ptr, info_ptr);
  png_destroy_write_struct(&png_ptr, &info_ptr);
  std::fclose(fout);

  return true;
}

bool Image::loadPng(const std::string& filename)
{
  // check that the file is a png file
  png_byte buf[8];

  FILE* in = std::fopen(filename.c_str(), "rb");

  if (!in) return false;

  for (int i = 0; i < 8; i++) {
    if (!(buf[i] = fgetc(in))) return false;
  }
  if (png_sig_cmp(buf, 0, 8)) return false;

  png_structp png_ptr =
    png_create_read_struct(PNG_LIBPNG_VER_STRING,
                           0, 0, 0);
  if (!png_ptr) return false;

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr) {
    png_destroy_read_struct(&png_ptr, 0, 0);
    return false;
  }

  if (setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_read_struct(&png_ptr, 0, 0);
    return false;
  }

  //  png_set_read_fn(png_ptr, reinterpret_cast<void*>(&in), my_istream_read_data);
  png_init_io(png_ptr, in);

  png_set_sig_bytes(png_ptr, 8);

  png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, 0);

  int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
  if (bit_depth % 8) {
    png_destroy_read_struct(&png_ptr, 0, 0);
    std::ostringstream os;
    os << "Invalid bit elements " << bit_depth;
    return false;
  }

  int colour_type = png_get_color_type(png_ptr, info_ptr);

  if (colour_type == PNG_COLOR_TYPE_PALETTE) {
    png_set_palette_to_rgb(png_ptr);
    colour_type = PNG_COLOR_TYPE_RGB;
  }

  if (colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
    png_set_expand_gray_1_2_4_to_8(png_ptr);
  }

  if (colour_type != PNG_COLOR_TYPE_RGB
      && colour_type != PNG_COLOR_TYPE_GRAY
      && colour_type != PNG_COLOR_TYPE_RGBA) {
    png_destroy_read_struct(&png_ptr, 0, 0);
    return false;
  }

  delete [] m_data;

  m_width = png_get_image_width(png_ptr, info_ptr);
  m_height = png_get_image_height(png_ptr, info_ptr);
  switch (colour_type) {
  case PNG_COLOR_TYPE_RGB:
    m_elements = 3;
    break;
  case PNG_COLOR_TYPE_RGBA:
    m_elements = 4;
    break;
  default:
    m_elements = 1;
    break;
  }

  png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);

  m_data = new double[m_width * m_height * m_elements];

  for (int y = 0; y < m_height; y++) {
    for (int x = 0; x < m_width; x++) {
      for (int i = 0; i < m_elements; i++) {
        png_byte *row = row_pointers[y];
        int index = m_elements * (y * m_width + x) + i;

        long element = 0;
        for (int j = bit_depth / 8 - 1; j >= 0; j--) {
          element <<= 8;
          element += row[(x * m_elements + i) * bit_depth / 8 + j];
        }

        m_data[index] = element / static_cast<double>((1 << bit_depth) - 1);
      }
    }
  }

  png_destroy_read_struct(&png_ptr, &info_ptr, 0);

  return true;
}

const double* Image::data() const
{
  return m_data;
}

double* Image::data()
{
  return m_data;
}

repository: jnbmoffa/raytracer

repo_name: jnbmoffa/raytracer


text:
package main

import (
	"errors"
	"os"
	"path"

	"github.com/NebulousLabs/Sia/consensus"
	"github.com/NebulousLabs/Sia/network"
	"github.com/NebulousLabs/Sia/siacrypto"
	"github.com/NebulousLabs/Sia/state"
)

// The ParticipantManager houses all of the participants. It will eventually contain a
// clock object that will be used and modified by all participants.
type ParticipantManager struct {
	parentDirectory string
	participants    map[string]*consensus.Participant
}

type NewParticipantInfo struct {
	Name      string
	SiblingID state.WalletID

	UseUniqueDirectory bool
	UniqueDirectory    string
}

// NewParticipantManager takes a port number as input and returns a server object that's
// ready to be populated with participants.
func newParticipantManager() (p *ParticipantManager, err error) {
	// Determine whether the server is public.
	if !config.Network.PublicConnection {
		err = errors.New("server is not public - the whole network will be local")
	}

	// Create the participant manager.
	p = new(ParticipantManager)
	p.participants = make(map[string]*consensus.Participant)
	return
}

// NewParticipant creates a directory 'name' at location 'filepath' and then
// creates a participant that will use that directory for its files. It's
// mostly a helper function to eliminate redundant code.
func (s *Server) createParticipantStructures(npi NewParticipantInfo) (dirname string, err error) {
	// Check that a participant of the given name does not already exist.
	_, exists := s.participantManager.participants[npi.Name]
	if exists {
		err = errors.New("a participant of that name already exists.")
		return
	}

	// Create a directory for the participant, using the unique directory
	// if the flag is set, and using the participantDir/Name if not.
	if npi.UseUniqueDirectory {
		dirname = npi.UniqueDirectory
	} else {
		dirname = path.Join(config.Filesystem.ParticipantDir, npi.Name) + "/"
	}
	if err = os.MkdirAll(dirname, os.ModeDir|os.ModePerm); err != nil {
		return
	}

	return
}

// NewBootstrapParticipant creates a new participant that is the first in it's
// quorum; it creates the quorum along with the participant.
func (s *Server) NewBootstrapParticipant(npi NewParticipantInfo, _ *struct{}) (err error) {
	dirname, err := s.createParticipantStructures(npi)
	if err != nil {
		return
	}

	// Create a keypair for the wallet that the sibling will tether to.
	pk, sk, err := siacrypto.CreateKeyPair()
	if err != nil {
		return
	}

	// Create the participant and add it to the server map.
	newParticipant, err := consensus.CreateBootstrapParticipant(s.router, dirname, npi.SiblingID, pk)
	if err != nil {
		return
	}
	s.participantManager.participants[npi.Name] = newParticipant

	// Add the wallet to the client list of generic wallets.
	s.genericWallets[GenericWalletID(npi.SiblingID)] = &GenericWallet{
		WalletID:  npi.SiblingID,
		PublicKey: pk,
		SecretKey: sk,
	}

	// Update the list of siblings to contain the bootstrap address, by
	// getting a list of siblings out of the newParticipant metadata.
	var metadata state.Metadata
	if err = newParticipant.Metadata(struct{}{}, &metadata); err != nil {
		return
	}
	s.metadata.Siblings = metadata.Siblings

	return
}

// NewJoiningParticipant creates a participant that joins the network known to
// the client as a sibling.
func (s *Server) NewJoiningParticipant(npi NewParticipantInfo, _ *struct{}) (err error) {
	dirname, err := s.createParticipantStructures(npi)
	if err != nil {
		return
	}

	// Verify that the sibID given is available to the client.
	_, exists := s.genericWallets[GenericWalletID(npi.SiblingID)]
	if !exists {
		err = errors.New("no known wallet of that id")
		return
	}

	// Refresh the metadata and then grab all the addresses for the joining
	// participant to use.
	if err = s.refreshMetadata(); err != nil {
		return
	}
	var siblingAddresses []network.Address
	for _, sibling := range s.metadata.Siblings {
		siblingAddresses = append(siblingAddresses, sibling.Address)
	}

	joiningParticipant, err := consensus.CreateJoiningParticipant(s.router, dirname, npi.SiblingID, s.genericWallets[GenericWalletID(npi.SiblingID)].SecretKey, siblingAddresses)
	if err != nil {
		return
	}
	s.participantManager.participants[npi.Name] = joiningParticipant

	// Update the list of siblings to contain the bootstrap address, by
	// getting a list of siblings out of the joiningParticipant metadata.
	var metadata state.Metadata
	if err = joiningParticipant.Metadata(struct{}{}, &metadata); err != nil {
		return
	}
	s.metadata.Siblings = metadata.Siblings

	return
}

// ParticipantNames returns a list of participant names known to the server.
func (s *Server) ParticipantNames(_ struct{}, parts *[]string) (err error) {
	*parts = make([]string, 0, len(s.participantManager.participants))
	for name := range s.participantManager.participants {
		*parts = append(*parts, name)
	}
	return
}

// ParticipantMetadata returns the metadata for the participant with the given
// name. If no participant of that name exists, an error is returned.
func (s *Server) ParticipantMetadata(name string, m *state.Metadata) (err error) {
	participant, exists := s.participantManager.participants[name]
	if !exists {
		err = errors.New("no participant of that name found")
		return
	}

	err = participant.Metadata(struct{}{}, m)
	if err != nil {
		return
	}

	return
}

// ParticipantWallets returns every wallet known to the participant of the
// given name.
func (s *Server) ParticipantWallets(name string, wallets *[]state.Wallet) (err error) {
	participant, exists := s.participantManager.participants[name]
	if !exists {
		err = errors.New("no participant of that name found")
		return
	}

	var walletIDList []state.WalletID
	err = participant.WalletIDs(struct{}{}, &walletIDList)
	if err != nil {
		return
	}

	for _, id := range walletIDList {
		var wallet state.Wallet
		err = participant.Wallet(id, &wallet)
		if err != nil {
			return
		}

		*wallets = append(*wallets, wallet)
	}

	return
}

repository: randydom/Sia

repo_name: randydom/Sia


text:
/*
Created by YWT
2017.2.27 15:00
*/

/*无特殊情况,所有金额记录单位均为分(人民币)*/

#ifndef GLOBAL_H
#define GLOBAL_H
#define _CRT_SECURE_NO_WARNINGS

#include <io.h>
#include <dos.h>
#include <direct.h>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <Windows.h>

#include "CardInfo.h"
#include "RulesInfo.h"
#include "DateUtil.h"
#include "SystemLog.h"

#define WIN32_PLATFORM

#endif
#pragma once

repository: initializeZero/C-Project

repo_name: initializeZero/C-Project


text:
// mergejoin_mem_test contains tests for merge join when the data structures are
// all held in memory.

package relpipes

import (
	"sort"
	"testing"
)

// natural join fooBar[foo, bar] with barBaz[bar, baz] resulting in
// fooBarBaz[foo, bar, baz]
type joinExprChan struct {
	left  chan fooBar
	right chan barBaz
	res   chan fooBarBaz
}

// test implementation of MergeJoin for the foo,bar * bar, baz -> foo, bar, baz
// join.
func (e *joinExprChan) MergeJoin(lSize, rSize chan int, advanceLeft, advanceRight, done chan struct{}) (compare func() TupComp, combine func(i, j int)) {
	var (
		leftBlock  []fooBar
		rightBlock []barBaz
	)
	// start the left block reader
	go func() {

		var recs []fooBar
		rec, ok := <-e.left
		if !ok {
			// there was nothing to join on
			close(lSize)
			return
		}

		recs = append(recs, rec)
		sz := 1
		for rec := range e.left {
			if sz == 0 || rec.bar == recs[0].bar {
				recs = append(recs, rec)
				sz++
				continue
			}
			// wait to be told to update the slices
			<-advanceLeft

			// update the left slice
			leftBlock = recs
			// send the new size and then reset
			select {
			case lSize <- sz:
				sz = 1
				// clear the memory
				recs = []fooBar{rec}
			case <-done:
				// early cancellation
				return
			}
		}

		// send the last block

		// wait to be told to update the slices
		<-advanceLeft
		// update the left slice
		leftBlock = recs
		// send the new size and then reset

		select {
		case lSize <- sz:
		case <-done:
			// early cancellation
			return
		}
		<-advanceLeft
		close(lSize)
		<-advanceRight
		close(e.res)

	}()

	// start the right block reader
	go func() {

		var recs []barBaz

		rec, ok := <-e.right
		if !ok {
			// there was nothing to join on
			close(rSize)
			return
		}
		recs = append(recs, rec)

		sz := 1
		for rec := range e.right {
			if sz == 0 || rec.bar == recs[0].bar {
				recs = append(recs, rec)
				sz++
				continue
			}

			// wait to be told to update the slices
			<-advanceRight

			// update the left slice
			rightBlock = recs
			// send the new size and then reset
			select {
			case rSize <- sz:
				sz = 1
				// clear the memory
				recs = []barBaz{rec}
			case <-done:
				// early cancellation
				return
			}
		}

		// send the last block

		// wait to be told to update the slices
		<-advanceRight
		// update the left slice
		rightBlock = recs
		// send the new size and then reset

		select {
		case rSize <- sz:
		case <-done:
			// early cancellation
			return
		}
		<-advanceRight
		close(rSize)
	}()

	compare = func() TupComp {

		if leftBlock[0].bar == rightBlock[0].bar {
			return EQ
		}
		if leftBlock[0].bar < rightBlock[0].bar {
			return LT
		}
		return GT
	}
	combine = func(i, j int) {
		e.res <- fooBarBaz{leftBlock[i].foo, leftBlock[i].bar, rightBlock[j].baz}
	}
	return
}

func TestChanMergeJoin(t *testing.T) {

	l := []fooBar{
		{1, 1},
		{1, 2},
		{2, 3},
		{3, 3},
		{1, 4},
		{2, 5},
	}

	r := []barBaz{
		{1, 1},
		{1, 2},
		{2, 2},
		{3, 1},
		{3, 4},
		{4, 4},
	}

	e := &joinExprChan{left: fooBarChan(l, 1), right: barBazChan(r, 1), res: make(chan fooBarBaz, 1)}
	go Join(e)

	var resTable []fooBarBaz

	for rec := range e.res {
		resTable = append(resTable, rec)
	}

	expectTable := []fooBarBaz{
		{1, 1, 1},
		{1, 1, 2},
		{1, 2, 2},
		{2, 3, 1},
		{2, 3, 4},
		{3, 3, 1},
		{3, 3, 4},
		{1, 4, 4},
	}
	if resLen := len(resTable); resLen != len(expectTable) {
		t.Errorf("Join() results have len => %v, want %v", resLen, len(expectTable))
	}
	for i := range expectTable {
		if resTable[i] != expectTable[i] {
			t.Errorf("Join() result %d tuple => %v, want %v", i, resTable[i], expectTable[i])
		}
	}

	// test the various record counts used in the benchmarks
	var TT = []struct {
		j *joinExprChan
		N int
	}{
		{makeMergeJoinChan(10, 10, 3, 10, 10, 3), 19},
		{makeMergeJoinChan(32, 32, 9, 32, 32, 9), 30},
		{makeMergeJoinChan(100, 100, 30, 100, 100, 30), 90},
		{makeMergeJoinChan(316, 316, 90, 316, 316, 90), 291},
		{makeMergeJoinChan(1000, 1000, 300, 1000, 1000, 300), 1105},
		{makeMergeJoinChan(3162, 3162, 900, 3162, 3162, 900), 3247},
		{makeMergeJoinChan(10000, 10000, 3000, 10000, 10000, 3000), 9880},
	}
	for i, tt := range TT {
		if l := CountResChan(tt.j.res); l != tt.N {
			t.Errorf("%d Table length was => %d, want %d", i, l, tt.N)
		}
	}
}

// create a merge join for testing
func makeMergeJoinChan(leftN, leftFoo, leftBar, rightN, rightBar, rightBaz int) *joinExprChan {
	l := makeFooBar(leftN, leftFoo, leftBar)
	r := makeBarBaz(rightN, rightBar, rightBaz)
	sort.Sort(fooBarByBar(l))
	sort.Sort(barBazByBar(r))
	j := &joinExprChan{left: fooBarChan(l, 1), right: barBazChan(r, 1), res: make(chan fooBarBaz, 1)}
	go Join(j)
	return j
}

func BenchmarkMergeJoinChan10x10(b *testing.B) { // 19 results
	runMergeJoinChanBenchmark(b, 10, 10, 3, 10, 10, 3)
}
func BenchmarkMergeJoinChan32x32(b *testing.B) { // 30 results
	runMergeJoinChanBenchmark(b, 32, 32, 9, 32, 32, 9)
}
func BenchmarkMergeJoinChan100x100(b *testing.B) { // 90 results
	runMergeJoinChanBenchmark(b, 100, 100, 30, 100, 100, 30)
}
func BenchmarkMergeJoinChan316x316(b *testing.B) { // 291 results
	runMergeJoinChanBenchmark(b, 316, 316, 90, 316, 316, 90)
}
func BenchmarkMergeJoinChan1000x1000(b *testing.B) { // 1105 results
	runMergeJoinChanBenchmark(b, 1000, 1000, 300, 1000, 1000, 300)
}
func BenchmarkMergeJoinChan3162x3162(b *testing.B) { // 3247 results
	runMergeJoinChanBenchmark(b, 3162, 3162, 900, 3162, 3162, 900)
}
func BenchmarkMergeJoinChan10000x10000(b *testing.B) { // as many as 9880 results
	runMergeJoinChanBenchmark(b, 10000, 10000, 3000, 10000, 10000, 3000)
}

func EmptyResChan(res chan fooBarBaz) {
	for _ = range res {
	}
}

func CountResChan(res chan fooBarBaz) (i int) {
	for _ = range res {
		i++
	}
	return
}

func runMergeJoinChanBenchmark(b *testing.B, leftN, leftFoo, leftBar, rightN, rightBar, rightBaz int) {
	l := makeFooBar(leftN, leftFoo, leftBar)
	r := makeBarBaz(rightN, rightBar, rightBaz)
	sort.Sort(fooBarByBar(l))
	sort.Sort(barBazByBar(r))
	b.StopTimer()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ex := &joinExprChan{left: fooBarChan(l, 1), right: barBazChan(r, 1), res: make(chan fooBarBaz, 1)}
		b.StartTimer()
		go Join(ex)
		EmptyResChan(ex.res)
	}
}

repository: jonlawlor/relpipes

repo_name: jonlawlor/relpipes


text:
package mdocker_test

import (
	"testing"

	"github.com/fsouza/go-dockerclient"
	"github.com/mistifyio/mistify-agent-docker"
	"github.com/mistifyio/mistify-agent/rpc"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
)

type MDockerTestSuite struct {
	APITestSuite
}

func TestMDockerTestSuite(t *testing.T) {
	suite.Run(t, new(MDockerTestSuite))
}

func (s *MDockerTestSuite) TestNew() {
	tests := []struct {
		description string
		endpoint    string
		tlsCertPath string
		expectedErr bool
	}{
		{"missing endpoint",
			"", "", true},
		{"bad endpoint",
			"unix:///dev/null", "", true},
		{"valid endpoint",
			"unix:///var/run/docker.sock", "", false},
		{"bad tls path",
			"unix:///var/run/docker.sock", "/dev/null", true},
	}

	for _, test := range tests {
		msg := testMsgFunc(test.description)

		md, err := mdocker.New(test.endpoint, s.ImageService, test.tlsCertPath)
		if test.expectedErr {
			s.Error(err, msg("should fail"))
			s.Nil(md, msg("failure shouldn't return a client"))
		} else {
			s.NoError(err, msg("should succeed"))
			s.NotNil(md, msg("success should return a client"))
		}
	}
}

func (s *MDockerTestSuite) TestRequestOpts() {
	var listOpts docker.ListContainersOptions
	request := &rpc.ContainerRequest{
		Opts: docker.ListContainersOptions{
			Limit: 5,
		},
	}
	s.NoError(s.MDocker.RequestOpts(request, &listOpts))
	s.True(assert.ObjectsAreEqualValues(request.Opts, listOpts))

	var saveOpts docker.CommitContainerOptions
	request = &rpc.ContainerRequest{
		Opts: docker.CommitContainerOptions{
			Author: "asdf",
		},
	}
	s.NoError(s.MDocker.RequestOpts(request, &saveOpts))
	s.True(assert.ObjectsAreEqualValues(request.Opts, saveOpts))
}

func (s *MDockerTestSuite) TestGetInfo() {
	request := &struct{}{}
	response := &docker.DockerInfo{}
	s.NoError(s.Client.Do("MDocker.GetInfo", request, response))
	s.NotEmpty(response.ID)
}

repository: mistifyio/mistify-agent-docker

repo_name: mistifyio/mistify-agent-docker


text:
@inproceedings{Remmen.2016,
 author = {Remmen, Peter and Lauster, Moritz and Mans, Michael and Osterhage, Tanja and M{\"u}ller, Dirk},
 title = {CityGML Import and Export for Dynamic Building Performance Simulation in Modelica},
 pages = {329--336},
 booktitle = {Building Simulation and Optimization conference (BSO16)},
 editor = {Hamza, N. and Unerdwood, C.},
 month = sept,
 year = {2016},
 publisher = {Newcastle University},
 venue = {Newcastle upon Tyne, England},
 isbn = {978-0-7017-0254-0},
 }

repository: PRemmen/TEASER

repo_name: PRemmen/TEASER

gha_license_id: NOASSERTION

gha_language: Python


text:
@inproceedings{zmigrod+al.emnlp21,
 title = {Efficient Sampling of Dependency Structure},
 author = {Zmigrod, Ran and
Vieira, Tim and
Cotterell, Ryan},
 booktitle = {Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing},
 month = {November},
 year = {2021},
 publisher = {Association for Computational Linguistics},
 url = {https://arxiv.org/abs/2109.06521},
 arxiv = {https://arxiv.org/abs/2109.06521},
 abstract = {Probabilistic distributions over spanning trees in directed graphs are a fundamental model of dependency structure in natural language processing, syntactic dependency trees. In NLP, dependency trees often have an additional root constraint: only one edge may emanate from the root. However, no sampling algorithm has been presented in the literature to account for this additional constraint. In this paper, we adapt two spanning tree sampling algorithms to faithfully sample dependency trees from a graph subject to the root constraint. Wilson (1996)'s sampling algorithm has a running time of O(H) where H is the mean hitting time of the graph. Colbourn (1996)'s sampling algorithm has a running time of O(N^3), which is often greater than the mean hitting time of a directed graph. Additionally, we build upon Colbourn's algorithm and present a novel extension that can sample K trees without replacement in O(K N^3 + K^2 N) time. To the best of our knowledge, no algorithm has been given for sampling spanning trees without replacement from a directed graph.}
}

repository: rycolab/website

repo_name: rycolab/website


text:
package migrations

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"math/big"
	"time"
)

type Migration032 struct {
	AM01
}

// AM01 migrates the listing and order data to use higher precision.
type AM01 struct{}

var AM01UpVer = 33
var AM01DownVer = 32

type AM01_TransactionRecord_beforeMigration struct {
	Txid      string
	Index     uint32
	Value     int64
	Address   string
	Spent     bool
	Timestamp time.Time
}

type AM01_TransactionRecord_afterMigration struct {
	Txid      string
	Index     uint32
	Value     big.Int
	Address   string
	Spent     bool
	Timestamp time.Time
}

type AM01_record struct {
	orderID                string
	coin                   string
	unmigratedTransactions []AM01_TransactionRecord_beforeMigration
	migratedTransactions   []AM01_TransactionRecord_afterMigration
}

func (AM01) Up(repoPath string, dbPassword string, testnet bool) (err error) {
	db, err := OpenDB(repoPath, dbPassword, testnet)
	if err != nil {
		return fmt.Errorf("opening db: %s", err.Error())
	}
	saleMigrationRecords, err := AM01_extractRecords(db, "select orderID, transactions, paymentCoin from sales;", false)
	if err != nil {
		return fmt.Errorf("get sales rows: %s", err.Error())
	}
	purchaseMigrationRecords, err := AM01_extractRecords(db, "select orderID, transactions, paymentCoin from purchases;", false)
	if err != nil {
		return fmt.Errorf("get purchase rows: %s", err.Error())
	}

	if err := withTransaction(db, func(tx *sql.Tx) error {
		err := AM01_updateRecords(tx, saleMigrationRecords, "update sales set transactions = ? where orderID = ?", testnet, false)
		if err != nil {
			return fmt.Errorf("update sales: %s", err.Error())
		}
		err = AM01_updateRecords(tx, purchaseMigrationRecords, "update purchases set transactions = ? where orderID = ?", testnet, false)
		if err != nil {
			return fmt.Errorf("update purchases: %s", err.Error())
		}
		return nil
	}); err != nil {
		return fmt.Errorf("migrating up: %s", err.Error())
	}

	return writeRepoVer(repoPath, AM01UpVer)
}

func (AM01) Down(repoPath string, dbPassword string, testnet bool) (err error) {
	db, err := OpenDB(repoPath, dbPassword, testnet)
	if err != nil {
		return fmt.Errorf("opening db: %s", err.Error())
	}
	saleMigrationRecords, err := AM01_extractRecords(db, "select orderID, transactions, paymentCoin from sales;", true)
	if err != nil {
		return fmt.Errorf("get sales rows: %s", err.Error())
	}
	purchaseMigrationRecords, err := AM01_extractRecords(db, "select orderID, transactions, paymentCoin from purchases;", true)
	if err != nil {
		return fmt.Errorf("get purchase rows: %s", err.Error())
	}

	if err := withTransaction(db, func(tx *sql.Tx) error {
		err := AM01_updateRecords(tx, saleMigrationRecords, "update sales set transactions = ? where orderID = ?", testnet, true)
		if err != nil {
			return fmt.Errorf("update sales: %s", err.Error())
		}
		err = AM01_updateRecords(tx, purchaseMigrationRecords, "update purchases set transactions = ? where orderID = ?", testnet, true)
		if err != nil {
			return fmt.Errorf("update purchases: %s", err.Error())
		}
		return nil
	}); err != nil {
		return fmt.Errorf("migrating down: %s", err.Error())
	}

	return writeRepoVer(repoPath, AM01DownVer)
}

func AM01_extractRecords(db *sql.DB, query string, migrateDown bool) ([]AM01_record, error) {
	var (
		results   = make([]AM01_record, 0)
		rows, err = db.Query(query)
	)
	if err != nil {
		return nil, fmt.Errorf("selecting rows: %s", err.Error())
	}
	defer rows.Close()
	for rows.Next() {
		var (
			serializedTransactions sql.NullString
			r                      = AM01_record{}
		)
		if err := rows.Scan(&r.orderID, &serializedTransactions, &r.coin); err != nil {
			return nil, fmt.Errorf("scanning rows: %s", err.Error())
		}
		if !serializedTransactions.Valid {
			continue
		}
		if migrateDown {
			if err := json.Unmarshal([]byte(serializedTransactions.String), &r.migratedTransactions); err != nil {
				return nil, fmt.Errorf("unmarshal migrated transactions: %s", err.Error())
			}
		} else {
			if err := json.Unmarshal([]byte(serializedTransactions.String), &r.unmigratedTransactions); err != nil {
				return nil, fmt.Errorf("unmarshal unmigrated transactions: %s", err.Error())
			}
		}
		results = append(results, r)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterating rows: %s", err.Error())
	}
	return results, nil
}

func AM01_updateRecords(tx *sql.Tx, records []AM01_record, query string, testMode bool, migrateDown bool) error {
	var update, err = tx.Prepare(query)
	if err != nil {
		return fmt.Errorf("prepare update statement: %s", err.Error())
	}
	defer update.Close()
	for _, beforeRecord := range records {

		if migrateDown {
			var migratedTransactionRecords = make([]AM01_TransactionRecord_beforeMigration, 0)
			for _, beforeTx := range beforeRecord.migratedTransactions {
				var migratedRecord = AM01_TransactionRecord_beforeMigration{
					Txid:      beforeTx.Txid,
					Index:     beforeTx.Index,
					Value:     beforeTx.Value.Int64(),
					Spent:     beforeTx.Spent,
					Timestamp: beforeTx.Timestamp,
					Address:   beforeTx.Address,
				}
				migratedTransactionRecords = append(migratedTransactionRecords, migratedRecord)
			}
			serializedTransactionRecords, err := json.Marshal(migratedTransactionRecords)
			if err != nil {
				return fmt.Errorf("marshal transactions: %s", err.Error())
			}
			if _, err := update.Exec(string(serializedTransactionRecords), beforeRecord.orderID); err != nil {
				return fmt.Errorf("updating record: %s", err.Error())
			}
		} else {
			var migratedTransactionRecords = make([]AM01_TransactionRecord_afterMigration, 0)
			for _, beforeTx := range beforeRecord.unmigratedTransactions {
				n := big.NewInt(beforeTx.Value)
				var migratedRecord = AM01_TransactionRecord_afterMigration{
					Txid:      beforeTx.Txid,
					Index:     beforeTx.Index,
					Value:     *n,
					Spent:     beforeTx.Spent,
					Timestamp: beforeTx.Timestamp,
					Address:   beforeTx.Address,
				}
				migratedTransactionRecords = append(migratedTransactionRecords, migratedRecord)
			}
			serializedTransactionRecords, err := json.Marshal(migratedTransactionRecords)
			if err != nil {
				return fmt.Errorf("marhsal transactions: %s", err.Error())
			}
			if _, err := update.Exec(string(serializedTransactionRecords), beforeRecord.orderID); err != nil {
				return fmt.Errorf("updating record: %s", err.Error())
			}
		}

	}
	return nil
}

repository: developertask/openbazaar-go

repo_name: developertask/openbazaar-go


text:
TARGET_ARCH := "${SECONDARY_TARGET_ARCH}"
MACHINEOVERRIDES := "${SECONDARY_TARGET_ARCH}"

require recipes-core/meta/external-arm-sdk-toolchain.bb

repository: rcn-ee/meta-arago

repo_name: rcn-ee/meta-arago

extension: bb


text:
PR = "r2"

MAP_NAME = "Berlin"
require om-maps.inc

MAP_FN = "om-maps-berlin-${PV}.eet"
MAP_VER = "${PV}"


text:
// Source : https://leetcode.com/problems/search-a-2d-matrix-ii/
// Author : Ke Li
// Date   : 2016-10-31

// Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the
// following properties:
//
// Integers in each row are sorted in ascending from left to right.
// Integers in each column are sorted in ascending from top to bottom.
//
// For example,
//
// Consider the following matrix:
//
// [
// [1,   4,  7, 11, 15],
// [2,   5,  8, 12, 19],
// [3,   6,  9, 16, 22],
// [10, 13, 14, 17, 24],
// [18, 21, 23, 26, 30]
// ]
//
// Given target = 5, return true.
// Given target = 20, return false.
//
package main

func searchMatrix(matrix [][]int, target int) bool {
	r, c := 0, len(matrix[0])-1

	for r < len(matrix) && c >= 0 {
		if matrix[r][c] == target {
			return true
		} else if matrix[r][c] < target {
			r++
		} else if matrix[r][c] > target {
			c--
		} else {
			return false
		}
	}
	return false
}

func main() {

}

repository: liketic/leetcode-go

repo_name: liketic/leetcode-go


text:
DESCRIPTION = "Starling audio player for GPE"
SECTION = "gpe/multimedia"
PRIORITY = "optional"
LICENSE = "GPL"
DEPENDS = "gtk+ libgpewidget gstreamer gst-plugins-good gst-plugins-bad esound sqlite3 libsoup"
RDEPENDS = "esd \
        gst-plugin-audioconvert \
        gst-plugin-esd \
        gst-plugin-typefindfunctions \
        gst-plugin-decodebin \
        gst-plugin-volume"
RRECOMMENDS = "gst-plugin-mad \
        gst-plugin-modplug \
        gst-plugin-ivorbis \
        gst-plugin-tcp"

PV = "0.2+svn${SRCDATE}"

inherit gpe autotools

SRC_URI = "${GPE_EXTRA_SVN}"

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

repository: jdegges/gumstix-pip-oe

repo_name: jdegges/gumstix-pip-oe


text:
package importer

import (
	"go/token"
	"strconv"
)

func disambiguate(name string, collides func(string) bool) string {
	if !token.Lookup(name).IsKeyword() && !collides(name) {
		return name
	}
	buf := []byte(name)
	if len(buf) > 0 && buf[len(buf)-1] >= '0' && buf[len(buf)-1] <= '9' {
		buf = append(buf, '_')
	}
	base := len(buf)
	for n := 2; ; n++ {
		buf = strconv.AppendInt(buf[:base], int64(n), 10)
		sbuf := string(buf)
		if !token.Lookup(sbuf).IsKeyword() && !collides(sbuf) {
			return sbuf
		}
	}
}


text:
/************************************************************************************************************
 *                                                                                *
 *                                ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo         *
 *                             o                                                                            *
 *                          o                                                                               *
 *                        o                                                                                *
 *                      o                                                                                *
 *                     o       ooooooo       ooooooo    o         o      oo                                 *
 *    o              o       o        o     o       o   o         o     o   o                               *
 *      o           o       o          o   o         o  o         o    o      o                             *
 *        o        o       o           o   o         o  o         o    o        o                           *
 *         o      o        o      oooo     o         o  o         o   o           o                         *
 *          o    o          o              o         o  o         o   o           o                         *
 *           o  o            o             o         o  o o      o   o          o                           *
 *            oo              oooooooo    o         o   o  oooooo   o      oooo                             *
 *                                                     o                                                    *
 *                                                     o                                                    *
 *                                                    o                            o                        *
 *                                                    o            o      oooo     o   o      oooo          *
 *                                                   o             o         o    o    o         o          *
 *                                                   o            o       ooo     o   o       ooo           *
 *                                                               o       o       o   o          o           *
 *                                                               ooooo   oooo    o   ooooo  oooo            *
 *                                                                              o                           *
 *                                                                                *
 ************************************************************************************************************
 *                                                                                *
 * Author: CS Systemes d'Information  (France)                                                              *
 *                                                                                *
 ************************************************************************************************************
 * HISTORIQUE                                                                                *
 *                                                                                *
 * VERSION : 1-0-0 : <TypeFT> : <NumFT> : 25 mai 2010 : Creation
 *                                                                                *
 * FIN-HISTORIQUE                                                                                *
 *                                                                                *
 * $Id$
 *                                                                                *
 ************************************************************************************************************/
#include "Verbeux.h"

namespace Intersecteur
{
	Verbeux::Verbeux() : _outstream(NULL), _errstream(NULL)
	{

	}

	Verbeux::~Verbeux()
	{

	}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// Positionne les streams de sortie et d'erreur
	////////////////////////////////////////////////////////////////////////////////////////////////
	void Verbeux::SetStreams(std::ostream * outstream, std::ostream * errstream)
	{
		_outstream = outstream;
		_errstream = errstream;
	}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// Positionne une erreur et l'affiche
	////////////////////////////////////////////////////////////////////////////////////////////////
    void Verbeux::SetError(const std::string & method, const std::string & erreur)
	{
		if ( _errstream ) *_errstream << "Erreur dans la methode " << method <<  " : " << erreur << std::endl;
	}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// Positionne un warning et l'affiche. TNT 030305
	////////////////////////////////////////////////////////////////////////////////////////////////
    void Verbeux::SetWarning(const std::string & method, const std::string & erreur)
	{
		if ( _errstream ) *_errstream << "Avertissement dans la methode " << method <<  " : " << erreur << std::endl;
	}
}

branch_name: refs/heads/develop


text:
require totalcross.inc

DESCRIPTION = "TotalCross Laucher Machine"

S = "${WORKDIR}/git/TotalCrossVM/src"
B = "${S}"

CXXFLAGS_append = " -I${STAGING_INCDIR}/skia/"
CFLAGS_append = " -I${STAGING_INCDIR}/skia/"

EXTRA_OEMAKE += "\
    BLDDIR='${B}' \
    SDLDIR='${STAGING_LIBDIR}' \
    SDL_INC='${STAGING_INCDIR}/SDL2' \
    SKIADIR='${STAGING_INCDIR}/skia/include' \
    SRCDIR='${S}/launchers/linux' \
    LIBS='-L. -lskia -lstdc++ -lpthread -lEGL -lfontconfig $(SDLDIR)/libSDL2main.a' \
"

do_configure() {
    cp ${S}/../builders/gcc-linux-arm/launcher/Makefile .
}

do_compile() {
    oe_runmake
}

do_install() {
    install -Dm 0755 ${B}/bin/Launcher ${D}${libdir}/totalcross/${PN}
}

FILES_${PN} += "${libdir}/totalcross/"

# FIXME: This is a workaround as next release uses CMake and doesn't make sense
# to spend too much time on this.
INSANE_SKIP_${PN} = "ldflags"

repository: TotalCross/meta-totalcross

repo_name: TotalCross/meta-totalcross