repository_name
stringlengths
7
107
function_path
stringlengths
4
190
function_identifier
stringlengths
1
236
language
stringclasses
1 value
function
stringlengths
9
647k
docstring
stringlengths
5
488k
function_url
stringlengths
71
285
context
stringlengths
0
2.51M
license
stringclasses
5 values
adampointer/go-deribit
client/operations/get_public_get_contract_size_responses.go
NewGetPublicGetContractSizeOK
go
func NewGetPublicGetContractSizeOK() *GetPublicGetContractSizeOK { return &GetPublicGetContractSizeOK{} }
NewGetPublicGetContractSizeOK creates a GetPublicGetContractSizeOK with default headers values
https://github.com/adampointer/go-deribit/blob/e119c5d4099de3ab6ac5d8f1bf42897028711a91/client/operations/get_public_get_contract_size_responses.go#L41-L43
package operations import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" models "github.com/adampointer/go-deribit/models" ) type GetPublicGetContractSizeReader struct { formats strfmt.Registry } func (o *GetPublicGetContractSizeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetPublicGetContractSizeOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } }
MIT License
ory/keto
internal/httpclient/client/read/post_check_parameters.go
SetPayload
go
func (o *PostCheckParams) SetPayload(payload *models.RelationQuery) { o.Payload = payload }
SetPayload adds the payload to the post check params
https://github.com/ory/keto/blob/0c8ff543436512edd00217079252227df8f7cb7f/internal/httpclient/client/read/post_check_parameters.go#L127-L129
package read import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/ory/keto/internal/httpclient/models" ) func NewPostCheckParams() *PostCheckParams { return &PostCheckParams{ timeout: cr.DefaultTimeout, } } func NewPostCheckParamsWithTimeout(timeout time.Duration) *PostCheckParams { return &PostCheckParams{ timeout: timeout, } } func NewPostCheckParamsWithContext(ctx context.Context) *PostCheckParams { return &PostCheckParams{ Context: ctx, } } func NewPostCheckParamsWithHTTPClient(client *http.Client) *PostCheckParams { return &PostCheckParams{ HTTPClient: client, } } type PostCheckParams struct { Payload *models.RelationQuery timeout time.Duration Context context.Context HTTPClient *http.Client } func (o *PostCheckParams) WithDefaults() *PostCheckParams { o.SetDefaults() return o } func (o *PostCheckParams) SetDefaults() { } func (o *PostCheckParams) WithTimeout(timeout time.Duration) *PostCheckParams { o.SetTimeout(timeout) return o } func (o *PostCheckParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } func (o *PostCheckParams) WithContext(ctx context.Context) *PostCheckParams { o.SetContext(ctx) return o } func (o *PostCheckParams) SetContext(ctx context.Context) { o.Context = ctx } func (o *PostCheckParams) WithHTTPClient(client *http.Client) *PostCheckParams { o.SetHTTPClient(client) return o } func (o *PostCheckParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } func (o *PostCheckParams) WithPayload(payload *models.RelationQuery) *PostCheckParams { o.SetPayload(payload) return o }
Apache License 2.0
plaid/plaid-go
plaid/model_w2.go
SetRetirementPlanNil
go
func (o *W2) SetRetirementPlanNil() { o.RetirementPlan.Set(nil) }
SetRetirementPlanNil sets the value for RetirementPlan to be an explicit nil
https://github.com/plaid/plaid-go/blob/c2a20f380d37eecba36138b04e14f540b59cc22a/plaid/model_w2.go#L796-L798
package plaid import ( "encoding/json" ) type W2 struct { Employer *PaystubEmployer `json:"employer,omitempty"` Employee *Employee `json:"employee,omitempty"` TaxYear NullableString `json:"tax_year,omitempty"` EmployerIdNumber NullableString `json:"employer_id_number,omitempty"` WagesTipsOtherComp NullableString `json:"wages_tips_other_comp,omitempty"` FederalIncomeTaxWithheld NullableString `json:"federal_income_tax_withheld,omitempty"` SocialSecurityWages NullableString `json:"social_security_wages,omitempty"` SocialSecurityTaxWithheld NullableString `json:"social_security_tax_withheld,omitempty"` MedicareWagesAndTips NullableString `json:"medicare_wages_and_tips,omitempty"` MedicareTaxWithheld NullableString `json:"medicare_tax_withheld,omitempty"` SocialSecurityTips NullableString `json:"social_security_tips,omitempty"` AllocatedTips NullableString `json:"allocated_tips,omitempty"` Box9 NullableString `json:"box_9,omitempty"` DependentCareBenefits NullableString `json:"dependent_care_benefits,omitempty"` NonqualifiedPlans NullableString `json:"nonqualified_plans,omitempty"` Box12 *[]W2Box12 `json:"box_12,omitempty"` StatutoryEmployee NullableString `json:"statutory_employee,omitempty"` RetirementPlan NullableString `json:"retirement_plan,omitempty"` ThirdPartySickPay NullableString `json:"third_party_sick_pay,omitempty"` Other NullableString `json:"other,omitempty"` StateAndLocalWages *[]W2StateAndLocalWages `json:"state_and_local_wages,omitempty"` AdditionalProperties map[string]interface{} } type _W2 W2 func NewW2() *W2 { this := W2{} return &this } func NewW2WithDefaults() *W2 { this := W2{} return &this } func (o *W2) GetEmployer() PaystubEmployer { if o == nil || o.Employer == nil { var ret PaystubEmployer return ret } return *o.Employer } func (o *W2) GetEmployerOk() (*PaystubEmployer, bool) { if o == nil || o.Employer == nil { return nil, false } return o.Employer, true } func (o *W2) HasEmployer() bool { if o != nil && o.Employer != nil { return true } return false } func (o *W2) SetEmployer(v PaystubEmployer) { o.Employer = &v } func (o *W2) GetEmployee() Employee { if o == nil || o.Employee == nil { var ret Employee return ret } return *o.Employee } func (o *W2) GetEmployeeOk() (*Employee, bool) { if o == nil || o.Employee == nil { return nil, false } return o.Employee, true } func (o *W2) HasEmployee() bool { if o != nil && o.Employee != nil { return true } return false } func (o *W2) SetEmployee(v Employee) { o.Employee = &v } func (o *W2) GetTaxYear() string { if o == nil || o.TaxYear.Get() == nil { var ret string return ret } return *o.TaxYear.Get() } func (o *W2) GetTaxYearOk() (*string, bool) { if o == nil { return nil, false } return o.TaxYear.Get(), o.TaxYear.IsSet() } func (o *W2) HasTaxYear() bool { if o != nil && o.TaxYear.IsSet() { return true } return false } func (o *W2) SetTaxYear(v string) { o.TaxYear.Set(&v) } func (o *W2) SetTaxYearNil() { o.TaxYear.Set(nil) } func (o *W2) UnsetTaxYear() { o.TaxYear.Unset() } func (o *W2) GetEmployerIdNumber() string { if o == nil || o.EmployerIdNumber.Get() == nil { var ret string return ret } return *o.EmployerIdNumber.Get() } func (o *W2) GetEmployerIdNumberOk() (*string, bool) { if o == nil { return nil, false } return o.EmployerIdNumber.Get(), o.EmployerIdNumber.IsSet() } func (o *W2) HasEmployerIdNumber() bool { if o != nil && o.EmployerIdNumber.IsSet() { return true } return false } func (o *W2) SetEmployerIdNumber(v string) { o.EmployerIdNumber.Set(&v) } func (o *W2) SetEmployerIdNumberNil() { o.EmployerIdNumber.Set(nil) } func (o *W2) UnsetEmployerIdNumber() { o.EmployerIdNumber.Unset() } func (o *W2) GetWagesTipsOtherComp() string { if o == nil || o.WagesTipsOtherComp.Get() == nil { var ret string return ret } return *o.WagesTipsOtherComp.Get() } func (o *W2) GetWagesTipsOtherCompOk() (*string, bool) { if o == nil { return nil, false } return o.WagesTipsOtherComp.Get(), o.WagesTipsOtherComp.IsSet() } func (o *W2) HasWagesTipsOtherComp() bool { if o != nil && o.WagesTipsOtherComp.IsSet() { return true } return false } func (o *W2) SetWagesTipsOtherComp(v string) { o.WagesTipsOtherComp.Set(&v) } func (o *W2) SetWagesTipsOtherCompNil() { o.WagesTipsOtherComp.Set(nil) } func (o *W2) UnsetWagesTipsOtherComp() { o.WagesTipsOtherComp.Unset() } func (o *W2) GetFederalIncomeTaxWithheld() string { if o == nil || o.FederalIncomeTaxWithheld.Get() == nil { var ret string return ret } return *o.FederalIncomeTaxWithheld.Get() } func (o *W2) GetFederalIncomeTaxWithheldOk() (*string, bool) { if o == nil { return nil, false } return o.FederalIncomeTaxWithheld.Get(), o.FederalIncomeTaxWithheld.IsSet() } func (o *W2) HasFederalIncomeTaxWithheld() bool { if o != nil && o.FederalIncomeTaxWithheld.IsSet() { return true } return false } func (o *W2) SetFederalIncomeTaxWithheld(v string) { o.FederalIncomeTaxWithheld.Set(&v) } func (o *W2) SetFederalIncomeTaxWithheldNil() { o.FederalIncomeTaxWithheld.Set(nil) } func (o *W2) UnsetFederalIncomeTaxWithheld() { o.FederalIncomeTaxWithheld.Unset() } func (o *W2) GetSocialSecurityWages() string { if o == nil || o.SocialSecurityWages.Get() == nil { var ret string return ret } return *o.SocialSecurityWages.Get() } func (o *W2) GetSocialSecurityWagesOk() (*string, bool) { if o == nil { return nil, false } return o.SocialSecurityWages.Get(), o.SocialSecurityWages.IsSet() } func (o *W2) HasSocialSecurityWages() bool { if o != nil && o.SocialSecurityWages.IsSet() { return true } return false } func (o *W2) SetSocialSecurityWages(v string) { o.SocialSecurityWages.Set(&v) } func (o *W2) SetSocialSecurityWagesNil() { o.SocialSecurityWages.Set(nil) } func (o *W2) UnsetSocialSecurityWages() { o.SocialSecurityWages.Unset() } func (o *W2) GetSocialSecurityTaxWithheld() string { if o == nil || o.SocialSecurityTaxWithheld.Get() == nil { var ret string return ret } return *o.SocialSecurityTaxWithheld.Get() } func (o *W2) GetSocialSecurityTaxWithheldOk() (*string, bool) { if o == nil { return nil, false } return o.SocialSecurityTaxWithheld.Get(), o.SocialSecurityTaxWithheld.IsSet() } func (o *W2) HasSocialSecurityTaxWithheld() bool { if o != nil && o.SocialSecurityTaxWithheld.IsSet() { return true } return false } func (o *W2) SetSocialSecurityTaxWithheld(v string) { o.SocialSecurityTaxWithheld.Set(&v) } func (o *W2) SetSocialSecurityTaxWithheldNil() { o.SocialSecurityTaxWithheld.Set(nil) } func (o *W2) UnsetSocialSecurityTaxWithheld() { o.SocialSecurityTaxWithheld.Unset() } func (o *W2) GetMedicareWagesAndTips() string { if o == nil || o.MedicareWagesAndTips.Get() == nil { var ret string return ret } return *o.MedicareWagesAndTips.Get() } func (o *W2) GetMedicareWagesAndTipsOk() (*string, bool) { if o == nil { return nil, false } return o.MedicareWagesAndTips.Get(), o.MedicareWagesAndTips.IsSet() } func (o *W2) HasMedicareWagesAndTips() bool { if o != nil && o.MedicareWagesAndTips.IsSet() { return true } return false } func (o *W2) SetMedicareWagesAndTips(v string) { o.MedicareWagesAndTips.Set(&v) } func (o *W2) SetMedicareWagesAndTipsNil() { o.MedicareWagesAndTips.Set(nil) } func (o *W2) UnsetMedicareWagesAndTips() { o.MedicareWagesAndTips.Unset() } func (o *W2) GetMedicareTaxWithheld() string { if o == nil || o.MedicareTaxWithheld.Get() == nil { var ret string return ret } return *o.MedicareTaxWithheld.Get() } func (o *W2) GetMedicareTaxWithheldOk() (*string, bool) { if o == nil { return nil, false } return o.MedicareTaxWithheld.Get(), o.MedicareTaxWithheld.IsSet() } func (o *W2) HasMedicareTaxWithheld() bool { if o != nil && o.MedicareTaxWithheld.IsSet() { return true } return false } func (o *W2) SetMedicareTaxWithheld(v string) { o.MedicareTaxWithheld.Set(&v) } func (o *W2) SetMedicareTaxWithheldNil() { o.MedicareTaxWithheld.Set(nil) } func (o *W2) UnsetMedicareTaxWithheld() { o.MedicareTaxWithheld.Unset() } func (o *W2) GetSocialSecurityTips() string { if o == nil || o.SocialSecurityTips.Get() == nil { var ret string return ret } return *o.SocialSecurityTips.Get() } func (o *W2) GetSocialSecurityTipsOk() (*string, bool) { if o == nil { return nil, false } return o.SocialSecurityTips.Get(), o.SocialSecurityTips.IsSet() } func (o *W2) HasSocialSecurityTips() bool { if o != nil && o.SocialSecurityTips.IsSet() { return true } return false } func (o *W2) SetSocialSecurityTips(v string) { o.SocialSecurityTips.Set(&v) } func (o *W2) SetSocialSecurityTipsNil() { o.SocialSecurityTips.Set(nil) } func (o *W2) UnsetSocialSecurityTips() { o.SocialSecurityTips.Unset() } func (o *W2) GetAllocatedTips() string { if o == nil || o.AllocatedTips.Get() == nil { var ret string return ret } return *o.AllocatedTips.Get() } func (o *W2) GetAllocatedTipsOk() (*string, bool) { if o == nil { return nil, false } return o.AllocatedTips.Get(), o.AllocatedTips.IsSet() } func (o *W2) HasAllocatedTips() bool { if o != nil && o.AllocatedTips.IsSet() { return true } return false } func (o *W2) SetAllocatedTips(v string) { o.AllocatedTips.Set(&v) } func (o *W2) SetAllocatedTipsNil() { o.AllocatedTips.Set(nil) } func (o *W2) UnsetAllocatedTips() { o.AllocatedTips.Unset() } func (o *W2) GetBox9() string { if o == nil || o.Box9.Get() == nil { var ret string return ret } return *o.Box9.Get() } func (o *W2) GetBox9Ok() (*string, bool) { if o == nil { return nil, false } return o.Box9.Get(), o.Box9.IsSet() } func (o *W2) HasBox9() bool { if o != nil && o.Box9.IsSet() { return true } return false } func (o *W2) SetBox9(v string) { o.Box9.Set(&v) } func (o *W2) SetBox9Nil() { o.Box9.Set(nil) } func (o *W2) UnsetBox9() { o.Box9.Unset() } func (o *W2) GetDependentCareBenefits() string { if o == nil || o.DependentCareBenefits.Get() == nil { var ret string return ret } return *o.DependentCareBenefits.Get() } func (o *W2) GetDependentCareBenefitsOk() (*string, bool) { if o == nil { return nil, false } return o.DependentCareBenefits.Get(), o.DependentCareBenefits.IsSet() } func (o *W2) HasDependentCareBenefits() bool { if o != nil && o.DependentCareBenefits.IsSet() { return true } return false } func (o *W2) SetDependentCareBenefits(v string) { o.DependentCareBenefits.Set(&v) } func (o *W2) SetDependentCareBenefitsNil() { o.DependentCareBenefits.Set(nil) } func (o *W2) UnsetDependentCareBenefits() { o.DependentCareBenefits.Unset() } func (o *W2) GetNonqualifiedPlans() string { if o == nil || o.NonqualifiedPlans.Get() == nil { var ret string return ret } return *o.NonqualifiedPlans.Get() } func (o *W2) GetNonqualifiedPlansOk() (*string, bool) { if o == nil { return nil, false } return o.NonqualifiedPlans.Get(), o.NonqualifiedPlans.IsSet() } func (o *W2) HasNonqualifiedPlans() bool { if o != nil && o.NonqualifiedPlans.IsSet() { return true } return false } func (o *W2) SetNonqualifiedPlans(v string) { o.NonqualifiedPlans.Set(&v) } func (o *W2) SetNonqualifiedPlansNil() { o.NonqualifiedPlans.Set(nil) } func (o *W2) UnsetNonqualifiedPlans() { o.NonqualifiedPlans.Unset() } func (o *W2) GetBox12() []W2Box12 { if o == nil || o.Box12 == nil { var ret []W2Box12 return ret } return *o.Box12 } func (o *W2) GetBox12Ok() (*[]W2Box12, bool) { if o == nil || o.Box12 == nil { return nil, false } return o.Box12, true } func (o *W2) HasBox12() bool { if o != nil && o.Box12 != nil { return true } return false } func (o *W2) SetBox12(v []W2Box12) { o.Box12 = &v } func (o *W2) GetStatutoryEmployee() string { if o == nil || o.StatutoryEmployee.Get() == nil { var ret string return ret } return *o.StatutoryEmployee.Get() } func (o *W2) GetStatutoryEmployeeOk() (*string, bool) { if o == nil { return nil, false } return o.StatutoryEmployee.Get(), o.StatutoryEmployee.IsSet() } func (o *W2) HasStatutoryEmployee() bool { if o != nil && o.StatutoryEmployee.IsSet() { return true } return false } func (o *W2) SetStatutoryEmployee(v string) { o.StatutoryEmployee.Set(&v) } func (o *W2) SetStatutoryEmployeeNil() { o.StatutoryEmployee.Set(nil) } func (o *W2) UnsetStatutoryEmployee() { o.StatutoryEmployee.Unset() } func (o *W2) GetRetirementPlan() string { if o == nil || o.RetirementPlan.Get() == nil { var ret string return ret } return *o.RetirementPlan.Get() } func (o *W2) GetRetirementPlanOk() (*string, bool) { if o == nil { return nil, false } return o.RetirementPlan.Get(), o.RetirementPlan.IsSet() } func (o *W2) HasRetirementPlan() bool { if o != nil && o.RetirementPlan.IsSet() { return true } return false } func (o *W2) SetRetirementPlan(v string) { o.RetirementPlan.Set(&v) }
MIT License
openshift-metal3/terraform-provider-ironic
vendor/github.com/gophercloud/gophercloud/openstack/baremetal/v1/nodes/results.go
Extract
go
func (r ValidateResult) Extract() (*NodeValidation, error) { var s NodeValidation err := r.ExtractInto(&s) return &s, err }
Extract interprets a ValidateResult as NodeValidation, if possible.
https://github.com/openshift-metal3/terraform-provider-ironic/blob/5e782ae14bfea9d1e8cb981c9a67386461d04c8a/vendor/github.com/gophercloud/gophercloud/openstack/baremetal/v1/nodes/results.go#L37-L41
package nodes import ( "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/pagination" ) type nodeResult struct { gophercloud.Result } func (r nodeResult) Extract() (*Node, error) { var s Node err := r.ExtractInto(&s) return &s, err } func (r BootDeviceResult) Extract() (*BootDeviceOpts, error) { var s BootDeviceOpts err := r.ExtractInto(&s) return &s, err } func (r SupportedBootDeviceResult) Extract() ([]string, error) { var s struct { Devices []string `json:"supported_boot_devices"` } err := r.ExtractInto(&s) return s.Devices, err }
Apache License 2.0
tikv/client-go
internal/mockstore/mocktikv/cluster.go
ScanRegions
go
func (c *Cluster) ScanRegions(startKey, endKey []byte, limit int) []*pd.Region { c.RLock() defer c.RUnlock() regions := make([]*Region, 0, len(c.regions)) for _, region := range c.regions { regions = append(regions, region) } sort.Slice(regions, func(i, j int) bool { return bytes.Compare(regions[i].Meta.GetStartKey(), regions[j].Meta.GetStartKey()) < 0 }) startPos := sort.Search(len(regions), func(i int) bool { if len(regions[i].Meta.GetEndKey()) == 0 { return true } return bytes.Compare(regions[i].Meta.GetEndKey(), startKey) > 0 }) regions = regions[startPos:] if len(endKey) > 0 { endPos := sort.Search(len(regions), func(i int) bool { return bytes.Compare(regions[i].Meta.GetStartKey(), endKey) >= 0 }) if endPos > 0 { regions = regions[:endPos] } } if limit > 0 && len(regions) > limit { regions = regions[:limit] } result := make([]*pd.Region, 0, len(regions)) for _, region := range regions { leader := region.leaderPeer() if leader == nil { leader = &metapb.Peer{} } else { leader = proto.Clone(leader).(*metapb.Peer) } r := &pd.Region{ Meta: proto.Clone(region.Meta).(*metapb.Region), Leader: leader, } result = append(result, r) } return result }
ScanRegions returns at most `limit` regions from given `key` and their leaders.
https://github.com/tikv/client-go/blob/a7d8ea1587e085fa951389656998493e841bccf7/internal/mockstore/mocktikv/cluster.go#L312-L361
package mocktikv import ( "bytes" "context" "math" "sort" "sync" "time" "github.com/golang/protobuf/proto" "github.com/pingcap/kvproto/pkg/kvrpcpb" "github.com/pingcap/kvproto/pkg/metapb" pd "github.com/tikv/pd/client" ) type Cluster struct { sync.RWMutex id uint64 stores map[uint64]*Store regions map[uint64]*Region mvccStore MVCCStore delayEvents map[delayKey]time.Duration delayMu sync.Mutex } type delayKey struct { startTS uint64 regionID uint64 } func NewCluster(mvccStore MVCCStore) *Cluster { return &Cluster{ stores: make(map[uint64]*Store), regions: make(map[uint64]*Region), delayEvents: make(map[delayKey]time.Duration), mvccStore: mvccStore, } } func (c *Cluster) AllocID() uint64 { c.Lock() defer c.Unlock() return c.allocID() } func (c *Cluster) AllocIDs(n int) []uint64 { c.Lock() defer c.Unlock() var ids []uint64 for len(ids) < n { ids = append(ids, c.allocID()) } return ids } func (c *Cluster) allocID() uint64 { c.id++ return c.id } func (c *Cluster) GetAllRegions() []*Region { regions := make([]*Region, 0, len(c.regions)) for _, region := range c.regions { regions = append(regions, region) } return regions } func (c *Cluster) GetStore(storeID uint64) *metapb.Store { c.RLock() defer c.RUnlock() if store := c.stores[storeID]; store != nil { return proto.Clone(store.meta).(*metapb.Store) } return nil } func (c *Cluster) GetAllStores() []*metapb.Store { c.RLock() defer c.RUnlock() stores := make([]*metapb.Store, 0, len(c.stores)) for _, store := range c.stores { stores = append(stores, proto.Clone(store.meta).(*metapb.Store)) } return stores } func (c *Cluster) StopStore(storeID uint64) { c.Lock() defer c.Unlock() if store := c.stores[storeID]; store != nil { store.meta.State = metapb.StoreState_Offline } } func (c *Cluster) StartStore(storeID uint64) { c.Lock() defer c.Unlock() if store := c.stores[storeID]; store != nil { store.meta.State = metapb.StoreState_Up } } func (c *Cluster) CancelStore(storeID uint64) { c.Lock() defer c.Unlock() if store := c.stores[storeID]; store != nil { store.cancel = true } } func (c *Cluster) UnCancelStore(storeID uint64) { c.Lock() defer c.Unlock() if store := c.stores[storeID]; store != nil { store.cancel = false } } func (c *Cluster) GetStoreByAddr(addr string) *metapb.Store { c.RLock() defer c.RUnlock() for _, s := range c.stores { if s.meta.GetAddress() == addr { return proto.Clone(s.meta).(*metapb.Store) } } return nil } func (c *Cluster) GetAndCheckStoreByAddr(addr string) (ss []*metapb.Store, err error) { c.RLock() defer c.RUnlock() for _, s := range c.stores { if s.cancel { err = context.Canceled return } if s.meta.GetAddress() == addr { ss = append(ss, proto.Clone(s.meta).(*metapb.Store)) } } return } func (c *Cluster) AddStore(storeID uint64, addr string, labels ...*metapb.StoreLabel) { c.Lock() defer c.Unlock() c.stores[storeID] = newStore(storeID, addr, labels...) } func (c *Cluster) RemoveStore(storeID uint64) { c.Lock() defer c.Unlock() delete(c.stores, storeID) } func (c *Cluster) MarkTombstone(storeID uint64) { c.Lock() defer c.Unlock() nm := *c.stores[storeID].meta nm.State = metapb.StoreState_Tombstone c.stores[storeID].meta = &nm } func (c *Cluster) UpdateStoreAddr(storeID uint64, addr string, labels ...*metapb.StoreLabel) { c.Lock() defer c.Unlock() c.stores[storeID] = newStore(storeID, addr, labels...) } func (c *Cluster) GetRegion(regionID uint64) (*metapb.Region, uint64) { c.RLock() defer c.RUnlock() r := c.regions[regionID] if r == nil { return nil, 0 } return proto.Clone(r.Meta).(*metapb.Region), r.leader } func (c *Cluster) GetRegionByKey(key []byte) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() return c.getRegionByKeyNoLock(key) } func (c *Cluster) getRegionByKeyNoLock(key []byte) (*metapb.Region, *metapb.Peer) { for _, r := range c.regions { if regionContains(r.Meta.StartKey, r.Meta.EndKey, key) { return proto.Clone(r.Meta).(*metapb.Region), proto.Clone(r.leaderPeer()).(*metapb.Peer) } } return nil, nil } func (c *Cluster) GetPrevRegionByKey(key []byte) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() currentRegion, _ := c.getRegionByKeyNoLock(key) if len(currentRegion.StartKey) == 0 { return nil, nil } for _, r := range c.regions { if bytes.Equal(r.Meta.EndKey, currentRegion.StartKey) { return proto.Clone(r.Meta).(*metapb.Region), proto.Clone(r.leaderPeer()).(*metapb.Peer) } } return nil, nil } func (c *Cluster) GetRegionByID(regionID uint64) (*metapb.Region, *metapb.Peer) { c.RLock() defer c.RUnlock() for _, r := range c.regions { if r.Meta.GetId() == regionID { return proto.Clone(r.Meta).(*metapb.Region), proto.Clone(r.leaderPeer()).(*metapb.Peer) } } return nil, nil }
Apache License 2.0
azure/autorest.go
test/autorest/paginggroup/zz_generated_pagers.go
Err
go
func (p *PagingGetSinglePagesPager) Err() error { return p.err }
Err returns the last error encountered while paging.
https://github.com/azure/autorest.go/blob/01cdd9c890252a9ef822f6d3f2e1273ff9e99cb6/test/autorest/paginggroup/zz_generated_pagers.go#L783-L785
package paginggroup import ( "context" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "net/http" "reflect" ) type PagingFirstResponseEmptyPager struct { client *PagingClient current PagingFirstResponseEmptyResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingFirstResponseEmptyResponse) (*policy.Request, error) } func (p *PagingFirstResponseEmptyPager) Err() error { return p.err } func (p *PagingFirstResponseEmptyPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResultValue.NextLink == nil || len(*p.current.ProductResultValue.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.firstResponseEmptyHandleError(resp) return false } result, err := p.client.firstResponseEmptyHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingFirstResponseEmptyPager) PageResponse() PagingFirstResponseEmptyResponse { return p.current } type PagingGetMultiplePagesFailurePager struct { client *PagingClient current PagingGetMultiplePagesFailureResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesFailureResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesFailurePager) Err() error { return p.err } func (p *PagingGetMultiplePagesFailurePager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesFailureHandleError(resp) return false } result, err := p.client.getMultiplePagesFailureHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesFailurePager) PageResponse() PagingGetMultiplePagesFailureResponse { return p.current } type PagingGetMultiplePagesFailureURIPager struct { client *PagingClient current PagingGetMultiplePagesFailureURIResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesFailureURIResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesFailureURIPager) Err() error { return p.err } func (p *PagingGetMultiplePagesFailureURIPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesFailureURIHandleError(resp) return false } result, err := p.client.getMultiplePagesFailureURIHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesFailureURIPager) PageResponse() PagingGetMultiplePagesFailureURIResponse { return p.current } type PagingGetMultiplePagesFragmentNextLinkPager struct { client *PagingClient current PagingGetMultiplePagesFragmentNextLinkResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesFragmentNextLinkResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesFragmentNextLinkPager) Err() error { return p.err } func (p *PagingGetMultiplePagesFragmentNextLinkPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ODataProductResult.ODataNextLink == nil || len(*p.current.ODataProductResult.ODataNextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesFragmentNextLinkHandleError(resp) return false } result, err := p.client.getMultiplePagesFragmentNextLinkHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesFragmentNextLinkPager) PageResponse() PagingGetMultiplePagesFragmentNextLinkResponse { return p.current } type PagingGetMultiplePagesFragmentWithGroupingNextLinkPager struct { client *PagingClient current PagingGetMultiplePagesFragmentWithGroupingNextLinkResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesFragmentWithGroupingNextLinkResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesFragmentWithGroupingNextLinkPager) Err() error { return p.err } func (p *PagingGetMultiplePagesFragmentWithGroupingNextLinkPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ODataProductResult.ODataNextLink == nil || len(*p.current.ODataProductResult.ODataNextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesFragmentWithGroupingNextLinkHandleError(resp) return false } result, err := p.client.getMultiplePagesFragmentWithGroupingNextLinkHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesFragmentWithGroupingNextLinkPager) PageResponse() PagingGetMultiplePagesFragmentWithGroupingNextLinkResponse { return p.current } type PagingGetMultiplePagesLROPager struct { client *PagingClient current PagingGetMultiplePagesLROResponse err error second bool } func (p *PagingGetMultiplePagesLROPager) Err() error { return p.err } func (p *PagingGetMultiplePagesLROPager) NextPage(ctx context.Context) bool { if !p.second { p.second = true return true } else if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } } req, err := runtime.NewRequest(ctx, http.MethodGet, *p.current.ProductResult.NextLink) if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { p.err = p.client.getMultiplePagesLROHandleError(resp) return false } result, err := p.client.getMultiplePagesLROHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesLROPager) PageResponse() PagingGetMultiplePagesLROResponse { return p.current } type PagingGetMultiplePagesPager struct { client *PagingClient current PagingGetMultiplePagesResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesPager) Err() error { return p.err } func (p *PagingGetMultiplePagesPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesHandleError(resp) return false } result, err := p.client.getMultiplePagesHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesPager) PageResponse() PagingGetMultiplePagesResponse { return p.current } type PagingGetMultiplePagesRetryFirstPager struct { client *PagingClient current PagingGetMultiplePagesRetryFirstResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesRetryFirstResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesRetryFirstPager) Err() error { return p.err } func (p *PagingGetMultiplePagesRetryFirstPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesRetryFirstHandleError(resp) return false } result, err := p.client.getMultiplePagesRetryFirstHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesRetryFirstPager) PageResponse() PagingGetMultiplePagesRetryFirstResponse { return p.current } type PagingGetMultiplePagesRetrySecondPager struct { client *PagingClient current PagingGetMultiplePagesRetrySecondResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesRetrySecondResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesRetrySecondPager) Err() error { return p.err } func (p *PagingGetMultiplePagesRetrySecondPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesRetrySecondHandleError(resp) return false } result, err := p.client.getMultiplePagesRetrySecondHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesRetrySecondPager) PageResponse() PagingGetMultiplePagesRetrySecondResponse { return p.current } type PagingGetMultiplePagesWithOffsetPager struct { client *PagingClient current PagingGetMultiplePagesWithOffsetResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetMultiplePagesWithOffsetResponse) (*policy.Request, error) } func (p *PagingGetMultiplePagesWithOffsetPager) Err() error { return p.err } func (p *PagingGetMultiplePagesWithOffsetPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getMultiplePagesWithOffsetHandleError(resp) return false } result, err := p.client.getMultiplePagesWithOffsetHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetMultiplePagesWithOffsetPager) PageResponse() PagingGetMultiplePagesWithOffsetResponse { return p.current } type PagingGetNoItemNamePagesPager struct { client *PagingClient current PagingGetNoItemNamePagesResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetNoItemNamePagesResponse) (*policy.Request, error) } func (p *PagingGetNoItemNamePagesPager) Err() error { return p.err } func (p *PagingGetNoItemNamePagesPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResultValue.NextLink == nil || len(*p.current.ProductResultValue.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getNoItemNamePagesHandleError(resp) return false } result, err := p.client.getNoItemNamePagesHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetNoItemNamePagesPager) PageResponse() PagingGetNoItemNamePagesResponse { return p.current } type PagingGetODataMultiplePagesPager struct { client *PagingClient current PagingGetODataMultiplePagesResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetODataMultiplePagesResponse) (*policy.Request, error) } func (p *PagingGetODataMultiplePagesPager) Err() error { return p.err } func (p *PagingGetODataMultiplePagesPager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ODataProductResult.ODataNextLink == nil || len(*p.current.ODataProductResult.ODataNextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getODataMultiplePagesHandleError(resp) return false } result, err := p.client.getODataMultiplePagesHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetODataMultiplePagesPager) PageResponse() PagingGetODataMultiplePagesResponse { return p.current } type PagingGetPagingModelWithItemNameWithXMSClientNamePager struct { client *PagingClient current PagingGetPagingModelWithItemNameWithXMSClientNameResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetPagingModelWithItemNameWithXMSClientNameResponse) (*policy.Request, error) } func (p *PagingGetPagingModelWithItemNameWithXMSClientNamePager) Err() error { return p.err } func (p *PagingGetPagingModelWithItemNameWithXMSClientNamePager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResultValueWithXMSClientName.NextLink == nil || len(*p.current.ProductResultValueWithXMSClientName.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getPagingModelWithItemNameWithXMSClientNameHandleError(resp) return false } result, err := p.client.getPagingModelWithItemNameWithXMSClientNameHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetPagingModelWithItemNameWithXMSClientNamePager) PageResponse() PagingGetPagingModelWithItemNameWithXMSClientNameResponse { return p.current } type PagingGetSinglePagesFailurePager struct { client *PagingClient current PagingGetSinglePagesFailureResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetSinglePagesFailureResponse) (*policy.Request, error) } func (p *PagingGetSinglePagesFailurePager) Err() error { return p.err } func (p *PagingGetSinglePagesFailurePager) NextPage(ctx context.Context) bool { var req *policy.Request var err error if !reflect.ValueOf(p.current).IsZero() { if p.current.ProductResult.NextLink == nil || len(*p.current.ProductResult.NextLink) == 0 { return false } req, err = p.advancer(ctx, p.current) } else { req, err = p.requester(ctx) } if err != nil { p.err = err return false } resp, err := p.client.con.Pipeline().Do(req) if err != nil { p.err = err return false } if !runtime.HasStatusCode(resp, http.StatusOK) { p.err = p.client.getSinglePagesFailureHandleError(resp) return false } result, err := p.client.getSinglePagesFailureHandleResponse(resp) if err != nil { p.err = err return false } p.current = result return true } func (p *PagingGetSinglePagesFailurePager) PageResponse() PagingGetSinglePagesFailureResponse { return p.current } type PagingGetSinglePagesPager struct { client *PagingClient current PagingGetSinglePagesResponse err error requester func(context.Context) (*policy.Request, error) advancer func(context.Context, PagingGetSinglePagesResponse) (*policy.Request, error) }
MIT License
nuclio/nuclio
pkg/processor/cloudevent/mockevent.go
GetMethod
go
func (me *mockEvent) GetMethod() string { args := me.Called() return args.String(0) }
GetMethod returns the method of the event, if applicable
https://github.com/nuclio/nuclio/blob/1103106864b77aec023ce868db8774c43b297eb2/pkg/processor/cloudevent/mockevent.go#L150-L153
package cloudevent import ( "time" "github.com/nuclio/nuclio-sdk-go" "github.com/stretchr/testify/mock" ) type mockEvent struct { mock.Mock triggerInfoProvider nuclio.TriggerInfoProvider } func (me *mockEvent) GetID() nuclio.ID { args := me.Called() return args.Get(0).(nuclio.ID) } func (me *mockEvent) SetID(id nuclio.ID) { me.Called() } func (me *mockEvent) SetTriggerInfoProvider(triggerInfoProvider nuclio.TriggerInfoProvider) { me.Called(triggerInfoProvider) me.triggerInfoProvider = triggerInfoProvider } func (me *mockEvent) GetTriggerInfo() nuclio.TriggerInfoProvider { return me.triggerInfoProvider } func (me *mockEvent) GetContentType() string { args := me.Called() return args.String(0) } func (me *mockEvent) GetBody() []byte { args := me.Called() return args.Get(0).([]byte) } func (me *mockEvent) GetBodyObject() interface{} { args := me.Called() return args.Get(0) } func (me *mockEvent) GetHeader(key string) interface{} { args := me.Called(key) return args.String(0) } func (me *mockEvent) GetHeaderByteSlice(key string) []byte { args := me.Called(key) return args.Get(0).([]byte) } func (me *mockEvent) GetHeaderString(key string) string { args := me.Called(key) return args.String(0) } func (me *mockEvent) GetHeaderInt(key string) (int, error) { args := me.Called(key) return args.Int(0), args.Error(1) } func (me *mockEvent) GetHeaders() map[string]interface{} { args := me.Called() return args.Get(0).(map[string]interface{}) } func (me *mockEvent) GetField(key string) interface{} { args := me.Called(key) return args.Get(0) } func (me *mockEvent) GetFieldByteSlice(key string) []byte { args := me.Called(key) return args.Get(0).([]byte) } func (me *mockEvent) GetFieldString(key string) string { args := me.Called(key) return args.String(0) } func (me *mockEvent) GetFieldInt(key string) (int, error) { args := me.Called(key) return args.Int(0), args.Error(1) } func (me *mockEvent) GetFields() map[string]interface{} { args := me.Called() return args.Get(0).(map[string]interface{}) } func (me *mockEvent) GetTimestamp() time.Time { args := me.Called() return args.Get(0).(time.Time) } func (me *mockEvent) GetPath() string { args := me.Called() return args.String(0) } func (me *mockEvent) GetURL() string { args := me.Called() return args.String(0) }
Apache License 2.0
dewey/feedbridge
vendor/github.com/peterbourgon/diskv/index.go
Initialize
go
func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) { i.Lock() defer i.Unlock() i.LessFunction = less i.BTree = rebuild(less, keys) }
Initialize populates the BTree tree with data from the keys channel, according to the passed less function. It's destructive to the BTreeIndex.
https://github.com/dewey/feedbridge/blob/ee9fbbcc430654770c3ea26fa0bdea49bd044243/vendor/github.com/peterbourgon/diskv/index.go#L42-L47
package diskv import ( "sync" "github.com/google/btree" ) type Index interface { Initialize(less LessFunction, keys <-chan string) Insert(key string) Delete(key string) Keys(from string, n int) []string } type LessFunction func(string, string) bool type btreeString struct { s string l LessFunction } func (s btreeString) Less(i btree.Item) bool { return s.l(s.s, i.(btreeString).s) } type BTreeIndex struct { sync.RWMutex LessFunction *btree.BTree }
MIT License
schollz/progressbar
progressbar.go
Describe
go
func (p *ProgressBar) Describe(description string) { p.config.description = description }
Describe will change the description shown before the progress, which can be changed on the fly (as for a slow running process).
https://github.com/schollz/progressbar/blob/f60d974c05811ca825b31db8834744f61ec6185e/progressbar.go#L516-L518
package progressbar import ( "errors" "fmt" "io" "io/ioutil" "math" "os" "regexp" "strings" "sync" "time" "github.com/mattn/go-runewidth" "github.com/mitchellh/colorstring" "golang.org/x/crypto/ssh/terminal" ) type ProgressBar struct { state state config config lock sync.Mutex } type State struct { CurrentPercent float64 CurrentBytes float64 SecondsSince float64 SecondsLeft float64 KBsPerSecond float64 } type state struct { currentNum int64 currentPercent int lastPercent int currentSaucerSize int lastShown time.Time startTime time.Time counterTime time.Time counterNumSinceLast int64 counterLastTenRates []float64 maxLineWidth int currentBytes float64 finished bool rendered string } type config struct { max int64 maxHumanized string maxHumanizedSuffix string width int writer io.Writer theme Theme renderWithBlankState bool description string iterationString string ignoreLength bool colorCodes bool showBytes bool showIterationsPerSecond bool showIterationsCount bool predictTime bool throttleDuration time.Duration clearOnFinish bool spinnerType int fullWidth bool invisible bool onCompletion func() useANSICodes bool } type Theme struct { Saucer string SaucerHead string SaucerPadding string BarStart string BarEnd string } type Option func(p *ProgressBar) func OptionSetWidth(s int) Option { return func(p *ProgressBar) { p.config.width = s } } func OptionSpinnerType(spinnerType int) Option { return func(p *ProgressBar) { p.config.spinnerType = spinnerType } } func OptionSetTheme(t Theme) Option { return func(p *ProgressBar) { p.config.theme = t } } func OptionSetVisibility(visibility bool) Option { return func(p *ProgressBar) { p.config.invisible = !visibility } } func OptionFullWidth() Option { return func(p *ProgressBar) { p.config.fullWidth = true } } func OptionSetWriter(w io.Writer) Option { return func(p *ProgressBar) { p.config.writer = w } } func OptionSetRenderBlankState(r bool) Option { return func(p *ProgressBar) { p.config.renderWithBlankState = r } } func OptionSetDescription(description string) Option { return func(p *ProgressBar) { p.config.description = description } } func OptionEnableColorCodes(colorCodes bool) Option { return func(p *ProgressBar) { p.config.colorCodes = colorCodes } } func OptionSetPredictTime(predictTime bool) Option { return func(p *ProgressBar) { p.config.predictTime = predictTime } } func OptionShowCount() Option { return func(p *ProgressBar) { p.config.showIterationsCount = true } } func OptionShowIts() Option { return func(p *ProgressBar) { p.config.showIterationsPerSecond = true } } func OptionSetItsString(iterationString string) Option { return func(p *ProgressBar) { p.config.iterationString = iterationString } } func OptionThrottle(duration time.Duration) Option { return func(p *ProgressBar) { p.config.throttleDuration = duration } } func OptionClearOnFinish() Option { return func(p *ProgressBar) { p.config.clearOnFinish = true } } func OptionOnCompletion(cmpl func()) Option { return func(p *ProgressBar) { p.config.onCompletion = cmpl } } func OptionShowBytes(val bool) Option { return func(p *ProgressBar) { p.config.showBytes = val } } func OptionUseANSICodes(val bool) Option { return func(p *ProgressBar) { p.config.useANSICodes = val } } var defaultTheme = Theme{Saucer: "█", SaucerPadding: " ", BarStart: "|", BarEnd: "|"} func NewOptions(max int, options ...Option) *ProgressBar { return NewOptions64(int64(max), options...) } func NewOptions64(max int64, options ...Option) *ProgressBar { b := ProgressBar{ state: getBasicState(), config: config{ writer: os.Stdout, theme: defaultTheme, iterationString: "it", width: 40, max: max, throttleDuration: 0 * time.Nanosecond, predictTime: true, spinnerType: 9, invisible: false, }, } for _, o := range options { o(&b) } if b.config.spinnerType < 0 || b.config.spinnerType > 75 { panic("invalid spinner type, must be between 0 and 75") } if b.config.max == -1 { b.config.ignoreLength = true b.config.max = int64(b.config.width) b.config.predictTime = false } b.config.maxHumanized, b.config.maxHumanizedSuffix = humanizeBytes(float64(b.config.max)) if b.config.renderWithBlankState { b.RenderBlank() } return &b } func getBasicState() state { now := time.Now() return state{ startTime: now, lastShown: now, counterTime: now, } } func New(max int) *ProgressBar { return NewOptions(max) } func DefaultBytes(maxBytes int64, description ...string) *ProgressBar { desc := "" if len(description) > 0 { desc = description[0] } bar := NewOptions64( maxBytes, OptionSetDescription(desc), OptionSetWriter(os.Stderr), OptionShowBytes(true), OptionSetWidth(10), OptionThrottle(65*time.Millisecond), OptionShowCount(), OptionOnCompletion(func() { fmt.Printf("\n") }), OptionSpinnerType(14), OptionFullWidth(), ) bar.RenderBlank() return bar } func DefaultBytesSilent(maxBytes int64, description ...string) *ProgressBar { desc := "" if len(description) > 0 { desc = description[0] } bar := NewOptions64( maxBytes, OptionSetDescription(desc), OptionSetWriter(ioutil.Discard), OptionShowBytes(true), OptionSetWidth(10), OptionThrottle(65*time.Millisecond), OptionShowCount(), OptionSpinnerType(14), OptionFullWidth(), ) bar.RenderBlank() return bar } func Default(max int64, description ...string) *ProgressBar { desc := "" if len(description) > 0 { desc = description[0] } bar := NewOptions64( max, OptionSetDescription(desc), OptionSetWriter(os.Stderr), OptionSetWidth(10), OptionThrottle(65*time.Millisecond), OptionShowCount(), OptionShowIts(), OptionOnCompletion(func() { fmt.Printf("\n") }), OptionSpinnerType(14), OptionFullWidth(), ) bar.RenderBlank() return bar } func DefaultSilent(max int64, description ...string) *ProgressBar { desc := "" if len(description) > 0 { desc = description[0] } bar := NewOptions64( max, OptionSetDescription(desc), OptionSetWriter(ioutil.Discard), OptionSetWidth(10), OptionThrottle(65*time.Millisecond), OptionShowCount(), OptionShowIts(), OptionSpinnerType(14), OptionFullWidth(), ) bar.RenderBlank() return bar } func (p *ProgressBar) String() string { return p.state.rendered } func (p *ProgressBar) RenderBlank() error { if p.config.invisible { return nil } return p.render() } func (p *ProgressBar) Reset() { p.lock.Lock() defer p.lock.Unlock() p.state = getBasicState() } func (p *ProgressBar) Finish() error { p.lock.Lock() p.state.currentNum = p.config.max p.lock.Unlock() return p.Add(0) } func (p *ProgressBar) Add(num int) error { return p.Add64(int64(num)) } func (p *ProgressBar) Set(num int) error { return p.Set64(int64(num)) } func (p *ProgressBar) Set64(num int64) error { p.lock.Lock() toAdd := num - int64(p.state.currentBytes) p.lock.Unlock() return p.Add64(toAdd) } func (p *ProgressBar) Add64(num int64) error { if p.config.invisible { return nil } p.lock.Lock() defer p.lock.Unlock() if p.config.max == 0 { return errors.New("max must be greater than 0") } if p.state.currentNum < p.config.max { if p.config.ignoreLength { p.state.currentNum = (p.state.currentNum + num) % p.config.max } else { p.state.currentNum += num } } p.state.currentBytes += float64(num) p.state.counterNumSinceLast += num if time.Since(p.state.counterTime).Seconds() > 0.5 { p.state.counterLastTenRates = append(p.state.counterLastTenRates, float64(p.state.counterNumSinceLast)/time.Since(p.state.counterTime).Seconds()) if len(p.state.counterLastTenRates) > 10 { p.state.counterLastTenRates = p.state.counterLastTenRates[1:] } p.state.counterTime = time.Now() p.state.counterNumSinceLast = 0 } percent := float64(p.state.currentNum) / float64(p.config.max) p.state.currentSaucerSize = int(percent * float64(p.config.width)) p.state.currentPercent = int(percent * 100) updateBar := p.state.currentPercent != p.state.lastPercent && p.state.currentPercent > 0 p.state.lastPercent = p.state.currentPercent if p.state.currentNum > p.config.max { return errors.New("current number exceeds max") } if updateBar || p.config.showIterationsPerSecond || p.config.showIterationsCount { return p.render() } return nil } func (p *ProgressBar) Clear() error { return clearProgressBar(p.config, p.state) }
MIT License
boj/redistore
redistore.go
load
go
func (s *RediStore) load(session *sessions.Session) (bool, error) { conn := s.Pool.Get() defer conn.Close() if err := conn.Err(); err != nil { return false, err } data, err := conn.Do("GET", s.keyPrefix+session.ID) if err != nil { return false, err } if data == nil { return false, nil } b, err := redis.Bytes(data, err) if err != nil { return false, err } return true, s.serializer.Deserialize(b, session) }
load reads the session from redis. returns true if there is a sessoin data in DB
https://github.com/boj/redistore/blob/cd5dcc76aeff9ba06b0a924829fe24fd69cdd517/redistore.go#L333-L351
package redistore import ( "bytes" "encoding/base32" "encoding/gob" "encoding/json" "errors" "fmt" "net/http" "strings" "time" "github.com/gomodule/redigo/redis" "github.com/gorilla/securecookie" "github.com/gorilla/sessions" ) var sessionExpire = 86400 * 30 type SessionSerializer interface { Deserialize(d []byte, ss *sessions.Session) error Serialize(ss *sessions.Session) ([]byte, error) } type JSONSerializer struct{} func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error) { m := make(map[string]interface{}, len(ss.Values)) for k, v := range ss.Values { ks, ok := k.(string) if !ok { err := fmt.Errorf("Non-string key value, cannot serialize session to JSON: %v", k) fmt.Printf("redistore.JSONSerializer.serialize() Error: %v", err) return nil, err } m[ks] = v } return json.Marshal(m) } func (s JSONSerializer) Deserialize(d []byte, ss *sessions.Session) error { m := make(map[string]interface{}) err := json.Unmarshal(d, &m) if err != nil { fmt.Printf("redistore.JSONSerializer.deserialize() Error: %v", err) return err } for k, v := range m { ss.Values[k] = v } return nil } type GobSerializer struct{} func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error) { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) err := enc.Encode(ss.Values) if err == nil { return buf.Bytes(), nil } return nil, err } func (s GobSerializer) Deserialize(d []byte, ss *sessions.Session) error { dec := gob.NewDecoder(bytes.NewBuffer(d)) return dec.Decode(&ss.Values) } type RediStore struct { Pool *redis.Pool Codecs []securecookie.Codec Options *sessions.Options DefaultMaxAge int maxLength int keyPrefix string serializer SessionSerializer } func (s *RediStore) SetMaxLength(l int) { if l >= 0 { s.maxLength = l } } func (s *RediStore) SetKeyPrefix(p string) { s.keyPrefix = p } func (s *RediStore) SetSerializer(ss SessionSerializer) { s.serializer = ss } func (s *RediStore) SetMaxAge(v int) { var c *securecookie.SecureCookie var ok bool s.Options.MaxAge = v for i := range s.Codecs { if c, ok = s.Codecs[i].(*securecookie.SecureCookie); ok { c.MaxAge(v) } else { fmt.Printf("Can't change MaxAge on codec %v\n", s.Codecs[i]) } } } func dial(network, address, password string) (redis.Conn, error) { c, err := redis.Dial(network, address) if err != nil { return nil, err } if password != "" { if _, err := c.Do("AUTH", password); err != nil { c.Close() return nil, err } } return c, err } func NewRediStore(size int, network, address, password string, keyPairs ...[]byte) (*RediStore, error) { return NewRediStoreWithPool(&redis.Pool{ MaxIdle: size, IdleTimeout: 240 * time.Second, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, Dial: func() (redis.Conn, error) { return dial(network, address, password) }, }, keyPairs...) } func dialWithDB(network, address, password, DB string) (redis.Conn, error) { c, err := dial(network, address, password) if err != nil { return nil, err } if _, err := c.Do("SELECT", DB); err != nil { c.Close() return nil, err } return c, err } func NewRediStoreWithDB(size int, network, address, password, DB string, keyPairs ...[]byte) (*RediStore, error) { return NewRediStoreWithPool(&redis.Pool{ MaxIdle: size, IdleTimeout: 240 * time.Second, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, Dial: func() (redis.Conn, error) { return dialWithDB(network, address, password, DB) }, }, keyPairs...) } func NewRediStoreWithPool(pool *redis.Pool, keyPairs ...[]byte) (*RediStore, error) { rs := &RediStore{ Pool: pool, Codecs: securecookie.CodecsFromPairs(keyPairs...), Options: &sessions.Options{ Path: "/", MaxAge: sessionExpire, }, DefaultMaxAge: 60 * 20, maxLength: 4096, keyPrefix: "session_", serializer: GobSerializer{}, } _, err := rs.ping() return rs, err } func (s *RediStore) Close() error { return s.Pool.Close() } func (s *RediStore) Get(r *http.Request, name string) (*sessions.Session, error) { return sessions.GetRegistry(r).Get(s, name) } func (s *RediStore) New(r *http.Request, name string) (*sessions.Session, error) { var ( err error ok bool ) session := sessions.NewSession(s, name) options := *s.Options session.Options = &options session.IsNew = true if c, errCookie := r.Cookie(name); errCookie == nil { err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...) if err == nil { ok, err = s.load(session) session.IsNew = !(err == nil && ok) } } return session, err } func (s *RediStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { if session.Options.MaxAge <= 0 { if err := s.delete(session); err != nil { return err } http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options)) } else { if session.ID == "" { session.ID = strings.TrimRight(base32.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)), "=") } if err := s.save(session); err != nil { return err } encoded, err := securecookie.EncodeMulti(session.Name(), session.ID, s.Codecs...) if err != nil { return err } http.SetCookie(w, sessions.NewCookie(session.Name(), encoded, session.Options)) } return nil } func (s *RediStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { conn := s.Pool.Get() defer conn.Close() if _, err := conn.Do("DEL", s.keyPrefix+session.ID); err != nil { return err } options := *session.Options options.MaxAge = -1 http.SetCookie(w, sessions.NewCookie(session.Name(), "", &options)) for k := range session.Values { delete(session.Values, k) } return nil } func (s *RediStore) ping() (bool, error) { conn := s.Pool.Get() defer conn.Close() data, err := conn.Do("PING") if err != nil || data == nil { return false, err } return (data == "PONG"), nil } func (s *RediStore) save(session *sessions.Session) error { b, err := s.serializer.Serialize(session) if err != nil { return err } if s.maxLength != 0 && len(b) > s.maxLength { return errors.New("SessionStore: the value to store is too big") } conn := s.Pool.Get() defer conn.Close() if err = conn.Err(); err != nil { return err } age := session.Options.MaxAge if age == 0 { age = s.DefaultMaxAge } _, err = conn.Do("SETEX", s.keyPrefix+session.ID, age, b) return err }
MIT License
fugue/fugue-client
client/environments/delete_environment_parameters.go
SetContext
go
func (o *DeleteEnvironmentParams) SetContext(ctx context.Context) { o.Context = ctx }
SetContext adds the context to the delete environment params
https://github.com/fugue/fugue-client/blob/a8c3e1e587ab8532929b3706321a79f719d9bb7a/client/environments/delete_environment_parameters.go#L92-L94
package environments import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" ) func NewDeleteEnvironmentParams() *DeleteEnvironmentParams { var () return &DeleteEnvironmentParams{ timeout: cr.DefaultTimeout, } } func NewDeleteEnvironmentParamsWithTimeout(timeout time.Duration) *DeleteEnvironmentParams { var () return &DeleteEnvironmentParams{ timeout: timeout, } } func NewDeleteEnvironmentParamsWithContext(ctx context.Context) *DeleteEnvironmentParams { var () return &DeleteEnvironmentParams{ Context: ctx, } } func NewDeleteEnvironmentParamsWithHTTPClient(client *http.Client) *DeleteEnvironmentParams { var () return &DeleteEnvironmentParams{ HTTPClient: client, } } type DeleteEnvironmentParams struct { EnvironmentID string timeout time.Duration Context context.Context HTTPClient *http.Client } func (o *DeleteEnvironmentParams) WithTimeout(timeout time.Duration) *DeleteEnvironmentParams { o.SetTimeout(timeout) return o } func (o *DeleteEnvironmentParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } func (o *DeleteEnvironmentParams) WithContext(ctx context.Context) *DeleteEnvironmentParams { o.SetContext(ctx) return o }
MIT License
soteria-dag/soterd
blockdag/phantom/set.go
intersection
go
func (nset *nodeSet) intersection(nset2 *nodeSet) *nodeSet { intersection := newNodeSet() if nset2 == nil { return intersection } for k := range nset.nodes { if nset2.contains(k) { intersection.add(k) } } return intersection }
returns nset intersection nset2
https://github.com/soteria-dag/soterd/blob/b18452bc9a4c0bec4eef54137fb497506b80baf5/blockdag/phantom/set.go#L87-L100
package phantom import ( "bytes" "encoding/gob" "sort" ) type nodeSet struct { nodes map[*Node]struct{} } func newNodeSet() *nodeSet { return &nodeSet{ nodes: make(map[*Node]struct{}), } } func (nset *nodeSet) size() int { return len(nset.nodes) } func (nset *nodeSet) add(node *Node) { if node == nil { return } if nset.contains(node) { return } nset.nodes[node] = keyExists } func (nset *nodeSet) remove(node *Node) { delete(nset.nodes, node) } func (nset *nodeSet) elements() []*Node { nodes := make([]*Node, len(nset.nodes)) index := 0 for k := range nset.nodes { nodes[index] = k index += 1 } sort.Slice(nodes, func(i, j int) bool { if nodes[i].GetId() < nodes[j].GetId() { return true } else { return false } }) return nodes } func (nset *nodeSet) contains(node *Node) bool { _, ok := nset.nodes[node] return ok } func (nset *nodeSet) difference(nset2 *nodeSet) *nodeSet { diff := newNodeSet() if nset2 == nil { return diff } for k := range nset.nodes { if !nset2.contains(k) { diff.add(k) } } return diff }
ISC License
danilopolani/gosc
string.go
ToCamelCase
go
func ToCamelCase(s string) string { return ToCamel(s) }
ToCamelCase is an alias of ToCamel
https://github.com/danilopolani/gosc/blob/65b2f5cee088115ca0dfaa6fb195e43b35c0a34c/string.go#L121-L123
package gosc import ( "bytes" cryrand "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "math/rand" "net" "net/url" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" ) var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") var camelingRegex = regexp.MustCompile("[0-9A-Za-z]+") func ToBytes(s string) []byte { return []byte(s) } func ByteToString(b []byte) string { return string(b[:]) } func Rstring(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func ReverseString(s string) string { return Rstring(s) } func LcFirst(s string) string { if s == "" { return "" } r, n := utf8.DecodeRuneInString(s) return string(unicode.ToLower(r)) + s[n:] } func LowerFirst(s string) string { return LcFirst(s) } func UcFirst(s string) string { if s == "" { return "" } r, n := utf8.DecodeRuneInString(s) return string(unicode.ToUpper(r)) + s[n:] } func UpperFirst(s string) string { return UcFirst(s) } func ToSnake(s string) string { s = strings.Replace(strings.Replace(s, "-", "_", -1), " ", "_", -1) runes := []rune(s) length := len(runes) var out []rune for i := 0; i < length; i++ { if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) { out = append(out, '_') } out = append(out, unicode.ToLower(runes[i])) } return string(out) } func ToSnakeCase(s string) string { return ToSnake(s) } func ToCamel(s string) string { byteSrc := []byte(s) chunks := camelingRegex.FindAll(byteSrc, -1) for idx, val := range chunks { val = bytes.ToLower(val) if idx > 0 { chunks[idx] = bytes.Title(val) } } return string(bytes.Join(chunks, nil)) }
MIT License
marcelmue/konstrukt
cmd/error.go
IsInvalidFlags
go
func IsInvalidFlags(err error) bool { return microerror.Cause(err) == invalidFlagsError }
IsInvalidFlags asserts invalidFlagsError.
https://github.com/marcelmue/konstrukt/blob/8494875a2d274afafee8c55df67eb94563bcd256/cmd/error.go#L19-L21
package cmd import "github.com/giantswarm/microerror" var invalidConfigError = &microerror.Error{ Kind: "invalidConfigError", } func IsInvalidConfig(err error) bool { return microerror.Cause(err) == invalidConfigError } var invalidFlagsError = &microerror.Error{ Kind: "invalidFlagsError", }
MIT License
azure/autorest.go
test/autorest/complexgroup/zz_generated_response_types.go
UnmarshalJSON
go
func (f *FlattencomplexGetValidResult) UnmarshalJSON(data []byte) error { res, err := unmarshalMyBaseTypeClassification(data) if err != nil { return err } f.MyBaseTypeClassification = res return nil }
UnmarshalJSON implements the json.Unmarshaller interface for type FlattencomplexGetValidResult.
https://github.com/azure/autorest.go/blob/01cdd9c890252a9ef822f6d3f2e1273ff9e99cb6/test/autorest/complexgroup/zz_generated_response_types.go#L200-L207
package complexgroup import "net/http" type ArrayGetEmptyResponse struct { ArrayGetEmptyResult RawResponse *http.Response } type ArrayGetEmptyResult struct { ArrayWrapper } type ArrayGetNotProvidedResponse struct { ArrayGetNotProvidedResult RawResponse *http.Response } type ArrayGetNotProvidedResult struct { ArrayWrapper } type ArrayGetValidResponse struct { ArrayGetValidResult RawResponse *http.Response } type ArrayGetValidResult struct { ArrayWrapper } type ArrayPutEmptyResponse struct { RawResponse *http.Response } type ArrayPutValidResponse struct { RawResponse *http.Response } type BasicGetEmptyResponse struct { BasicGetEmptyResult RawResponse *http.Response } type BasicGetEmptyResult struct { Basic } type BasicGetInvalidResponse struct { BasicGetInvalidResult RawResponse *http.Response } type BasicGetInvalidResult struct { Basic } type BasicGetNotProvidedResponse struct { BasicGetNotProvidedResult RawResponse *http.Response } type BasicGetNotProvidedResult struct { Basic } type BasicGetNullResponse struct { BasicGetNullResult RawResponse *http.Response } type BasicGetNullResult struct { Basic } type BasicGetValidResponse struct { BasicGetValidResult RawResponse *http.Response } type BasicGetValidResult struct { Basic } type BasicPutValidResponse struct { RawResponse *http.Response } type DictionaryGetEmptyResponse struct { DictionaryGetEmptyResult RawResponse *http.Response } type DictionaryGetEmptyResult struct { DictionaryWrapper } type DictionaryGetNotProvidedResponse struct { DictionaryGetNotProvidedResult RawResponse *http.Response } type DictionaryGetNotProvidedResult struct { DictionaryWrapper } type DictionaryGetNullResponse struct { DictionaryGetNullResult RawResponse *http.Response } type DictionaryGetNullResult struct { DictionaryWrapper } type DictionaryGetValidResponse struct { DictionaryGetValidResult RawResponse *http.Response } type DictionaryGetValidResult struct { DictionaryWrapper } type DictionaryPutEmptyResponse struct { RawResponse *http.Response } type DictionaryPutValidResponse struct { RawResponse *http.Response } type FlattencomplexGetValidResponse struct { FlattencomplexGetValidResult RawResponse *http.Response } type FlattencomplexGetValidResult struct { MyBaseTypeClassification }
MIT License
akutz/gournal
vendor/github.com/uber-go/zap/json_encoder.go
AddUint
go
func (enc *jsonEncoder) AddUint(key string, val uint) { enc.AddUint64(key, uint64(val)) }
AddUint adds a string key and integer value to the encoder's fields. The key is JSON-escaped.
https://github.com/akutz/gournal/blob/f6e56fa29076290418175a5105fd0223c66ad1bc/vendor/github.com/uber-go/zap/json_encoder.go#L129-L131
package zap import ( "encoding/json" "errors" "fmt" "io" "math" "strconv" "sync" "time" "unicode/utf8" ) const ( _hex = "0123456789abcdef" _initialBufSize = 1024 ) var ( errNilSink = errors.New("can't write encoded message a nil WriteSyncer") defaultMessageF = MessageKey("msg") defaultTimeF = EpochFormatter("ts") defaultLevelF = LevelString("level") jsonPool = sync.Pool{New: func() interface{} { return &jsonEncoder{ bytes: make([]byte, 0, _initialBufSize), } }} ) type jsonEncoder struct { bytes []byte messageF MessageFormatter timeF TimeFormatter levelF LevelFormatter } func NewJSONEncoder(options ...JSONOption) Encoder { enc := jsonPool.Get().(*jsonEncoder) enc.truncate() enc.messageF = defaultMessageF enc.timeF = defaultTimeF enc.levelF = defaultLevelF for _, opt := range options { opt.apply(enc) } return enc } func (enc *jsonEncoder) Free() { jsonPool.Put(enc) } func (enc *jsonEncoder) AddString(key, val string) { enc.addKey(key) enc.bytes = append(enc.bytes, '"') enc.safeAddString(val) enc.bytes = append(enc.bytes, '"') } func (enc *jsonEncoder) AddBool(key string, val bool) { enc.addKey(key) enc.bytes = strconv.AppendBool(enc.bytes, val) } func (enc *jsonEncoder) AddInt(key string, val int) { enc.AddInt64(key, int64(val)) } func (enc *jsonEncoder) AddInt64(key string, val int64) { enc.addKey(key) enc.bytes = strconv.AppendInt(enc.bytes, val, 10) }
Apache License 2.0
ethsana/sana
pkg/accounting/mock/accounting.go
WithReleaseFunc
go
func WithReleaseFunc(f func(peer swarm.Address, price uint64)) Option { return optionFunc(func(s *Service) { s.releaseFunc = f }) }
WithReleaseFunc sets the mock Release function
https://github.com/ethsana/sana/blob/eb538a0f1800a322993040c2c2b8bb6649c443ae/pkg/accounting/mock/accounting.go#L50-L54
package mock import ( "context" "math/big" "sync" "github.com/ethsana/sana/pkg/accounting" "github.com/ethsana/sana/pkg/swarm" ) type Service struct { lock sync.Mutex balances map[string]*big.Int reserveFunc func(ctx context.Context, peer swarm.Address, price uint64) error releaseFunc func(peer swarm.Address, price uint64) creditFunc func(peer swarm.Address, price uint64, orig bool) error prepareDebitFunc func(peer swarm.Address, price uint64) (accounting.Action, error) balanceFunc func(swarm.Address) (*big.Int, error) shadowBalanceFunc func(swarm.Address) (*big.Int, error) balancesFunc func() (map[string]*big.Int, error) compensatedBalanceFunc func(swarm.Address) (*big.Int, error) compensatedBalancesFunc func() (map[string]*big.Int, error) balanceSurplusFunc func(swarm.Address) (*big.Int, error) } type debitAction struct { accounting *Service price *big.Int peer swarm.Address applied bool } func WithReserveFunc(f func(ctx context.Context, peer swarm.Address, price uint64) error) Option { return optionFunc(func(s *Service) { s.reserveFunc = f }) }
BSD 3-Clause New or Revised License
dipper-labs/dipper-protocol
app/v0/distribution/keeper/store.go
IterateValidatorOutstandingRewards
go
func (k Keeper) IterateValidatorOutstandingRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorOutstandingRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorOutstandingRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) addr := GetValidatorOutstandingRewardsAddress(iter.Key()) if handler(addr, rewards) { break } } }
IterateValidatorOutstandingRewards - iterate validator outstanding rewards
https://github.com/dipper-labs/dipper-protocol/blob/94dd33dd64dee9971092c42352fe8d455e8458de/app/v0/distribution/keeper/store.go#L295-L307
package keeper import ( "github.com/Dipper-Labs/Dipper-Protocol/app/v0/distribution/types" sdk "github.com/Dipper-Labs/Dipper-Protocol/types" ) func (k Keeper) GetDelegatorWithdrawAddr(ctx sdk.Context, delAddr sdk.AccAddress) sdk.AccAddress { store := ctx.KVStore(k.storeKey) b := store.Get(GetDelegatorWithdrawAddrKey(delAddr)) if b == nil { return delAddr } return sdk.AccAddress(b) } func (k Keeper) SetDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAddr sdk.AccAddress) { store := ctx.KVStore(k.storeKey) store.Set(GetDelegatorWithdrawAddrKey(delAddr), withdrawAddr.Bytes()) } func (k Keeper) DeleteDelegatorWithdrawAddr(ctx sdk.Context, delAddr, withdrawAddr sdk.AccAddress) { store := ctx.KVStore(k.storeKey) store.Delete(GetDelegatorWithdrawAddrKey(delAddr)) } func (k Keeper) IterateDelegatorWithdrawAddrs(ctx sdk.Context, handler func(del sdk.AccAddress, addr sdk.AccAddress) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, DelegatorWithdrawAddrPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { addr := sdk.AccAddress(iter.Value()) del := GetDelegatorWithdrawInfoAddress(iter.Key()) if handler(del, addr) { break } } } func (k Keeper) GetFeePool(ctx sdk.Context) (feePool types.FeePool) { store := ctx.KVStore(k.storeKey) b := store.Get(FeePoolKey) if b == nil { panic("Stored fee pool should not have been nil") } k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &feePool) return } func (k Keeper) SetFeePool(ctx sdk.Context, feePool types.FeePool) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(feePool) store.Set(FeePoolKey, b) } func (k Keeper) GetPreviousProposerConsAddr(ctx sdk.Context) (consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) b := store.Get(ProposerKey) if b == nil { panic("Previous proposer not set") } k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &consAddr) return } func (k Keeper) SetPreviousProposerConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(consAddr) store.Set(ProposerKey, b) } func (k Keeper) GetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) (period types.DelegatorStartingInfo) { store := ctx.KVStore(k.storeKey) b := store.Get(GetDelegatorStartingInfoKey(val, del)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &period) return } func (k Keeper) SetDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress, period types.DelegatorStartingInfo) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(period) store.Set(GetDelegatorStartingInfoKey(val, del), b) } func (k Keeper) HasDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) bool { store := ctx.KVStore(k.storeKey) return store.Has(GetDelegatorStartingInfoKey(val, del)) } func (k Keeper) DeleteDelegatorStartingInfo(ctx sdk.Context, val sdk.ValAddress, del sdk.AccAddress) { store := ctx.KVStore(k.storeKey) store.Delete(GetDelegatorStartingInfoKey(val, del)) } func (k Keeper) IterateDelegatorStartingInfos(ctx sdk.Context, handler func(val sdk.ValAddress, del sdk.AccAddress, info types.DelegatorStartingInfo) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, DelegatorStartingInfoPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var info types.DelegatorStartingInfo k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &info) val, del := GetDelegatorStartingInfoAddresses(iter.Key()) if handler(val, del, info) { break } } } func (k Keeper) GetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64) (rewards types.ValidatorHistoricalRewards) { store := ctx.KVStore(k.storeKey) b := store.Get(GetValidatorHistoricalRewardsKey(val, period)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &rewards) return } func (k Keeper) SetValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewards) store.Set(GetValidatorHistoricalRewardsKey(val, period), b) } func (k Keeper) IterateValidatorHistoricalRewards(ctx sdk.Context, handler func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) addr, period := GetValidatorHistoricalRewardsAddressPeriod(iter.Key()) if handler(addr, period, rewards) { break } } } func (k Keeper) DeleteValidatorHistoricalReward(ctx sdk.Context, val sdk.ValAddress, period uint64) { store := ctx.KVStore(k.storeKey) store.Delete(GetValidatorHistoricalRewardsKey(val, period)) } func (k Keeper) DeleteValidatorHistoricalRewards(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, GetValidatorHistoricalRewardsPrefix(val)) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) } } func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx sdk.Context) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { store.Delete(iter.Key()) } } func (k Keeper) GetValidatorHistoricalReferenceCount(ctx sdk.Context) (count uint64) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorHistoricalRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorHistoricalRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) count += uint64(rewards.ReferenceCount) } return } func (k Keeper) GetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorCurrentRewards) { store := ctx.KVStore(k.storeKey) b := store.Get(GetValidatorCurrentRewardsKey(val)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &rewards) return } func (k Keeper) SetValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorCurrentRewards) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewards) store.Set(GetValidatorCurrentRewardsKey(val), b) } func (k Keeper) DeleteValidatorCurrentRewards(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) store.Delete(GetValidatorCurrentRewardsKey(val)) } func (k Keeper) IterateValidatorCurrentRewards(ctx sdk.Context, handler func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorCurrentRewardsPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var rewards types.ValidatorCurrentRewards k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &rewards) addr := GetValidatorCurrentRewardsAddress(iter.Key()) if handler(addr, rewards) { break } } } func (k Keeper) GetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress) (commission types.ValidatorAccumulatedCommission) { store := ctx.KVStore(k.storeKey) b := store.Get(GetValidatorAccumulatedCommissionKey(val)) if b == nil { return types.ValidatorAccumulatedCommission{} } k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &commission) return } func (k Keeper) SetValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) { var bz []byte store := ctx.KVStore(k.storeKey) if commission.IsZero() { bz = k.cdc.MustMarshalBinaryLengthPrefixed(types.InitialValidatorAccumulatedCommission()) } else { bz = k.cdc.MustMarshalBinaryLengthPrefixed(commission) } store.Set(GetValidatorAccumulatedCommissionKey(val), bz) } func (k Keeper) DeleteValidatorAccumulatedCommission(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) store.Delete(GetValidatorAccumulatedCommissionKey(val)) } func (k Keeper) IterateValidatorAccumulatedCommissions(ctx sdk.Context, handler func(val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool)) { store := ctx.KVStore(k.storeKey) iter := sdk.KVStorePrefixIterator(store, ValidatorAccumulatedCommissionPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { var commission types.ValidatorAccumulatedCommission k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &commission) addr := GetValidatorAccumulatedCommissionAddress(iter.Key()) if handler(addr, commission) { break } } } func (k Keeper) GetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) (rewards types.ValidatorOutstandingRewards) { store := ctx.KVStore(k.storeKey) b := store.Get(GetValidatorOutstandingRewardsKey(val)) k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &rewards) return } func (k Keeper) SetValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) { store := ctx.KVStore(k.storeKey) b := k.cdc.MustMarshalBinaryLengthPrefixed(rewards) store.Set(GetValidatorOutstandingRewardsKey(val), b) } func (k Keeper) DeleteValidatorOutstandingRewards(ctx sdk.Context, val sdk.ValAddress) { store := ctx.KVStore(k.storeKey) store.Delete(GetValidatorOutstandingRewardsKey(val)) }
Apache License 2.0
danilopolani/gosc
slice_test.go
TestAnyString
go
func TestAnyString(t *testing.T) { t.Parallel() var tests = []struct { s []string expected bool }{ {[]string{"foo", "bar", "baz"}, true}, {[]string{"foo", "\u0062\u0061\u0072", "baz"}, true}, {[]string{"foo", "bar", "buz"}, true}, {[]string{"foo", "bur", "buz"}, false}, } for _, test := range tests { actual := AnyString(test.s, func(s string) bool { return strings.HasPrefix(s, "ba") }) if actual != test.expected { t.Errorf("Expected AnyString(%q, fn) to be %v, got %v", test.s, test.expected, actual) } } }
TestAnyString tests the AnyString function
https://github.com/danilopolani/gosc/blob/65b2f5cee088115ca0dfaa6fb195e43b35c0a34c/slice_test.go#L152-L173
package gosc import ( "strings" "testing" ) func TestMapString(t *testing.T) { t.Parallel() var tests = []struct { s []string expected []string }{ {[]string{"foo", "bar", "baz"}, []string{"FOO", "BAR", "BAZ"}}, {[]string{"foo", "\u0062\u0061\u0072", "baz"}, []string{"FOO", "BAR", "BAZ"}}, {[]string{}, []string{}}, } for _, test := range tests { actual := MapString(test.s, strings.ToUpper) if !EqSlices(&actual, &test.expected) { t.Errorf("Expected MapString(%q, fn) to be %q, got %v", test.s, test.expected, actual) } } } func TestMapInt(t *testing.T) { t.Parallel() var tests = []struct { s []int expected []int }{ {[]int{0, 2, 4}, []int{0, 4, 8}}, {[]int{}, []int{}}, {[]int{2, 4, 5}, []int{4, 8, 10}}, {[]int{-2}, []int{-4}}, } for _, test := range tests { actual := MapInt(test.s, func(i int) int { return i * 2 }) if !EqSlices(&actual, &test.expected) { t.Errorf("Expected MapInt(%q, fn) to be %q, got %v", test.s, test.expected, actual) } } } func TestFilterString(t *testing.T) { t.Parallel() var tests = []struct { s []string expected []string }{ {[]string{"foo", "bar", "baz"}, []string{"bar", "baz"}}, {[]string{"foo", "\u0062\u0061\u0072", "baz"}, []string{"bar", "baz"}}, {[]string{"foo", "far", "faz"}, []string{}}, {[]string{}, []string{}}, } for _, test := range tests { actual := FilterString(test.s, func(s string) bool { return strings.HasPrefix(s, "b") }) if !EqSlices(&actual, &test.expected) { t.Errorf("Expected FilterString(%q, fn) to be %q, got %v", test.s, test.expected, actual) } } } func TestFilterInt(t *testing.T) { t.Parallel() var tests = []struct { s []int expected []int }{ {[]int{0, 2, 4}, []int{0, 2, 4}}, {[]int{}, []int{}}, {[]int{2, 4, 5}, []int{2, 4}}, {[]int{5}, []int{}}, {[]int{-2, 4}, []int{-2, 4}}, } for _, test := range tests { actual := FilterInt(test.s, func(i int) bool { return i%2 == 0 }) if !EqSlices(&actual, &test.expected) { t.Errorf("Expected FilterString(%q, fn) to be %q, got %v", test.s, test.expected, actual) } } } func TestAllString(t *testing.T) { t.Parallel() var tests = []struct { s []string expected bool }{ {[]string{"boo", "bar", "baz"}, true}, {[]string{"boo", "\u0062\u0061\u0072", "baz"}, true}, {[]string{"foo", "bar", "baz"}, false}, {[]string{}, true}, } for _, test := range tests { actual := AllString(test.s, func(s string) bool { return strings.HasPrefix(s, "b") }) if actual != test.expected { t.Errorf("Expected AllString(%q, fn) to be %v, got %v", test.s, test.expected, actual) } } } func TestAllInt(t *testing.T) { t.Parallel() var tests = []struct { s []int expected bool }{ {[]int{0, 2, 4}, true}, {[]int{}, true}, {[]int{2, 4, 5}, false}, {[]int{5}, false}, {[]int{-2, 4}, true}, } for _, test := range tests { actual := AllInt(test.s, func(i int) bool { return i%2 == 0 }) if actual != test.expected { t.Errorf("Expected AllInt(%q, fn) to be %v, got %v", test.s, test.expected, actual) } } }
MIT License
dude333/rapina
reports/logger.go
Printf
go
func (l *Logger) Printf(format string, v ...interface{}) { l.output(fmt.Sprintf(format, v...)) }
Printf prints the plain text.
https://github.com/dude333/rapina/blob/edcff1ffd73a3cacca344d02c93bc51b43e5a8bf/reports/logger.go#L43-L45
package reports import ( "fmt" "io" "os" ) type Logger struct { out io.Writer buf []byte } func NewLogger(out io.Writer) *Logger { return &Logger{out: out} } func (l *Logger) SetOut(out io.Writer) { l.out = out } func (l *Logger) Run(format string, v ...interface{}) { s := fmt.Sprintf(format, v...) if len(s) > 0 && s[len(s)-1] == '\n' { s = s[:len(s)-1] } l.output("[ ] " + s) } func (l *Logger) Ok() { l.outputln("\r[✓]") } func (l *Logger) Nok() { l.outputln("\r[✗]") }
MIT License
contraband/autopilot
vendor/code.cloudfoundry.org/cli/api/cloudcontroller/ccv2/route.go
GetSpaceRoutes
go
func (client *Client) GetSpaceRoutes(spaceGUID string, queryParams ...QQuery) ([]Route, Warnings, error) { request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetSpaceRoutesRequest, URIParams: map[string]string{"space_guid": spaceGUID}, Query: FormatQueryParameters(queryParams), }) if err != nil { return nil, nil, err } var fullRoutesList []Route warnings, err := client.paginate(request, Route{}, func(item interface{}) error { if route, ok := item.(Route); ok { fullRoutesList = append(fullRoutesList, route) } else { return ccerror.UnknownObjectInListError{ Expected: Route{}, Unexpected: item, } } return nil }) return fullRoutesList, warnings, err }
GetSpaceRoutes returns a list of Routes associated with the provided Space GUID, and filtered by the provided queries.
https://github.com/contraband/autopilot/blob/1dc8b7d7d1636dde8b3d53e7a85cd62e7d5d647d/vendor/code.cloudfoundry.org/cli/api/cloudcontroller/ccv2/route.go#L156-L180
package ccv2 import ( "bytes" "encoding/json" "fmt" "net/http" "net/url" "code.cloudfoundry.org/cli/api/cloudcontroller" "code.cloudfoundry.org/cli/api/cloudcontroller/ccerror" "code.cloudfoundry.org/cli/api/cloudcontroller/ccv2/internal" "code.cloudfoundry.org/cli/api/cloudcontroller/ccversion" "code.cloudfoundry.org/cli/types" ) type Route struct { GUID string `json:"-"` Host string `json:"host,omitempty"` Path string `json:"path,omitempty"` Port types.NullInt `json:"port,omitempty"` DomainGUID string `json:"domain_guid"` SpaceGUID string `json:"space_guid"` } func (route *Route) UnmarshalJSON(data []byte) error { var ccRoute struct { Metadata internal.Metadata `json:"metadata"` Entity struct { Host string `json:"host"` Path string `json:"path"` Port types.NullInt `json:"port"` DomainGUID string `json:"domain_guid"` SpaceGUID string `json:"space_guid"` } `json:"entity"` } if err := json.Unmarshal(data, &ccRoute); err != nil { return err } route.GUID = ccRoute.Metadata.GUID route.Host = ccRoute.Entity.Host route.Path = ccRoute.Entity.Path route.Port = ccRoute.Entity.Port route.DomainGUID = ccRoute.Entity.DomainGUID route.SpaceGUID = ccRoute.Entity.SpaceGUID return nil } func (client *Client) UpdateRouteApplication(routeGUID string, appGUID string) (Route, Warnings, error) { request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PutRouteAppRequest, URIParams: map[string]string{ "app_guid": appGUID, "route_guid": routeGUID, }, }) if err != nil { return Route{}, nil, err } var route Route response := cloudcontroller.Response{ Result: &route, } err = client.connection.Make(request, &response) return route, response.Warnings, err } func (client *Client) DeleteRouteApplication(routeGUID string, appGUID string) (Warnings, error) { request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.DeleteRouteAppRequest, URIParams: map[string]string{ "app_guid": appGUID, "route_guid": routeGUID, }, }) if err != nil { return nil, err } var response cloudcontroller.Response err = client.connection.Make(request, &response) return response.Warnings, err } func (client *Client) CreateRoute(route Route, generatePort bool) (Route, Warnings, error) { body, err := json.Marshal(route) if err != nil { return Route{}, nil, err } request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.PostRouteRequest, Body: bytes.NewReader(body), }) if err != nil { return Route{}, nil, err } if generatePort { query := url.Values{} query.Add("generate_port", "true") request.URL.RawQuery = query.Encode() } var updatedRoute Route response := cloudcontroller.Response{ Result: &updatedRoute, } err = client.connection.Make(request, &response) return updatedRoute, response.Warnings, err } func (client *Client) GetApplicationRoutes(appGUID string, queryParams ...QQuery) ([]Route, Warnings, error) { request, err := client.newHTTPRequest(requestOptions{ RequestName: internal.GetAppRoutesRequest, URIParams: map[string]string{"app_guid": appGUID}, Query: FormatQueryParameters(queryParams), }) if err != nil { return nil, nil, err } var fullRoutesList []Route warnings, err := client.paginate(request, Route{}, func(item interface{}) error { if route, ok := item.(Route); ok { fullRoutesList = append(fullRoutesList, route) } else { return ccerror.UnknownObjectInListError{ Expected: Route{}, Unexpected: item, } } return nil }) return fullRoutesList, warnings, err }
Apache License 2.0
iann0036/iamlive-lambda-extension
iamlive/vendor/github.com/golang-collections/go-datastructures/queue/queue.go
Len
go
func (q *Queue) Len() int64 { q.lock.Lock() defer q.lock.Unlock() return int64(len(q.items)) }
Len returns the number of items in this queue.
https://github.com/iann0036/iamlive-lambda-extension/blob/b4505e9521e9f919151b71556b799eacb12230f5/iamlive/vendor/github.com/golang-collections/go-datastructures/queue/queue.go#L242-L247
package queue import ( "runtime" "sync" "sync/atomic" ) type waiters []*sema func (w *waiters) get() *sema { if len(*w) == 0 { return nil } sema := (*w)[0] copy((*w)[0:], (*w)[1:]) (*w)[len(*w)-1] = nil *w = (*w)[:len(*w)-1] return sema } func (w *waiters) put(sema *sema) { *w = append(*w, sema) } type items []interface{} func (items *items) get(number int64) []interface{} { returnItems := make([]interface{}, 0, number) index := int64(0) for i := int64(0); i < number; i++ { if i >= int64(len(*items)) { break } returnItems = append(returnItems, (*items)[i]) (*items)[i] = nil index++ } *items = (*items)[index:] return returnItems } func (items *items) getUntil(checker func(item interface{}) bool) []interface{} { length := len(*items) if len(*items) == 0 { return []interface{}{} } returnItems := make([]interface{}, 0, length) index := 0 for i, item := range *items { if !checker(item) { break } returnItems = append(returnItems, item) index = i } *items = (*items)[index:] return returnItems } type sema struct { wg *sync.WaitGroup response *sync.WaitGroup } func newSema() *sema { return &sema{ wg: &sync.WaitGroup{}, response: &sync.WaitGroup{}, } } type Queue struct { waiters waiters items items lock sync.Mutex disposed bool } func (q *Queue) Put(items ...interface{}) error { if len(items) == 0 { return nil } q.lock.Lock() if q.disposed { q.lock.Unlock() return disposedError } q.items = append(q.items, items...) for { sema := q.waiters.get() if sema == nil { break } sema.response.Add(1) sema.wg.Done() sema.response.Wait() if len(q.items) == 0 { break } } q.lock.Unlock() return nil } func (q *Queue) Get(number int64) ([]interface{}, error) { if number < 1 { return []interface{}{}, nil } q.lock.Lock() if q.disposed { q.lock.Unlock() return nil, disposedError } var items []interface{} if len(q.items) == 0 { sema := newSema() q.waiters.put(sema) sema.wg.Add(1) q.lock.Unlock() sema.wg.Wait() if q.disposed { return nil, disposedError } items = q.items.get(number) sema.response.Done() return items, nil } items = q.items.get(number) q.lock.Unlock() return items, nil } func (q *Queue) TakeUntil(checker func(item interface{}) bool) ([]interface{}, error) { if checker == nil { return nil, nil } q.lock.Lock() if q.disposed { q.lock.Unlock() return nil, disposedError } result := q.items.getUntil(checker) q.lock.Unlock() return result, nil } func (q *Queue) Empty() bool { q.lock.Lock() defer q.lock.Unlock() return len(q.items) == 0 }
MIT License
terra-project/mantle-sdk
lcd/client/transactions/get_txs_hash_parameters.go
WriteToRequest
go
func (o *GetTxsHashParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if err := r.SetPathParam("hash", o.Hash); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
WriteToRequest writes these params to a swagger request
https://github.com/terra-project/mantle-sdk/blob/99e0b656c1de904ea98ce778fa339f8b9dcbaece/lcd/client/transactions/get_txs_hash_parameters.go#L119-L135
package transactions import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" ) func NewGetTxsHashParams() *GetTxsHashParams { var () return &GetTxsHashParams{ timeout: cr.DefaultTimeout, } } func NewGetTxsHashParamsWithTimeout(timeout time.Duration) *GetTxsHashParams { var () return &GetTxsHashParams{ timeout: timeout, } } func NewGetTxsHashParamsWithContext(ctx context.Context) *GetTxsHashParams { var () return &GetTxsHashParams{ Context: ctx, } } func NewGetTxsHashParamsWithHTTPClient(client *http.Client) *GetTxsHashParams { var () return &GetTxsHashParams{ HTTPClient: client, } } type GetTxsHashParams struct { Hash string timeout time.Duration Context context.Context HTTPClient *http.Client } func (o *GetTxsHashParams) WithTimeout(timeout time.Duration) *GetTxsHashParams { o.SetTimeout(timeout) return o } func (o *GetTxsHashParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } func (o *GetTxsHashParams) WithContext(ctx context.Context) *GetTxsHashParams { o.SetContext(ctx) return o } func (o *GetTxsHashParams) SetContext(ctx context.Context) { o.Context = ctx } func (o *GetTxsHashParams) WithHTTPClient(client *http.Client) *GetTxsHashParams { o.SetHTTPClient(client) return o } func (o *GetTxsHashParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } func (o *GetTxsHashParams) WithHash(hash string) *GetTxsHashParams { o.SetHash(hash) return o } func (o *GetTxsHashParams) SetHash(hash string) { o.Hash = hash }
Apache License 2.0
socketplane/socketplane
Godeps/_workspace/src/github.com/hashicorp/consul/consul/state_store.go
GetNode
go
func (s *StateStore) GetNode(name string) (uint64, bool, string) { idx, res, err := s.nodeTable.Get("id", name) if err != nil { s.logger.Printf("[ERR] consul.state: Error during node lookup: %v", err) return 0, false, "" } if len(res) == 0 { return idx, false, "" } return idx, true, res[0].(*structs.Node).Address }
GetNode returns all the address of the known and if it was found
https://github.com/socketplane/socketplane/blob/bc8b7e0e5ddf354c857a77b5cdfb904540026373/Godeps/_workspace/src/github.com/hashicorp/consul/consul/state_store.go#L538-L548
package consul import ( "fmt" "io" "io/ioutil" "log" "os" "runtime" "strings" "sync" "time" "github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/armon/go-radix" "github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/armon/gomdb" "github.com/socketplane/socketplane/Godeps/_workspace/src/github.com/hashicorp/consul/consul/structs" ) const ( dbNodes = "nodes" dbServices = "services" dbChecks = "checks" dbKVS = "kvs" dbTombstone = "tombstones" dbSessions = "sessions" dbSessionChecks = "sessionChecks" dbACLs = "acls" dbMaxMapSize32bit uint64 = 128 * 1024 * 1024 dbMaxMapSize64bit uint64 = 32 * 1024 * 1024 * 1024 dbMaxReaders uint = 4096 ) type kvMode int const ( kvSet kvMode = iota kvCAS kvLock kvUnlock ) type StateStore struct { logger *log.Logger path string env *mdb.Env nodeTable *MDBTable serviceTable *MDBTable checkTable *MDBTable kvsTable *MDBTable tombstoneTable *MDBTable sessionTable *MDBTable sessionCheckTable *MDBTable aclTable *MDBTable tables MDBTables watch map[*MDBTable]*NotifyGroup queryTables map[string]MDBTables kvWatch *radix.Tree kvWatchLock sync.Mutex lockDelay map[string]time.Time lockDelayLock sync.RWMutex gc *TombstoneGC } type StateSnapshot struct { store *StateStore tx *MDBTxn lastIndex uint64 } type sessionCheck struct { Node string CheckID string Session string } func (s *StateSnapshot) Close() error { s.tx.Abort() return nil } func NewStateStore(gc *TombstoneGC, logOutput io.Writer) (*StateStore, error) { path, err := ioutil.TempDir("", "consul") if err != nil { return nil, err } return NewStateStorePath(gc, path, logOutput) } func NewStateStorePath(gc *TombstoneGC, path string, logOutput io.Writer) (*StateStore, error) { env, err := mdb.NewEnv() if err != nil { return nil, err } s := &StateStore{ logger: log.New(logOutput, "", log.LstdFlags), path: path, env: env, watch: make(map[*MDBTable]*NotifyGroup), kvWatch: radix.New(), lockDelay: make(map[string]time.Time), gc: gc, } if err := s.initialize(); err != nil { env.Close() os.RemoveAll(path) return nil, err } return s, nil } func (s *StateStore) Close() error { s.env.Close() os.RemoveAll(s.path) return nil } func (s *StateStore) initialize() error { if err := s.env.SetMaxDBs(mdb.DBI(32)); err != nil { return err } dbSize := dbMaxMapSize32bit if runtime.GOARCH == "amd64" { dbSize = dbMaxMapSize64bit } if err := s.env.SetMapSize(dbSize); err != nil { return err } if err := s.env.SetMaxReaders(dbMaxReaders); err != nil { return err } var flags uint = mdb.NOMETASYNC | mdb.NOSYNC | mdb.NOTLS if err := s.env.Open(s.path, flags, 0755); err != nil { return err } encoder := func(obj interface{}) []byte { buf, err := structs.Encode(255, obj) if err != nil { panic(err) } return buf[1:] } s.nodeTable = &MDBTable{ Name: dbNodes, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"Node"}, CaseInsensitive: true, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.Node) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.serviceTable = &MDBTable{ Name: dbServices, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"Node", "ServiceID"}, }, "service": &MDBIndex{ AllowBlank: true, Fields: []string{"ServiceName"}, CaseInsensitive: true, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.ServiceNode) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.checkTable = &MDBTable{ Name: dbChecks, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"Node", "CheckID"}, }, "status": &MDBIndex{ Fields: []string{"Status"}, }, "service": &MDBIndex{ AllowBlank: true, Fields: []string{"ServiceName"}, }, "node": &MDBIndex{ AllowBlank: true, Fields: []string{"Node", "ServiceID"}, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.HealthCheck) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.kvsTable = &MDBTable{ Name: dbKVS, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"Key"}, }, "id_prefix": &MDBIndex{ Virtual: true, RealIndex: "id", Fields: []string{"Key"}, IdxFunc: DefaultIndexPrefixFunc, }, "session": &MDBIndex{ AllowBlank: true, Fields: []string{"Session"}, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.DirEntry) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.tombstoneTable = &MDBTable{ Name: dbTombstone, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"Key"}, }, "id_prefix": &MDBIndex{ Virtual: true, RealIndex: "id", Fields: []string{"Key"}, IdxFunc: DefaultIndexPrefixFunc, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.DirEntry) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.sessionTable = &MDBTable{ Name: dbSessions, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"ID"}, }, "node": &MDBIndex{ AllowBlank: true, Fields: []string{"Node"}, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.Session) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.sessionCheckTable = &MDBTable{ Name: dbSessionChecks, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"Node", "CheckID", "Session"}, }, }, Decoder: func(buf []byte) interface{} { out := new(sessionCheck) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.aclTable = &MDBTable{ Name: dbACLs, Indexes: map[string]*MDBIndex{ "id": &MDBIndex{ Unique: true, Fields: []string{"ID"}, }, }, Decoder: func(buf []byte) interface{} { out := new(structs.ACL) if err := structs.Decode(buf, out); err != nil { panic(err) } return out }, } s.tables = []*MDBTable{s.nodeTable, s.serviceTable, s.checkTable, s.kvsTable, s.tombstoneTable, s.sessionTable, s.sessionCheckTable, s.aclTable} for _, table := range s.tables { table.Env = s.env table.Encoder = encoder if err := table.Init(); err != nil { return err } s.watch[table] = &NotifyGroup{} } s.queryTables = map[string]MDBTables{ "Nodes": MDBTables{s.nodeTable}, "Services": MDBTables{s.serviceTable}, "ServiceNodes": MDBTables{s.nodeTable, s.serviceTable}, "NodeServices": MDBTables{s.nodeTable, s.serviceTable}, "ChecksInState": MDBTables{s.checkTable}, "NodeChecks": MDBTables{s.checkTable}, "ServiceChecks": MDBTables{s.checkTable}, "CheckServiceNodes": MDBTables{s.nodeTable, s.serviceTable, s.checkTable}, "NodeInfo": MDBTables{s.nodeTable, s.serviceTable, s.checkTable}, "NodeDump": MDBTables{s.nodeTable, s.serviceTable, s.checkTable}, "SessionGet": MDBTables{s.sessionTable}, "SessionList": MDBTables{s.sessionTable}, "NodeSessions": MDBTables{s.sessionTable}, "ACLGet": MDBTables{s.aclTable}, "ACLList": MDBTables{s.aclTable}, } return nil } func (s *StateStore) Watch(tables MDBTables, notify chan struct{}) { for _, t := range tables { s.watch[t].Wait(notify) } } func (s *StateStore) WatchKV(prefix string, notify chan struct{}) { s.kvWatchLock.Lock() defer s.kvWatchLock.Unlock() if raw, ok := s.kvWatch.Get(prefix); ok { grp := raw.(*NotifyGroup) grp.Wait(notify) return } grp := &NotifyGroup{} grp.Wait(notify) s.kvWatch.Insert(prefix, grp) } func (s *StateStore) notifyKV(path string, prefix bool) { s.kvWatchLock.Lock() defer s.kvWatchLock.Unlock() var toDelete []string fn := func(s string, v interface{}) bool { group := v.(*NotifyGroup) group.Notify() if s != "" { toDelete = append(toDelete, s) } return false } s.kvWatch.WalkPath(path, fn) if prefix { s.kvWatch.WalkPrefix(path, fn) } for i := len(toDelete) - 1; i >= 0; i-- { s.kvWatch.Delete(toDelete[i]) } } func (s *StateStore) QueryTables(q string) MDBTables { return s.queryTables[q] } func (s *StateStore) EnsureRegistration(index uint64, req *structs.RegisterRequest) error { tx, err := s.tables.StartTxn(false) if err != nil { panic(fmt.Errorf("Failed to start txn: %v", err)) } defer tx.Abort() node := structs.Node{req.Node, req.Address} if err := s.ensureNodeTxn(index, node, tx); err != nil { return err } if req.Service != nil { if err := s.ensureServiceTxn(index, req.Node, req.Service, tx); err != nil { return err } } if req.Check != nil { if err := s.ensureCheckTxn(index, req.Check, tx); err != nil { return err } } return tx.Commit() } func (s *StateStore) EnsureNode(index uint64, node structs.Node) error { tx, err := s.nodeTable.StartTxn(false, nil) if err != nil { return err } defer tx.Abort() if err := s.ensureNodeTxn(index, node, tx); err != nil { return err } return tx.Commit() } func (s *StateStore) ensureNodeTxn(index uint64, node structs.Node, tx *MDBTxn) error { if err := s.nodeTable.InsertTxn(tx, node); err != nil { return err } if err := s.nodeTable.SetLastIndexTxn(tx, index); err != nil { return err } tx.Defer(func() { s.watch[s.nodeTable].Notify() }) return nil }
Apache License 2.0
kyma-project/helm-broker
internal/broker/middleware.go
ServeHTTP
go
func (RequireAsyncMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { if r.URL.Query().Get("accepts_incomplete") != "true" { writeErrorResponse(rw, http.StatusUnprocessableEntity, "AsyncRequired", "This service plan requires client support for asynchronous service operations.") return } next(rw, r) }
ServeHTTP handling asynchronous HTTP requests in Open Service Broker Api
https://github.com/kyma-project/helm-broker/blob/ac685995cdd6f980dab815b8ebde01d34586e587/internal/broker/middleware.go#L44-L52
package broker import ( "net/http" "github.com/gorilla/mux" osb "github.com/kubernetes-sigs/go-open-service-broker-client/v2" "github.com/kyma-project/helm-broker/internal" ) type OSBContextMiddleware struct{} func (OSBContextMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { brokerNamespace := mux.Vars(r)["namespace"] if brokerNamespace == "" { brokerNamespace = string(internal.ClusterWide) } osbCtx := OsbContext{ APIVersion: r.Header.Get(osb.APIVersionHeader), OriginatingIdentity: r.Header.Get(osb.OriginatingIdentityHeader), BrokerNamespace: internal.Namespace(brokerNamespace), } if err := osbCtx.validateAPIVersion(); err != nil { writeErrorResponse(rw, http.StatusPreconditionFailed, err.Error(), "Requests requires the 'X-Broker-API-Version' header specified") return } if err := osbCtx.validateOriginatingIdentity(); err != nil { writeErrorResponse(rw, http.StatusPreconditionFailed, err.Error(), "Requests requires the 'X-Broker-API-Originating-Identity' header specified") return } r = r.WithContext(contextWithOSB(r.Context(), osbCtx)) next(rw, r) } type RequireAsyncMiddleware struct{}
Apache License 2.0
algorand/go-algorand-sdk
templates/template.go
GetProgram
go
func (contract ContractTemplate) GetProgram() []byte { return contract.program }
GetProgram returns the program bytes
https://github.com/algorand/go-algorand-sdk/blob/8de2dff28607866c65a8b346835cbf02ae6eb520/templates/template.go#L25-L27
package templates import ( "encoding/base64" "encoding/binary" "fmt" "github.com/algorand/go-algorand-sdk/types" ) type ContractTemplate struct { address string program []byte } func (contract ContractTemplate) GetAddress() string { return contract.address }
MIT License
linki/mate
vendor/github.com/coreos/go-oidc/oidc/util.go
CookieTokenExtractor
go
func CookieTokenExtractor(cookieName string) RequestTokenExtractor { return func(r *http.Request) (string, error) { ck, err := r.Cookie(cookieName) if err != nil { return "", fmt.Errorf("token cookie not found in request: %v", err) } if ck.Value == "" { return "", errors.New("token cookie found but is empty") } return ck.Value, nil } }
CookieTokenExtractor returns a RequestTokenExtractor which extracts a token from the named cookie in a request.
https://github.com/linki/mate/blob/848c39ec72b8cfe26b38cc62a6b1286c8b868f51/vendor/github.com/coreos/go-oidc/oidc/util.go#L41-L54
package oidc import ( "crypto/rand" "encoding/base64" "errors" "fmt" "net" "net/http" "net/url" "strings" "time" "github.com/coreos/go-oidc/jose" ) type RequestTokenExtractor func(r *http.Request) (string, error) func ExtractBearerToken(r *http.Request) (string, error) { ah := r.Header.Get("Authorization") if ah == "" { return "", errors.New("missing Authorization header") } if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" { return "", errors.New("should be a bearer token") } val := ah[7:] if len(val) == 0 { return "", errors.New("bearer token is empty") } return val, nil }
MIT License
changkun/redir
vendor/github.com/aws/aws-sdk-go/aws/convert_types.go
Int8ValueMap
go
func Int8ValueMap(src map[string]*int8) map[string]int8 { dst := make(map[string]int8) for k, val := range src { if val != nil { dst[k] = *val } } return dst }
Int8ValueMap converts a string map of int8 pointers into a string map of int8 values
https://github.com/changkun/redir/blob/45ca46c930968bcdc4c3880b8717ac0a6829a262/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go#L290-L298
package aws import "time" func String(v string) *string { return &v } func StringValue(v *string) string { if v != nil { return *v } return "" } func StringSlice(src []string) []*string { dst := make([]*string, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } func StringValueSlice(src []*string) []string { dst := make([]string, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } func StringMap(src map[string]string) map[string]*string { dst := make(map[string]*string) for k, val := range src { v := val dst[k] = &v } return dst } func StringValueMap(src map[string]*string) map[string]string { dst := make(map[string]string) for k, val := range src { if val != nil { dst[k] = *val } } return dst } func Bool(v bool) *bool { return &v } func BoolValue(v *bool) bool { if v != nil { return *v } return false } func BoolSlice(src []bool) []*bool { dst := make([]*bool, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } func BoolValueSlice(src []*bool) []bool { dst := make([]bool, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } func BoolMap(src map[string]bool) map[string]*bool { dst := make(map[string]*bool) for k, val := range src { v := val dst[k] = &v } return dst } func BoolValueMap(src map[string]*bool) map[string]bool { dst := make(map[string]bool) for k, val := range src { if val != nil { dst[k] = *val } } return dst } func Int(v int) *int { return &v } func IntValue(v *int) int { if v != nil { return *v } return 0 } func IntSlice(src []int) []*int { dst := make([]*int, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } func IntValueSlice(src []*int) []int { dst := make([]int, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } func IntMap(src map[string]int) map[string]*int { dst := make(map[string]*int) for k, val := range src { v := val dst[k] = &v } return dst } func IntValueMap(src map[string]*int) map[string]int { dst := make(map[string]int) for k, val := range src { if val != nil { dst[k] = *val } } return dst } func Uint(v uint) *uint { return &v } func UintValue(v *uint) uint { if v != nil { return *v } return 0 } func UintSlice(src []uint) []*uint { dst := make([]*uint, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } func UintValueSlice(src []*uint) []uint { dst := make([]uint, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } func UintMap(src map[string]uint) map[string]*uint { dst := make(map[string]*uint) for k, val := range src { v := val dst[k] = &v } return dst } func UintValueMap(src map[string]*uint) map[string]uint { dst := make(map[string]uint) for k, val := range src { if val != nil { dst[k] = *val } } return dst } func Int8(v int8) *int8 { return &v } func Int8Value(v *int8) int8 { if v != nil { return *v } return 0 } func Int8Slice(src []int8) []*int8 { dst := make([]*int8, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } func Int8ValueSlice(src []*int8) []int8 { dst := make([]int8, len(src)) for i := 0; i < len(src); i++ { if src[i] != nil { dst[i] = *(src[i]) } } return dst } func Int8Map(src map[string]int8) map[string]*int8 { dst := make(map[string]*int8) for k, val := range src { v := val dst[k] = &v } return dst }
MIT License
sqless/sqless
types/issuekeys.go
Sign
go
func (ik *IssueKeys) Sign(signer *asymmetric.PrivateKey) (err error) { return ik.DefaultHashSignVerifierImpl.Sign(&ik.IssueKeysHeader, signer) }
Sign implements interfaces/Transaction.Sign.
https://github.com/sqless/sqless/blob/2f82fc2898bf872c91596ad2541668f252dfc694/types/issuekeys.go#L63-L65
package types import ( "github.com/SQLess/SQLess/blockproducer/interfaces" "github.com/SQLess/SQLess/crypto" "github.com/SQLess/SQLess/crypto/asymmetric" "github.com/SQLess/SQLess/crypto/verifier" "github.com/SQLess/SQLess/proto" ) type MinerKey struct { Miner proto.AccountAddress EncryptionKey string } type IssueKeysHeader struct { TargetSQLChain proto.AccountAddress MinerKeys []MinerKey Nonce interfaces.AccountNonce } func (h *IssueKeysHeader) GetAccountNonce() interfaces.AccountNonce { return h.Nonce } type IssueKeys struct { IssueKeysHeader interfaces.TransactionTypeMixin verifier.DefaultHashSignVerifierImpl } func NewIssueKeys(header *IssueKeysHeader) *IssueKeys { return &IssueKeys{ IssueKeysHeader: *header, TransactionTypeMixin: *interfaces.NewTransactionTypeMixin(interfaces.TransactionTypeIssueKeys), } }
Apache License 2.0
googlecloudplatform/gcp-service-broker
brokerapi/brokers/brokers_test.go
BindDetails
go
func (s *serviceStub) BindDetails() brokerapi.BindDetails { return brokerapi.BindDetails{ ServiceID: s.ServiceId, PlanID: s.PlanId, } }
BindDetails creates a brokerapi.BindDetails object valid for the given service.
https://github.com/googlecloudplatform/gcp-service-broker/blob/6c394c65edb35b7551fc4db03df2895661ecd8ba/brokerapi/brokers/brokers_test.go#L90-L95
package brokers_test import ( "context" "encoding/json" "errors" "os" "reflect" "testing" . "github.com/GoogleCloudPlatform/gcp-service-broker/brokerapi/brokers" "github.com/GoogleCloudPlatform/gcp-service-broker/db_service" "github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models" "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker" "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker/brokerfakes" "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin" "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base" "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/storage" "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext" "github.com/GoogleCloudPlatform/gcp-service-broker/utils" "github.com/pivotal-cf/brokerapi" "google.golang.org/api/googleapi" "code.cloudfoundry.org/lager" "github.com/jinzhu/gorm" "golang.org/x/oauth2/jwt" ) type InstanceState int const ( StateNone InstanceState = iota StateProvisioned StateBound StateUnbound StateDeprovisioned ) const ( fakeInstanceId = "newid" fakeBindingId = "newbinding" ) type serviceStub struct { ServiceId string PlanId string Provider *brokerfakes.FakeServiceProvider ServiceDefinition *broker.ServiceDefinition } func (s *serviceStub) ProvisionDetails() brokerapi.ProvisionDetails { return brokerapi.ProvisionDetails{ ServiceID: s.ServiceId, PlanID: s.PlanId, } } func (s *serviceStub) DeprovisionDetails() brokerapi.DeprovisionDetails { return brokerapi.DeprovisionDetails{ ServiceID: s.ServiceId, PlanID: s.PlanId, } }
Apache License 2.0
go-chi/chi
tree.go
tailSort
go
func (ns nodes) tailSort() { for i := len(ns) - 1; i >= 0; i-- { if ns[i].typ > ntStatic && ns[i].tail == '/' { ns.Swap(i, len(ns)-1) return } } }
tailSort pushes nodes with '/' as the tail to the end of the list for param nodes. The list order determines the traversal order.
https://github.com/go-chi/chi/blob/df44563f0692b1e677f18220b9be165e481cf51b/tree.go#L786-L793
package chi import ( "fmt" "net/http" "regexp" "sort" "strconv" "strings" ) type methodTyp uint const ( mSTUB methodTyp = 1 << iota mCONNECT mDELETE mGET mHEAD mOPTIONS mPATCH mPOST mPUT mTRACE ) var mALL = mCONNECT | mDELETE | mGET | mHEAD | mOPTIONS | mPATCH | mPOST | mPUT | mTRACE var methodMap = map[string]methodTyp{ http.MethodConnect: mCONNECT, http.MethodDelete: mDELETE, http.MethodGet: mGET, http.MethodHead: mHEAD, http.MethodOptions: mOPTIONS, http.MethodPatch: mPATCH, http.MethodPost: mPOST, http.MethodPut: mPUT, http.MethodTrace: mTRACE, } func RegisterMethod(method string) { if method == "" { return } method = strings.ToUpper(method) if _, ok := methodMap[method]; ok { return } n := len(methodMap) if n > strconv.IntSize-2 { panic(fmt.Sprintf("chi: max number of methods reached (%d)", strconv.IntSize)) } mt := methodTyp(2 << n) methodMap[method] = mt mALL |= mt } type nodeTyp uint8 const ( ntStatic nodeTyp = iota ntRegexp ntParam ntCatchAll ) type node struct { subroutes Routes rex *regexp.Regexp endpoints endpoints prefix string children [ntCatchAll + 1]nodes tail byte typ nodeTyp label byte } type endpoints map[methodTyp]*endpoint type endpoint struct { handler http.Handler pattern string paramKeys []string } func (s endpoints) Value(method methodTyp) *endpoint { mh, ok := s[method] if !ok { mh = &endpoint{} s[method] = mh } return mh } func (n *node) InsertRoute(method methodTyp, pattern string, handler http.Handler) *node { var parent *node search := pattern for { if len(search) == 0 { n.setEndpoint(method, handler, pattern) return n } var label = search[0] var segTail byte var segEndIdx int var segTyp nodeTyp var segRexpat string if label == '{' || label == '*' { segTyp, _, segRexpat, segTail, _, segEndIdx = patNextSegment(search) } var prefix string if segTyp == ntRegexp { prefix = segRexpat } parent = n n = n.getEdge(segTyp, label, segTail, prefix) if n == nil { child := &node{label: label, tail: segTail, prefix: search} hn := parent.addChild(child, search) hn.setEndpoint(method, handler, pattern) return hn } if n.typ > ntStatic { search = search[segEndIdx:] continue } commonPrefix := longestPrefix(search, n.prefix) if commonPrefix == len(n.prefix) { search = search[commonPrefix:] continue } child := &node{ typ: ntStatic, prefix: search[:commonPrefix], } parent.replaceChild(search[0], segTail, child) n.label = n.prefix[commonPrefix] n.prefix = n.prefix[commonPrefix:] child.addChild(n, n.prefix) search = search[commonPrefix:] if len(search) == 0 { child.setEndpoint(method, handler, pattern) return child } subchild := &node{ typ: ntStatic, label: search[0], prefix: search, } hn := child.addChild(subchild, search) hn.setEndpoint(method, handler, pattern) return hn } } func (n *node) addChild(child *node, prefix string) *node { search := prefix hn := child segTyp, _, segRexpat, segTail, segStartIdx, segEndIdx := patNextSegment(search) switch segTyp { case ntStatic: default: if segTyp == ntRegexp { rex, err := regexp.Compile(segRexpat) if err != nil { panic(fmt.Sprintf("chi: invalid regexp pattern '%s' in route param", segRexpat)) } child.prefix = segRexpat child.rex = rex } if segStartIdx == 0 { child.typ = segTyp if segTyp == ntCatchAll { segStartIdx = -1 } else { segStartIdx = segEndIdx } if segStartIdx < 0 { segStartIdx = len(search) } child.tail = segTail if segStartIdx != len(search) { search = search[segStartIdx:] nn := &node{ typ: ntStatic, label: search[0], prefix: search, } hn = child.addChild(nn, search) } } else if segStartIdx > 0 { child.typ = ntStatic child.prefix = search[:segStartIdx] child.rex = nil search = search[segStartIdx:] nn := &node{ typ: segTyp, label: search[0], tail: segTail, } hn = child.addChild(nn, search) } } n.children[child.typ] = append(n.children[child.typ], child) n.children[child.typ].Sort() return hn } func (n *node) replaceChild(label, tail byte, child *node) { for i := 0; i < len(n.children[child.typ]); i++ { if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail { n.children[child.typ][i] = child n.children[child.typ][i].label = label n.children[child.typ][i].tail = tail return } } panic("chi: replacing missing child") } func (n *node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *node { nds := n.children[ntyp] for i := 0; i < len(nds); i++ { if nds[i].label == label && nds[i].tail == tail { if ntyp == ntRegexp && nds[i].prefix != prefix { continue } return nds[i] } } return nil } func (n *node) setEndpoint(method methodTyp, handler http.Handler, pattern string) { if n.endpoints == nil { n.endpoints = make(endpoints) } paramKeys := patParamKeys(pattern) if method&mSTUB == mSTUB { n.endpoints.Value(mSTUB).handler = handler } if method&mALL == mALL { h := n.endpoints.Value(mALL) h.handler = handler h.pattern = pattern h.paramKeys = paramKeys for _, m := range methodMap { h := n.endpoints.Value(m) h.handler = handler h.pattern = pattern h.paramKeys = paramKeys } } else { h := n.endpoints.Value(method) h.handler = handler h.pattern = pattern h.paramKeys = paramKeys } } func (n *node) FindRoute(rctx *Context, method methodTyp, path string) (*node, endpoints, http.Handler) { rctx.routePattern = "" rctx.routeParams.Keys = rctx.routeParams.Keys[:0] rctx.routeParams.Values = rctx.routeParams.Values[:0] rn := n.findRoute(rctx, method, path) if rn == nil { return nil, nil, nil } rctx.URLParams.Keys = append(rctx.URLParams.Keys, rctx.routeParams.Keys...) rctx.URLParams.Values = append(rctx.URLParams.Values, rctx.routeParams.Values...) if rn.endpoints[method].pattern != "" { rctx.routePattern = rn.endpoints[method].pattern rctx.RoutePatterns = append(rctx.RoutePatterns, rctx.routePattern) } return rn, rn.endpoints, rn.endpoints[method].handler } func (n *node) findRoute(rctx *Context, method methodTyp, path string) *node { nn := n search := path for t, nds := range nn.children { ntyp := nodeTyp(t) if len(nds) == 0 { continue } var xn *node xsearch := search var label byte if search != "" { label = search[0] } switch ntyp { case ntStatic: xn = nds.findEdge(label) if xn == nil || !strings.HasPrefix(xsearch, xn.prefix) { continue } xsearch = xsearch[len(xn.prefix):] case ntParam, ntRegexp: if xsearch == "" { continue } for idx := 0; idx < len(nds); idx++ { xn = nds[idx] p := strings.IndexByte(xsearch, xn.tail) if p < 0 { if xn.tail == '/' { p = len(xsearch) } else { continue } } else if ntyp == ntRegexp && p == 0 { continue } if ntyp == ntRegexp && xn.rex != nil { if !xn.rex.MatchString(xsearch[:p]) { continue } } else if strings.IndexByte(xsearch[:p], '/') != -1 { continue } prevlen := len(rctx.routeParams.Values) rctx.routeParams.Values = append(rctx.routeParams.Values, xsearch[:p]) xsearch = xsearch[p:] if len(xsearch) == 0 { if xn.isLeaf() { h := xn.endpoints[method] if h != nil && h.handler != nil { rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...) return xn } rctx.methodNotAllowed = true } } fin := xn.findRoute(rctx, method, xsearch) if fin != nil { return fin } rctx.routeParams.Values = rctx.routeParams.Values[:prevlen] xsearch = search } rctx.routeParams.Values = append(rctx.routeParams.Values, "") default: rctx.routeParams.Values = append(rctx.routeParams.Values, search) xn = nds[0] xsearch = "" } if xn == nil { continue } if len(xsearch) == 0 { if xn.isLeaf() { h := xn.endpoints[method] if h != nil && h.handler != nil { rctx.routeParams.Keys = append(rctx.routeParams.Keys, h.paramKeys...) return xn } rctx.methodNotAllowed = true } } fin := xn.findRoute(rctx, method, xsearch) if fin != nil { return fin } if xn.typ > ntStatic { if len(rctx.routeParams.Values) > 0 { rctx.routeParams.Values = rctx.routeParams.Values[:len(rctx.routeParams.Values)-1] } } } return nil } func (n *node) findEdge(ntyp nodeTyp, label byte) *node { nds := n.children[ntyp] num := len(nds) idx := 0 switch ntyp { case ntStatic, ntParam, ntRegexp: i, j := 0, num-1 for i <= j { idx = i + (j-i)/2 if label > nds[idx].label { i = idx + 1 } else if label < nds[idx].label { j = idx - 1 } else { i = num } } if nds[idx].label != label { return nil } return nds[idx] default: return nds[idx] } } func (n *node) isLeaf() bool { return n.endpoints != nil } func (n *node) findPattern(pattern string) bool { nn := n for _, nds := range nn.children { if len(nds) == 0 { continue } n = nn.findEdge(nds[0].typ, pattern[0]) if n == nil { continue } var idx int var xpattern string switch n.typ { case ntStatic: idx = longestPrefix(pattern, n.prefix) if idx < len(n.prefix) { continue } case ntParam, ntRegexp: idx = strings.IndexByte(pattern, '}') + 1 case ntCatchAll: idx = longestPrefix(pattern, "*") default: panic("chi: unknown node type") } xpattern = pattern[idx:] if len(xpattern) == 0 { return true } return n.findPattern(xpattern) } return false } func (n *node) routes() []Route { rts := []Route{} n.walk(func(eps endpoints, subroutes Routes) bool { if eps[mSTUB] != nil && eps[mSTUB].handler != nil && subroutes == nil { return false } pats := make(map[string]endpoints) for mt, h := range eps { if h.pattern == "" { continue } p, ok := pats[h.pattern] if !ok { p = endpoints{} pats[h.pattern] = p } p[mt] = h } for p, mh := range pats { hs := make(map[string]http.Handler) if mh[mALL] != nil && mh[mALL].handler != nil { hs["*"] = mh[mALL].handler } for mt, h := range mh { if h.handler == nil { continue } m := methodTypString(mt) if m == "" { continue } hs[m] = h.handler } rt := Route{subroutes, hs, p} rts = append(rts, rt) } return false }) return rts } func (n *node) walk(fn func(eps endpoints, subroutes Routes) bool) bool { if (n.endpoints != nil || n.subroutes != nil) && fn(n.endpoints, n.subroutes) { return true } for _, ns := range n.children { for _, cn := range ns { if cn.walk(fn) { return true } } } return false } func patNextSegment(pattern string) (nodeTyp, string, string, byte, int, int) { ps := strings.Index(pattern, "{") ws := strings.Index(pattern, "*") if ps < 0 && ws < 0 { return ntStatic, "", "", 0, 0, len(pattern) } if ps >= 0 && ws >= 0 && ws < ps { panic("chi: wildcard '*' must be the last pattern in a route, otherwise use a '{param}'") } var tail byte = '/' if ps >= 0 { nt := ntParam cc := 0 pe := ps for i, c := range pattern[ps:] { if c == '{' { cc++ } else if c == '}' { cc-- if cc == 0 { pe = ps + i break } } } if pe == ps { panic("chi: route param closing delimiter '}' is missing") } key := pattern[ps+1 : pe] pe++ if pe < len(pattern) { tail = pattern[pe] } var rexpat string if idx := strings.Index(key, ":"); idx >= 0 { nt = ntRegexp rexpat = key[idx+1:] key = key[:idx] } if len(rexpat) > 0 { if rexpat[0] != '^' { rexpat = "^" + rexpat } if rexpat[len(rexpat)-1] != '$' { rexpat += "$" } } return nt, key, rexpat, tail, ps, pe } if ws < len(pattern)-1 { panic("chi: wildcard '*' must be the last value in a route. trim trailing text or use a '{param}' instead") } return ntCatchAll, "*", "", 0, ws, len(pattern) } func patParamKeys(pattern string) []string { pat := pattern paramKeys := []string{} for { ptyp, paramKey, _, _, _, e := patNextSegment(pat) if ptyp == ntStatic { return paramKeys } for i := 0; i < len(paramKeys); i++ { if paramKeys[i] == paramKey { panic(fmt.Sprintf("chi: routing pattern '%s' contains duplicate param key, '%s'", pattern, paramKey)) } } paramKeys = append(paramKeys, paramKey) pat = pat[e:] } } func longestPrefix(k1, k2 string) int { max := len(k1) if l := len(k2); l < max { max = l } var i int for i = 0; i < max; i++ { if k1[i] != k2[i] { break } } return i } func methodTypString(method methodTyp) string { for s, t := range methodMap { if method == t { return s } } return "" } type nodes []*node func (ns nodes) Sort() { sort.Sort(ns); ns.tailSort() } func (ns nodes) Len() int { return len(ns) } func (ns nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] } func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label }
MIT License
upmc-enterprises/emmie
vendor/k8s.io/client-go/1.4/kubernetes/typed/core/v1/event.go
List
go
func (c *events) List(opts api.ListOptions) (result *v1.EventList, err error) { result = &v1.EventList{} err = c.client.Get(). Namespace(c.ns). Resource("events"). VersionedParams(&opts, api.ParameterCodec). Do(). Into(result) return }
List takes label and field selectors, and returns the list of Events that match those selectors.
https://github.com/upmc-enterprises/emmie/blob/b6cc8675569eedb31c64b4a174b1dda90ba8bb43/vendor/k8s.io/client-go/1.4/kubernetes/typed/core/v1/event.go#L118-L127
package v1 import ( api "k8s.io/client-go/1.4/pkg/api" v1 "k8s.io/client-go/1.4/pkg/api/v1" watch "k8s.io/client-go/1.4/pkg/watch" ) type EventsGetter interface { Events(namespace string) EventInterface } type EventInterface interface { Create(*v1.Event) (*v1.Event, error) Update(*v1.Event) (*v1.Event, error) Delete(name string, options *api.DeleteOptions) error DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error Get(name string) (*v1.Event, error) List(opts api.ListOptions) (*v1.EventList, error) Watch(opts api.ListOptions) (watch.Interface, error) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.Event, err error) EventExpansion } type events struct { client *CoreClient ns string } func newEvents(c *CoreClient, namespace string) *events { return &events{ client: c, ns: namespace, } } func (c *events) Create(event *v1.Event) (result *v1.Event, err error) { result = &v1.Event{} err = c.client.Post(). Namespace(c.ns). Resource("events"). Body(event). Do(). Into(result) return } func (c *events) Update(event *v1.Event) (result *v1.Event, err error) { result = &v1.Event{} err = c.client.Put(). Namespace(c.ns). Resource("events"). Name(event.Name). Body(event). Do(). Into(result) return } func (c *events) Delete(name string, options *api.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("events"). Name(name). Body(options). Do(). Error() } func (c *events) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("events"). VersionedParams(&listOptions, api.ParameterCodec). Body(options). Do(). Error() } func (c *events) Get(name string) (result *v1.Event, err error) { result = &v1.Event{} err = c.client.Get(). Namespace(c.ns). Resource("events"). Name(name). Do(). Into(result) return }
BSD 3-Clause New or Revised License
chillum/jsonmon
vendor/golang.org/x/sys/windows/security_windows.go
CreateWellKnownSid
go
func CreateWellKnownSid(sidType WELL_KNOWN_SID_TYPE) (*SID, error) { return CreateWellKnownDomainSid(sidType, nil) }
Creates a SID for a well-known predefined alias, generally using the constants of the form Win*Sid, for the local machine.
https://github.com/chillum/jsonmon/blob/2a03fe1db08bcd61b854ec58c07bc266e27ef58d/vendor/golang.org/x/sys/windows/security_windows.go#L450-L452
package windows import ( "syscall" "unsafe" "golang.org/x/sys/internal/unsafeheader" ) const ( NameUnknown = 0 NameFullyQualifiedDN = 1 NameSamCompatible = 2 NameDisplay = 3 NameUniqueId = 6 NameCanonical = 7 NameUserPrincipal = 8 NameCanonicalEx = 9 NameServicePrincipal = 10 NameDnsDomain = 12 ) func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) { u, e := UTF16PtrFromString(username) if e != nil { return "", e } n := uint32(50) for { b := make([]uint16, n) e = TranslateName(u, from, to, &b[0], &n) if e == nil { return UTF16ToString(b[:n]), nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", e } if n <= uint32(len(b)) { return "", e } } } const ( NetSetupUnknownStatus = iota NetSetupUnjoined NetSetupWorkgroupName NetSetupDomainName ) type UserInfo10 struct { Name *uint16 Comment *uint16 UsrComment *uint16 FullName *uint16 } const ( SidTypeUser = 1 + iota SidTypeGroup SidTypeDomain SidTypeAlias SidTypeWellKnownGroup SidTypeDeletedAccount SidTypeInvalid SidTypeUnknown SidTypeComputer SidTypeLabel ) type SidIdentifierAuthority struct { Value [6]byte } var ( SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}} SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}} SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}} SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}} SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}} SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}} SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}} ) const ( SECURITY_NULL_RID = 0 SECURITY_WORLD_RID = 0 SECURITY_LOCAL_RID = 0 SECURITY_CREATOR_OWNER_RID = 0 SECURITY_CREATOR_GROUP_RID = 1 SECURITY_DIALUP_RID = 1 SECURITY_NETWORK_RID = 2 SECURITY_BATCH_RID = 3 SECURITY_INTERACTIVE_RID = 4 SECURITY_LOGON_IDS_RID = 5 SECURITY_SERVICE_RID = 6 SECURITY_LOCAL_SYSTEM_RID = 18 SECURITY_BUILTIN_DOMAIN_RID = 32 SECURITY_PRINCIPAL_SELF_RID = 10 SECURITY_CREATOR_OWNER_SERVER_RID = 0x2 SECURITY_CREATOR_GROUP_SERVER_RID = 0x3 SECURITY_LOGON_IDS_RID_COUNT = 0x3 SECURITY_ANONYMOUS_LOGON_RID = 0x7 SECURITY_PROXY_RID = 0x8 SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9 SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID SECURITY_AUTHENTICATED_USER_RID = 0xb SECURITY_RESTRICTED_CODE_RID = 0xc SECURITY_NT_NON_UNIQUE_RID = 0x15 ) const ( DOMAIN_ALIAS_RID_ADMINS = 0x220 DOMAIN_ALIAS_RID_USERS = 0x221 DOMAIN_ALIAS_RID_GUESTS = 0x222 DOMAIN_ALIAS_RID_POWER_USERS = 0x223 DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224 DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225 DOMAIN_ALIAS_RID_PRINT_OPS = 0x226 DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227 DOMAIN_ALIAS_RID_REPLICATOR = 0x228 DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229 DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 0x22d DOMAIN_ALIAS_RID_MONITORING_USERS = 0x22e DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230 DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231 DOMAIN_ALIAS_RID_DCOM_USERS = 0x232 DOMAIN_ALIAS_RID_IUSERS = 0x238 DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239 DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 0x23c DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e ) type SID struct{} func StringToSid(s string) (*SID, error) { var sid *SID p, e := UTF16PtrFromString(s) if e != nil { return nil, e } e = ConvertStringSidToSid(p, &sid) if e != nil { return nil, e } defer LocalFree((Handle)(unsafe.Pointer(sid))) return sid.Copy() } func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) { if len(account) == 0 { return nil, "", 0, syscall.EINVAL } acc, e := UTF16PtrFromString(account) if e != nil { return nil, "", 0, e } var sys *uint16 if len(system) > 0 { sys, e = UTF16PtrFromString(system) if e != nil { return nil, "", 0, e } } n := uint32(50) dn := uint32(50) for { b := make([]byte, n) db := make([]uint16, dn) sid = (*SID)(unsafe.Pointer(&b[0])) e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType) if e == nil { return sid, UTF16ToString(db), accType, nil } if e != ERROR_INSUFFICIENT_BUFFER { return nil, "", 0, e } if n <= uint32(len(b)) { return nil, "", 0, e } } } func (sid *SID) String() string { var s *uint16 e := ConvertSidToStringSid(sid, &s) if e != nil { return "" } defer LocalFree((Handle)(unsafe.Pointer(s))) return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:]) } func (sid *SID) Len() int { return int(GetLengthSid(sid)) } func (sid *SID) Copy() (*SID, error) { b := make([]byte, sid.Len()) sid2 := (*SID)(unsafe.Pointer(&b[0])) e := CopySid(uint32(len(b)), sid2, sid) if e != nil { return nil, e } return sid2, nil } func (sid *SID) IdentifierAuthority() SidIdentifierAuthority { return *getSidIdentifierAuthority(sid) } func (sid *SID) SubAuthorityCount() uint8 { return *getSidSubAuthorityCount(sid) } func (sid *SID) SubAuthority(idx uint32) uint32 { if idx >= uint32(sid.SubAuthorityCount()) { panic("sub-authority index out of range") } return *getSidSubAuthority(sid, idx) } func (sid *SID) IsValid() bool { return isValidSid(sid) } func (sid *SID) Equals(sid2 *SID) bool { return EqualSid(sid, sid2) } func (sid *SID) IsWellKnown(sidType WELL_KNOWN_SID_TYPE) bool { return isWellKnownSid(sid, sidType) } func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) { var sys *uint16 if len(system) > 0 { sys, err = UTF16PtrFromString(system) if err != nil { return "", "", 0, err } } n := uint32(50) dn := uint32(50) for { b := make([]uint16, n) db := make([]uint16, dn) e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType) if e == nil { return UTF16ToString(b), UTF16ToString(db), accType, nil } if e != ERROR_INSUFFICIENT_BUFFER { return "", "", 0, e } if n <= uint32(len(b)) { return "", "", 0, e } } } type WELL_KNOWN_SID_TYPE uint32 const ( WinNullSid = 0 WinWorldSid = 1 WinLocalSid = 2 WinCreatorOwnerSid = 3 WinCreatorGroupSid = 4 WinCreatorOwnerServerSid = 5 WinCreatorGroupServerSid = 6 WinNtAuthoritySid = 7 WinDialupSid = 8 WinNetworkSid = 9 WinBatchSid = 10 WinInteractiveSid = 11 WinServiceSid = 12 WinAnonymousSid = 13 WinProxySid = 14 WinEnterpriseControllersSid = 15 WinSelfSid = 16 WinAuthenticatedUserSid = 17 WinRestrictedCodeSid = 18 WinTerminalServerSid = 19 WinRemoteLogonIdSid = 20 WinLogonIdsSid = 21 WinLocalSystemSid = 22 WinLocalServiceSid = 23 WinNetworkServiceSid = 24 WinBuiltinDomainSid = 25 WinBuiltinAdministratorsSid = 26 WinBuiltinUsersSid = 27 WinBuiltinGuestsSid = 28 WinBuiltinPowerUsersSid = 29 WinBuiltinAccountOperatorsSid = 30 WinBuiltinSystemOperatorsSid = 31 WinBuiltinPrintOperatorsSid = 32 WinBuiltinBackupOperatorsSid = 33 WinBuiltinReplicatorSid = 34 WinBuiltinPreWindows2000CompatibleAccessSid = 35 WinBuiltinRemoteDesktopUsersSid = 36 WinBuiltinNetworkConfigurationOperatorsSid = 37 WinAccountAdministratorSid = 38 WinAccountGuestSid = 39 WinAccountKrbtgtSid = 40 WinAccountDomainAdminsSid = 41 WinAccountDomainUsersSid = 42 WinAccountDomainGuestsSid = 43 WinAccountComputersSid = 44 WinAccountControllersSid = 45 WinAccountCertAdminsSid = 46 WinAccountSchemaAdminsSid = 47 WinAccountEnterpriseAdminsSid = 48 WinAccountPolicyAdminsSid = 49 WinAccountRasAndIasServersSid = 50 WinNTLMAuthenticationSid = 51 WinDigestAuthenticationSid = 52 WinSChannelAuthenticationSid = 53 WinThisOrganizationSid = 54 WinOtherOrganizationSid = 55 WinBuiltinIncomingForestTrustBuildersSid = 56 WinBuiltinPerfMonitoringUsersSid = 57 WinBuiltinPerfLoggingUsersSid = 58 WinBuiltinAuthorizationAccessSid = 59 WinBuiltinTerminalServerLicenseServersSid = 60 WinBuiltinDCOMUsersSid = 61 WinBuiltinIUsersSid = 62 WinIUserSid = 63 WinBuiltinCryptoOperatorsSid = 64 WinUntrustedLabelSid = 65 WinLowLabelSid = 66 WinMediumLabelSid = 67 WinHighLabelSid = 68 WinSystemLabelSid = 69 WinWriteRestrictedCodeSid = 70 WinCreatorOwnerRightsSid = 71 WinCacheablePrincipalsGroupSid = 72 WinNonCacheablePrincipalsGroupSid = 73 WinEnterpriseReadonlyControllersSid = 74 WinAccountReadonlyControllersSid = 75 WinBuiltinEventLogReadersGroup = 76 WinNewEnterpriseReadonlyControllersSid = 77 WinBuiltinCertSvcDComAccessGroup = 78 WinMediumPlusLabelSid = 79 WinLocalLogonSid = 80 WinConsoleLogonSid = 81 WinThisOrganizationCertificateSid = 82 WinApplicationPackageAuthoritySid = 83 WinBuiltinAnyPackageSid = 84 WinCapabilityInternetClientSid = 85 WinCapabilityInternetClientServerSid = 86 WinCapabilityPrivateNetworkClientServerSid = 87 WinCapabilityPicturesLibrarySid = 88 WinCapabilityVideosLibrarySid = 89 WinCapabilityMusicLibrarySid = 90 WinCapabilityDocumentsLibrarySid = 91 WinCapabilitySharedUserCertificatesSid = 92 WinCapabilityEnterpriseAuthenticationSid = 93 WinCapabilityRemovableStorageSid = 94 WinBuiltinRDSRemoteAccessServersSid = 95 WinBuiltinRDSEndpointServersSid = 96 WinBuiltinRDSManagementServersSid = 97 WinUserModeDriversSid = 98 WinBuiltinHyperVAdminsSid = 99 WinAccountCloneableControllersSid = 100 WinBuiltinAccessControlAssistanceOperatorsSid = 101 WinBuiltinRemoteManagementUsersSid = 102 WinAuthenticationAuthorityAssertedSid = 103 WinAuthenticationServiceAssertedSid = 104 WinLocalAccountSid = 105 WinLocalAccountAndAdministratorSid = 106 WinAccountProtectedUsersSid = 107 WinCapabilityAppointmentsSid = 108 WinCapabilityContactsSid = 109 WinAccountDefaultSystemManagedSid = 110 WinBuiltinDefaultSystemManagedGroupSid = 111 WinBuiltinStorageReplicaAdminsSid = 112 WinAccountKeyAdminsSid = 113 WinAccountEnterpriseKeyAdminsSid = 114 WinAuthenticationKeyTrustSid = 115 WinAuthenticationKeyPropertyMFASid = 116 WinAuthenticationKeyPropertyAttestationSid = 117 WinAuthenticationFreshKeyAuthSid = 118 WinBuiltinDeviceOwnersSid = 119 )
Apache License 2.0
form3tech-oss/f1
vendor/github.com/wcharczuk/go-chart/linear_sequence.go
WithStep
go
func (lg *LinearSeq) WithStep(step float64) *LinearSeq { lg.step = step return lg }
WithStep sets the step and returns the linear generator.
https://github.com/form3tech-oss/f1/blob/0126db025a6fefdbfe1d74be5e21b4f129b1c3ca/vendor/github.com/wcharczuk/go-chart/linear_sequence.go#L70-L73
package chart func LinearRange(start, end float64) []float64 { return Seq{NewLinearSequence().WithStart(start).WithEnd(end).WithStep(1.0)}.Values() } func LinearRangeWithStep(start, end, step float64) []float64 { return Seq{NewLinearSequence().WithStart(start).WithEnd(end).WithStep(step)}.Values() } func NewLinearSequence() *LinearSeq { return &LinearSeq{step: 1.0} } type LinearSeq struct { start float64 end float64 step float64 } func (lg LinearSeq) Start() float64 { return lg.start } func (lg LinearSeq) End() float64 { return lg.end } func (lg LinearSeq) Step() float64 { return lg.step } func (lg LinearSeq) Len() int { if lg.start < lg.end { return int((lg.end-lg.start)/lg.step) + 1 } return int((lg.start-lg.end)/lg.step) + 1 } func (lg LinearSeq) GetValue(index int) float64 { fi := float64(index) if lg.start < lg.end { return lg.start + (fi * lg.step) } return lg.start - (fi * lg.step) } func (lg *LinearSeq) WithStart(start float64) *LinearSeq { lg.start = start return lg } func (lg *LinearSeq) WithEnd(end float64) *LinearSeq { lg.end = end return lg }
Apache License 2.0
wework/grabbit
gbus/invocation.go
Ctx
go
func (dfi *defaultInvocationContext) Ctx() context.Context { return dfi.ctx }
Ctx implements the Invocation.Ctx signature
https://github.com/wework/grabbit/blob/60007d8cbc0915ead1e718dce3aeb26aa4c0ffc3/gbus/invocation.go#L89-L91
package gbus import ( "context" "database/sql" "time" "github.com/sirupsen/logrus" ) var _ Invocation = &defaultInvocationContext{} var _ Messaging = &defaultInvocationContext{} type defaultInvocationContext struct { *Glogged invokingSvc string bus *DefaultBus inboundMsg *BusMessage tx *sql.Tx ctx context.Context exchange string routingKey string deliveryInfo DeliveryInfo } type DeliveryInfo struct { Attempt uint MaxRetryCount uint } func (dfi *defaultInvocationContext) InvokingSvc() string { return dfi.invokingSvc } func (dfi *defaultInvocationContext) Reply(ctx context.Context, replyMessage *BusMessage) error { if dfi.inboundMsg != nil { replyMessage.CorrelationID = dfi.inboundMsg.ID replyMessage.SagaCorrelationID = dfi.inboundMsg.SagaID replyMessage.RPCID = dfi.inboundMsg.RPCID } var err error if dfi.tx != nil { return dfi.bus.sendWithTx(ctx, dfi.tx, dfi.invokingSvc, replyMessage) } if err = dfi.bus.Send(ctx, dfi.invokingSvc, replyMessage); err != nil { logrus.WithError(err).Error("could not send reply") } return err } func (dfi *defaultInvocationContext) Send(ctx context.Context, toService string, command *BusMessage, policies ...MessagePolicy) error { if dfi.tx != nil { return dfi.bus.sendWithTx(ctx, dfi.tx, toService, command, policies...) } return dfi.bus.Send(ctx, toService, command, policies...) } func (dfi *defaultInvocationContext) Publish(ctx context.Context, exchange, topic string, event *BusMessage, policies ...MessagePolicy) error { if dfi.tx != nil { return dfi.bus.publishWithTx(ctx, dfi.tx, exchange, topic, event, policies...) } return dfi.bus.Publish(ctx, exchange, topic, event, policies...) } func (dfi *defaultInvocationContext) RPC(ctx context.Context, service string, request, reply *BusMessage, timeout time.Duration) (*BusMessage, error) { return dfi.bus.RPC(ctx, service, request, reply, timeout) } func (dfi *defaultInvocationContext) Bus() Messaging { return dfi } func (dfi *defaultInvocationContext) Tx() *sql.Tx { return dfi.tx }
Apache License 2.0
fabioxgn/go-bot
cmd.go
RegisterPassiveCommand
go
func RegisterPassiveCommand(command string, cmdFunc func(cmd *PassiveCmd) (string, error)) { passiveCommands[command] = cmdFunc }
RegisterPassiveCommand adds a new passive command to the bot. The command should be registered in the Init() func of your package Passive commands receives all the text posted to a channel without any parsing command: String used to identify the command, for internal use only (ex: logs) cmdFunc: Function which will be executed. It will received the raw message, channel and nick
https://github.com/fabioxgn/go-bot/blob/a549ee4a4236df4a586d200394c5ae40dab9d928/cmd.go#L102-L104
package bot import ( "fmt" "log" "sync" ) type Cmd struct { Raw string Channel string Nick string Message string Command string FullArg string Args []string } type PassiveCmd struct { Raw string Channel string Nick string } type customCommand struct { Version int Cmd string CmdFuncV1 activeCmdFuncV1 CmdFuncV2 activeCmdFuncV2 Description string ExampleArgs string } type incomingMessage struct { Channel string Text string SenderNick string BotCurrentNick string } type CmdResult struct { Channel string Message string } const ( v1 = iota v2 ) const ( commandNotAvailable = "Command %v not available." noCommandsAvailable = "No commands available." errorExecutingCommand = "Error executing %s: %s" ) type passiveCmdFunc func(cmd *PassiveCmd) (string, error) type activeCmdFuncV1 func(cmd *Cmd) (string, error) type activeCmdFuncV2 func(cmd *Cmd) (CmdResult, error) var ( commands = make(map[string]*customCommand) passiveCommands = make(map[string]passiveCmdFunc) ) func RegisterCommand(command, description, exampleArgs string, cmdFunc activeCmdFuncV1) { commands[command] = &customCommand{ Version: v1, Cmd: command, CmdFuncV1: cmdFunc, Description: description, ExampleArgs: exampleArgs, } } func RegisterCommandV2(command, description, exampleArgs string, cmdFunc activeCmdFuncV2) { commands[command] = &customCommand{ Version: v2, Cmd: command, CmdFuncV2: cmdFunc, Description: description, ExampleArgs: exampleArgs, } }
MIT License
melodious-chat/melodious
database.go
UserExistsID
go
func (db *Database) UserExistsID(id int) (bool, error) { row := db.db.QueryRow(` SELECT id FROM melodious.accounts WHERE id=$1 LIMIT 1; `, id) var _id int err := row.Scan(&_id) if err == sql.ErrNoRows { return false, nil } else if err != nil { return false, err } return true, nil }
UserExistsID - checks if user with given id exists. Always check if returned error is not-nil, as it returns false on errors
https://github.com/melodious-chat/melodious/blob/28ab00f90d304a5e5ea7e41cae0ac4603380c728/database.go#L139-L153
package main import ( "crypto/sha256" "database/sql" "encoding/json" "errors" "fmt" "time" "github.com/apex/log" "github.com/lib/pq" ) type Database struct { mel *Melodious db *sql.DB } func (db *Database) GetUsersList() ([]*User, error) { rows, err := db.db.Query(` SELECT id, username, owner FROM melodious.accounts WHERE banned=false; `) if err != nil { return []*User{}, err } users := []*User{} for rows.Next() { user := &User{} err := rows.Scan(&(user.ID), &(user.Username), &(user.Owner)) if err != nil { return []*User{}, err } users = append(users, user) } return users, nil } func (db *Database) HasUsers() (bool, error) { row := db.db.QueryRow(` SELECT id FROM melodious.accounts LIMIT 1; `) var id int err := row.Scan(&id) if err == sql.ErrNoRows { return false, nil } else if err != nil { return false, err } return true, err } func (db *Database) RegisterUser(name string, passhash string, ip string) error { return db.RegisterUserOwner(name, passhash, false, ip) } func (db *Database) RegisterUserOwner(name string, passhash string, owner bool, ip string) error { sum := sha256.Sum256([]byte(passhash)) sumstr := fmt.Sprintf("%x", sum[:32]) _, err := db.db.Exec(` INSERT INTO melodious.accounts (username, passhash, owner) VALUES ($1, $2, $3); `, name, sumstr, owner) if err != nil { return err } return nil } func (db *Database) DeleteUser(name string) error { _, err := db.db.Exec(` DELETE FROM melodious.accounts WHERE username=$1; `, name) if err != nil { return err } return nil } func (db *Database) DeleteUserID(id int) error { _, err := db.db.Exec(` DELETE FROM melodious.accounts WHERE id=$1; `, id) if err != nil { return err } return nil } func (db *Database) GetUserID(name string) (int, error) { row := db.db.QueryRow(` SELECT id FROM melodious.accounts WHERE username=$1 LIMIT 1; `, name) var id int err := row.Scan(&id) if err == sql.ErrNoRows { return -1, errors.New("no such user") } else if err != nil { return -1, err } return 0, err } func (db *Database) UserExists(name string) (bool, error) { row := db.db.QueryRow(` SELECT id FROM melodious.accounts WHERE username=$1 LIMIT 1; `, name) var id int err := row.Scan(&id) if err == sql.ErrNoRows { return false, nil } else if err != nil { return false, err } return true, nil }
MIT License
radondb/radondb-mysql-kubernetes
mysqlcluster/container/init_sidecar.go
getResources
go
func (c *initSidecar) getResources() corev1.ResourceRequirements { return c.Spec.PodPolicy.ExtraResources }
getResources get the container resources.
https://github.com/radondb/radondb-mysql-kubernetes/blob/2d61f5963beb275806ff275a86088742fffc03dc/mysqlcluster/container/init_sidecar.go#L145-L147
package container import ( "fmt" "strconv" corev1 "k8s.io/api/core/v1" "github.com/radondb/radondb-mysql-kubernetes/mysqlcluster" "github.com/radondb/radondb-mysql-kubernetes/utils" ) type initSidecar struct { *mysqlcluster.MysqlCluster name string } func (c *initSidecar) getName() string { return c.name } func (c *initSidecar) getImage() string { return c.Spec.PodPolicy.SidecarImage } func (c *initSidecar) getCommand() []string { return []string{"sidecar", "init"} } func (c *initSidecar) getEnvVars() []corev1.EnvVar { sctName := c.GetNameForResource(utils.Secret) sctNamebackup := c.Spec.BackupSecretName envs := []corev1.EnvVar{ { Name: "CONTAINER_TYPE", Value: utils.ContainerInitSidecarName, }, { Name: "POD_HOSTNAME", ValueFrom: &corev1.EnvVarSource{ FieldRef: &corev1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.name", }, }, }, { Name: "NAMESPACE", Value: c.Namespace, }, { Name: "SERVICE_NAME", Value: c.GetNameForResource(utils.HeadlessSVC), }, { Name: "STATEFULSET_NAME", Value: c.GetNameForResource(utils.StatefulSet), }, { Name: "REPLICAS", Value: fmt.Sprintf("%d", *c.Spec.Replicas), }, { Name: "ADMIT_DEFEAT_HEARBEAT_COUNT", Value: strconv.Itoa(int(*c.Spec.XenonOpts.AdmitDefeatHearbeatCount)), }, { Name: "ELECTION_TIMEOUT", Value: strconv.Itoa(int(*c.Spec.XenonOpts.ElectionTimeout)), }, { Name: "MYSQL_VERSION", Value: c.GetMySQLVersion(), }, { Name: "RESTORE_FROM", Value: c.Spec.RestoreFrom, }, getEnvVarFromSecret(sctName, "MYSQL_ROOT_PASSWORD", "root-password", false), getEnvVarFromSecret(sctName, "INTERNAL_ROOT_PASSWORD", "internal-root-password", true), getEnvVarFromSecret(sctName, "MYSQL_DATABASE", "mysql-database", true), getEnvVarFromSecret(sctName, "MYSQL_USER", "mysql-user", true), getEnvVarFromSecret(sctName, "MYSQL_PASSWORD", "mysql-password", true), getEnvVarFromSecret(sctName, "MYSQL_REPL_USER", "replication-user", true), getEnvVarFromSecret(sctName, "MYSQL_REPL_PASSWORD", "replication-password", true), getEnvVarFromSecret(sctName, "METRICS_USER", "metrics-user", true), getEnvVarFromSecret(sctName, "METRICS_PASSWORD", "metrics-password", true), getEnvVarFromSecret(sctName, "OPERATOR_USER", "operator-user", true), getEnvVarFromSecret(sctName, "OPERATOR_PASSWORD", "operator-password", true), getEnvVarFromSecret(sctName, "BACKUP_USER", "backup-user", true), getEnvVarFromSecret(sctName, "BACKUP_PASSWORD", "backup-password", true), } if len(c.Spec.BackupSecretName) != 0 { envs = append(envs, getEnvVarFromSecret(sctNamebackup, "S3_ENDPOINT", "s3-endpoint", false), getEnvVarFromSecret(sctNamebackup, "S3_ACCESSKEY", "s3-access-key", true), getEnvVarFromSecret(sctNamebackup, "S3_SECRETKEY", "s3-secret-key", true), getEnvVarFromSecret(sctNamebackup, "S3_BUCKET", "s3-bucket", true), ) } if c.Spec.MysqlOpts.InitTokuDB { envs = append(envs, corev1.EnvVar{ Name: "INIT_TOKUDB", Value: "1", }) } return envs } func (c *initSidecar) getLifecycle() *corev1.Lifecycle { return nil }
Apache License 2.0
tidb-incubator/tinysql
ddl/db_change_test.go
TestParallelDDLBeforeRunDDLJob
go
func (s *testStateChangeSuite) TestParallelDDLBeforeRunDDLJob(c *C) { defer s.se.Execute(context.Background(), "drop table test_table") _, err := s.se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), "create table test_table (c1 int, c2 int default 1, index (c1))") c.Assert(err, IsNil) se, err := session.CreateSession(s.store) c.Assert(err, IsNil) _, err = se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) se1, err := session.CreateSession(s.store) c.Assert(err, IsNil) _, err = se1.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) intercept := &ddl.TestInterceptor{} firstConnID := uint64(1) finishedCnt := int32(0) interval := 5 * time.Millisecond var sessionCnt int32 intercept.OnGetInfoSchemaExported = func(ctx sessionctx.Context, is infoschema.InfoSchema) infoschema.InfoSchema { var info infoschema.InfoSchema atomic.AddInt32(&sessionCnt, 1) for { if atomic.LoadInt32(&sessionCnt) == 2 { info = is break } log.Info("sleep in TestParallelDDLBeforeRunDDLJob", zap.String("interval", interval.String())) time.Sleep(interval) } currID := ctx.GetSessionVars().ConnectionID for { seCnt := atomic.LoadInt32(&sessionCnt) if currID == firstConnID || seCnt == finishedCnt { break } log.Info("sleep in TestParallelDDLBeforeRunDDLJob", zap.String("interval", interval.String())) time.Sleep(interval) } return info } d := s.dom.DDL() d.(ddl.DDLForTest).SetInterceptor(intercept) wg := sync.WaitGroup{} wg.Add(2) go func() { defer wg.Done() se.SetConnectionID(firstConnID) _, err1 := se.Execute(context.Background(), "alter table test_table drop column c2") c.Assert(err1, IsNil) atomic.StoreInt32(&sessionCnt, finishedCnt) }() go func() { defer wg.Done() se1.SetConnectionID(2) _, err2 := se1.Execute(context.Background(), "alter table test_table add column c2 int") c.Assert(err2, NotNil) c.Assert(strings.Contains(err2.Error(), "Information schema is changed"), IsTrue) }() wg.Wait() intercept = &ddl.TestInterceptor{} d.(ddl.DDLForTest).SetInterceptor(intercept) }
TestParallelDDLBeforeRunDDLJob tests a session to execute DDL with an outdated information schema. This test is used to simulate the following conditions: In a cluster, TiDB "a" executes the DDL. TiDB "b" fails to load schema, then TiDB "b" executes the DDL statement associated with the DDL statement executed by "a".
https://github.com/tidb-incubator/tinysql/blob/1f08ceeae7f525dee0a0c8931ac594ef06d21cc5/ddl/db_change_test.go#L453-L535
package ddl_test import ( "context" "fmt" "strings" "sync" "sync/atomic" "time" . "github.com/pingcap/check" "github.com/pingcap/errors" "github.com/pingcap/log" "github.com/pingcap/tidb/ddl" "github.com/pingcap/tidb/domain" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/parser" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/util/admin" "github.com/pingcap/tidb/util/testkit" "go.uber.org/zap" ) var _ = Suite(&testStateChangeSuite{}) var _ = SerialSuites(&serialTestStateChangeSuite{}) type serialTestStateChangeSuite struct { testStateChangeSuiteBase } type testStateChangeSuite struct { testStateChangeSuiteBase } type testStateChangeSuiteBase struct { lease time.Duration store kv.Storage dom *domain.Domain se session.Session p *parser.Parser preSQL string } func (s *testStateChangeSuiteBase) SetUpSuite(c *C) { s.lease = 200 * time.Millisecond ddl.WaitTimeWhenErrorOccurred = 1 * time.Microsecond var err error s.store, err = mockstore.NewMockTikvStore() c.Assert(err, IsNil) session.SetSchemaLease(s.lease) s.dom, err = session.BootstrapSession(s.store) c.Assert(err, IsNil) s.se, err = session.CreateSession4Test(s.store) c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), "create database test_db_state default charset utf8 default collate utf8_bin") c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) s.p = parser.New() } func (s *testStateChangeSuiteBase) TearDownSuite(c *C) { s.se.Execute(context.Background(), "drop database if exists test_db_state") s.se.Close() s.dom.Close() s.store.Close() } type sqlWithErr struct { sql string expectErr error } type expectQuery struct { sql string rows []string } func (s *testStateChangeSuite) TestDeleteOnly(c *C) { sqls := make([]sqlWithErr, 1) sqls[0] = sqlWithErr{"insert t set c1 = 'c1_insert', c3 = '2018-02-12', c4 = 1", errors.Errorf("Can't find column c1")} dropColumnSQL := "alter table t drop column c1" s.runTestInSchemaState(c, model.StateDeleteOnly, "", dropColumnSQL, sqls, nil) } func (s *testStateChangeSuiteBase) runTestInSchemaState(c *C, state model.SchemaState, tableName, alterTableSQL string, sqlWithErrs []sqlWithErr, expectQuery *expectQuery) { _, err := s.se.Execute(context.Background(), `create table t ( c1 varchar(64), c2 varchar(64), c3 varchar(64), c4 int primary key, unique key idx2 (c2, c3))`) c.Assert(err, IsNil) defer s.se.Execute(context.Background(), "drop table t") _, err = s.se.Execute(context.Background(), "insert into t values('a', 'N', '2017-07-01', 8)") c.Assert(err, IsNil) callback := &ddl.TestDDLCallback{} prevState := model.StateNone var checkErr error times := 0 se, err := session.CreateSession(s.store) c.Assert(err, IsNil) _, err = se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) callback.OnJobUpdatedExported = func(job *model.Job) { if job.SchemaState == prevState || checkErr != nil || times >= 3 { return } times++ if job.SchemaState != state { return } for _, sqlWithErr := range sqlWithErrs { _, err = se.Execute(context.Background(), sqlWithErr.sql) if !terror.ErrorEqual(err, sqlWithErr.expectErr) { checkErr = err break } } } d := s.dom.DDL() originalCallback := d.GetHook() d.(ddl.DDLForTest).SetHook(callback) _, err = s.se.Execute(context.Background(), alterTableSQL) c.Assert(err, IsNil) c.Assert(errors.ErrorStack(checkErr), Equals, "") d.(ddl.DDLForTest).SetHook(originalCallback) if expectQuery != nil { tk := testkit.NewTestKit(c, s.store) tk.MustExec("use test_db_state") result, err := s.execQuery(tk, expectQuery.sql) c.Assert(err, IsNil) err = checkResult(result, testkit.Rows(expectQuery.rows...)) c.Assert(err, IsNil) } } func (s *testStateChangeSuiteBase) execQuery(tk *testkit.TestKit, sql string) (*testkit.Result, error) { comment := Commentf("sql:%s", sql) rs, err := tk.Exec(sql) if err != nil { return nil, err } result := tk.ResultSetToResult(rs, comment) return result, nil } func checkResult(result *testkit.Result, expected [][]interface{}) error { got := fmt.Sprintf("%s", result.Rows()) need := fmt.Sprintf("%s", expected) if got != need { return fmt.Errorf("need %v, but got %v", need, got) } return nil } func (s *testStateChangeSuite) TestParallelAlterModifyColumn(c *C) { sql := "ALTER TABLE t MODIFY COLUMN b int;" f := func(c *C, err1, err2 error) { c.Assert(err1, IsNil) c.Assert(err2, IsNil) _, err := s.se.Execute(context.Background(), "select * from t") c.Assert(err, IsNil) } s.testControlParallelExecSQL(c, sql, sql, f) } func (s *testStateChangeSuite) TestParallelAddColumAndSetDefaultValue(c *C) { _, err := s.se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), `create table tx ( c1 varchar(64), c2 varchar(64), primary key idx2 (c2, c1))`) c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), "insert into tx values('a', 'N')") c.Assert(err, IsNil) defer s.se.Execute(context.Background(), "drop table tx") sql1 := "alter table tx add column cx int" sql2 := "alter table tx alter c2 set default 'N'" f := func(c *C, err1, err2 error) { c.Assert(err1, IsNil) c.Assert(err2, IsNil) _, err := s.se.Execute(context.Background(), "delete from tx where c1='a'") c.Assert(err, IsNil) } s.testControlParallelExecSQL(c, sql1, sql2, f) } func (s *testStateChangeSuite) TestParallelChangeColumnName(c *C) { sql1 := "ALTER TABLE t CHANGE a aa int;" sql2 := "ALTER TABLE t CHANGE b aa int;" f := func(c *C, err1, err2 error) { var oneErr error if (err1 != nil && err2 == nil) || (err1 == nil && err2 != nil) { if err1 != nil { oneErr = err1 } else { oneErr = err2 } } c.Assert(oneErr.Error(), Equals, "[schema:1060]Duplicate column name 'aa'") } s.testControlParallelExecSQL(c, sql1, sql2, f) } func (s *testStateChangeSuite) TestParallelAlterAddIndex(c *C) { sql1 := "ALTER TABLE t add index index_b(b);" sql2 := "CREATE INDEX index_b ON t (c);" f := func(c *C, err1, err2 error) { c.Assert(err1, IsNil) c.Assert(err2.Error(), Equals, "[ddl:1061]index already exist index_b") } s.testControlParallelExecSQL(c, sql1, sql2, f) } func (s *testStateChangeSuite) TestParallelDropColumn(c *C) { sql := "ALTER TABLE t drop COLUMN c ;" f := func(c *C, err1, err2 error) { c.Assert(err1, IsNil) c.Assert(err2.Error(), Equals, "[ddl:1091]column c doesn't exist") } s.testControlParallelExecSQL(c, sql, sql, f) } func (s *testStateChangeSuite) TestParallelDropIndex(c *C) { sql1 := "alter table t drop index idx1 ;" sql2 := "alter table t drop index idx2 ;" f := func(c *C, err1, err2 error) { c.Assert(err1, IsNil) c.Assert(err2.Error(), Equals, "[autoid:1075]Incorrect table definition; there can be only one auto column and it must be defined as a key") } s.testControlParallelExecSQL(c, sql1, sql2, f) } type checkRet func(c *C, err1, err2 error) func (s *testStateChangeSuiteBase) testControlParallelExecSQL(c *C, sql1, sql2 string, f checkRet) { _, err := s.se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) _, err = s.se.Execute(context.Background(), "create table t(a int, b int, c int, d int auto_increment,e int, index idx1(d), index idx2(d,e))") c.Assert(err, IsNil) if len(s.preSQL) != 0 { _, err := s.se.Execute(context.Background(), s.preSQL) c.Assert(err, IsNil) } defer s.se.Execute(context.Background(), "drop table t") _, err = s.se.Execute(context.Background(), "drop database if exists t_part") c.Assert(err, IsNil) s.se.Execute(context.Background(), `create table t_part (a int key);`) callback := &ddl.TestDDLCallback{} times := 0 callback.OnJobUpdatedExported = func(job *model.Job) { if times != 0 { return } var qLen int for { kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error { jobs, err1 := admin.GetDDLJobs(txn) if err1 != nil { return err1 } qLen = len(jobs) return nil }) if qLen == 2 { break } time.Sleep(5 * time.Millisecond) } times++ } d := s.dom.DDL() originalCallback := d.GetHook() defer d.(ddl.DDLForTest).SetHook(originalCallback) d.(ddl.DDLForTest).SetHook(callback) wg := sync.WaitGroup{} var err1 error var err2 error se, err := session.CreateSession(s.store) c.Assert(err, IsNil) _, err = se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) se1, err := session.CreateSession(s.store) c.Assert(err, IsNil) _, err = se1.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) wg.Add(2) ch := make(chan struct{}) go func() { var qLen int for { kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error { jobs, err3 := admin.GetDDLJobs(txn) if err3 != nil { return err3 } qLen = len(jobs) return nil }) if qLen == 1 { close(ch) break } time.Sleep(5 * time.Millisecond) } }() go func() { defer wg.Done() _, err1 = se.Execute(context.Background(), sql1) }() go func() { defer wg.Done() <-ch _, err2 = se1.Execute(context.Background(), sql2) }() wg.Wait() f(c, err1, err2) } func (s *testStateChangeSuite) testParallelExecSQL(c *C, sql string) { se, err := session.CreateSession(s.store) c.Assert(err, IsNil) _, err = se.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) se1, err1 := session.CreateSession(s.store) c.Assert(err1, IsNil) _, err = se1.Execute(context.Background(), "use test_db_state") c.Assert(err, IsNil) var err2, err3 error wg := sync.WaitGroup{} callback := &ddl.TestDDLCallback{} once := sync.Once{} callback.OnJobUpdatedExported = func(job *model.Job) { once.Do(func() { time.Sleep(time.Millisecond * 10) }) } d := s.dom.DDL() originalCallback := d.GetHook() defer d.(ddl.DDLForTest).SetHook(originalCallback) d.(ddl.DDLForTest).SetHook(callback) wg.Add(2) go func() { defer wg.Done() _, err2 = se.Execute(context.Background(), sql) }() go func() { defer wg.Done() _, err3 = se1.Execute(context.Background(), sql) }() wg.Wait() c.Assert(err2, IsNil) c.Assert(err3, IsNil) } func (s *testStateChangeSuite) TestCreateTableIfNotExists(c *C) { defer s.se.Execute(context.Background(), "drop table test_not_exists") s.testParallelExecSQL(c, "create table if not exists test_not_exists(a int);") } func (s *testStateChangeSuite) TestCreateDBIfNotExists(c *C) { defer s.se.Execute(context.Background(), "drop database test_not_exists") s.testParallelExecSQL(c, "create database if not exists test_not_exists;") } func (s *testStateChangeSuite) TestDDLIfNotExists(c *C) { defer s.se.Execute(context.Background(), "drop table test_not_exists") _, err := s.se.Execute(context.Background(), "create table if not exists test_not_exists(a int)") c.Assert(err, IsNil) s.testParallelExecSQL(c, "alter table test_not_exists add column if not exists b int") s.testParallelExecSQL(c, "alter table test_not_exists add index if not exists idx_b (b)") s.testParallelExecSQL(c, "create index if not exists idx_b on test_not_exists (b)") } func (s *testStateChangeSuite) TestDDLIfExists(c *C) { defer func() { s.se.Execute(context.Background(), "drop table test_exists") s.se.Execute(context.Background(), "drop table test_exists_2") }() _, err := s.se.Execute(context.Background(), "create table if not exists test_exists (a int key, b int)") c.Assert(err, IsNil) s.testParallelExecSQL(c, "alter table test_exists drop column if exists b") s.testParallelExecSQL(c, "alter table test_exists change column if exists a c int") s.testParallelExecSQL(c, "alter table test_exists modify column if exists a bigint") _, err = s.se.Execute(context.Background(), "alter table test_exists add index idx_c (c)") c.Assert(err, IsNil) s.testParallelExecSQL(c, "alter table test_exists drop index if exists idx_c") }
Apache License 2.0
dizzyfool/genna
model/entity.go
HasMultiplePKs
go
func (e *Entity) HasMultiplePKs() bool { counter := 0 for _, col := range e.Columns { if col.IsPK { counter++ } if counter > 1 { return true } } return false }
HasMultiplePKs checks if entity has many primary keys
https://github.com/dizzyfool/genna/blob/39d07df79c8ecb5937d404f0b3534c05ebb4f9da/model/entity.go#L106-L119
package model import ( "github.com/dizzyfool/genna/util" ) type Entity struct { GoName string GoNamePlural string PGName string PGSchema string PGFullName string ViewName string Columns []Column Relations []Relation Imports []string colIndex util.Index impIndex map[string]struct{} } func NewEntity(schema, pgName string, columns []Column, relations []Relation) Entity { goName := util.EntityName(pgName) if schema != util.PublicSchema { goName = util.CamelCased(schema) + goName } goNamePlural := util.CamelCased(util.Sanitize(pgName)) if schema != util.PublicSchema { goNamePlural = util.CamelCased(schema) + goNamePlural } entity := Entity{ GoName: goName, GoNamePlural: goNamePlural, PGName: pgName, PGSchema: schema, PGFullName: util.JoinF(schema, pgName), Columns: []Column{}, Relations: []Relation{}, colIndex: util.NewIndex(), Imports: []string{}, impIndex: map[string]struct{}{}, } if columns != nil { for _, col := range columns { entity.AddColumn(col) } } if relations != nil { for _, rel := range relations { entity.AddRelation(rel) } } return entity } func (e *Entity) AddColumn(column Column) { if !e.colIndex.Available(column.GoName) { column.GoName = e.colIndex.GetNext(column.GoName) } e.colIndex.Add(column.GoName) e.Columns = append(e.Columns, column) if imp := column.Import; imp != "" { if _, ok := e.impIndex[imp]; !ok { e.impIndex[imp] = struct{}{} e.Imports = append(e.Imports, imp) } } } func (e *Entity) AddRelation(relation Relation) { if !e.colIndex.Available(relation.GoName) { relation.GoName = e.colIndex.GetNext(relation.GoName + util.Rel) } e.colIndex.Add(relation.GoName) e.Relations = append(e.Relations, relation) for _, field := range relation.FKFields { for i, column := range e.Columns { if column.PGName == field { e.Columns[i].AddRelation(&relation) } } } }
MIT License
maaslalani/crow
command/command.go
Clear
go
func Clear() { c := exec.Command("clear") Sync(c) c.Run() }
Clear clears the screen
https://github.com/maaslalani/crow/blob/16ae45bb183b62b71ac4da12019216cce6244ca8/command/command.go#L31-L35
package command import ( "log" "os" "os/exec" "syscall" "github.com/maaslalani/crow/config" ) func Run(cmd []string) *exec.Cmd { if config.Clear { Clear() } c := exec.Command(cmd[0], cmd[1:]...) Sync(c) c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} err := c.Start() if err != nil { log.Fatal(err) } return c }
MIT License
ghettovoice/gosip
transport/transport.go
FillTargetHostAndPort
go
func FillTargetHostAndPort(network string, target *Target) *Target { if strings.TrimSpace(target.Host) == "" { target.Host = DefaultHost } if target.Port == nil { p := sip.DefaultPort(network) target.Port = &p } return target }
Fills endpoint target with default values.
https://github.com/ghettovoice/gosip/blob/f0c4b77a298bd43fd73022c76d73376d58dc205a/transport/transport.go#L86-L96
package transport import ( "errors" "fmt" "io" "net" "regexp" "strconv" "strings" "github.com/ghettovoice/gosip/log" "github.com/ghettovoice/gosip/sip" ) const ( MTU = sip.MTU DefaultHost = sip.DefaultHost DefaultProtocol = sip.DefaultProtocol DefaultUdpPort = sip.DefaultUdpPort DefaultTcpPort = sip.DefaultTcpPort DefaultTlsPort = sip.DefaultTlsPort DefaultWsPort = sip.DefaultWsPort DefaultWssPort = sip.DefaultWssPort ) type Target struct { Host string Port *sip.Port } func (trg *Target) Addr() string { var ( host string port sip.Port ) if strings.TrimSpace(trg.Host) != "" { host = trg.Host } else { host = DefaultHost } if trg.Port != nil { port = *trg.Port } return fmt.Sprintf("%v:%v", host, port) } func (trg *Target) String() string { if trg == nil { return "<nil>" } fields := log.Fields{ "target_addr": trg.Addr(), } return fmt.Sprintf("transport.Target<%s>", fields) } func NewTarget(host string, port int) *Target { cport := sip.Port(port) return &Target{Host: host, Port: &cport} } func NewTargetFromAddr(addr string) (*Target, error) { host, port, err := net.SplitHostPort(addr) if err != nil { return nil, err } iport, err := strconv.Atoi(port) if err != nil { return nil, err } return NewTarget(host, iport), nil }
BSD 2-Clause Simplified License
cppforlife/knctl
vendor/github.com/gophercloud/gophercloud/openstack/client.go
NewDNSV2
go
func NewDNSV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { sc, err := initClientOpts(client, eo, "dns") sc.ResourceBase = sc.Endpoint + "v2/" return sc, err }
NewDNSV2 creates a ServiceClient that may be used to access the v2 DNS service.
https://github.com/cppforlife/knctl/blob/47e523d82b9d655d8648fe36d371a084b4613945/vendor/github.com/gophercloud/gophercloud/openstack/client.go#L369-L373
package openstack import ( "fmt" "reflect" "github.com/gophercloud/gophercloud" tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens" tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens" "github.com/gophercloud/gophercloud/openstack/utils" ) const ( v2 = "v2.0" v3 = "v3" ) func NewClient(endpoint string) (*gophercloud.ProviderClient, error) { base, err := utils.BaseEndpoint(endpoint) if err != nil { return nil, err } endpoint = gophercloud.NormalizeURL(endpoint) base = gophercloud.NormalizeURL(base) p := new(gophercloud.ProviderClient) p.IdentityBase = base p.IdentityEndpoint = endpoint p.UseTokenLock() return p, nil } func AuthenticatedClient(options gophercloud.AuthOptions) (*gophercloud.ProviderClient, error) { client, err := NewClient(options.IdentityEndpoint) if err != nil { return nil, err } err = Authenticate(client, options) if err != nil { return nil, err } return client, nil } func Authenticate(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error { versions := []*utils.Version{ {ID: v2, Priority: 20, Suffix: "/v2.0/"}, {ID: v3, Priority: 30, Suffix: "/v3/"}, } chosen, endpoint, err := utils.ChooseVersion(client, versions) if err != nil { return err } switch chosen.ID { case v2: return v2auth(client, endpoint, options, gophercloud.EndpointOpts{}) case v3: return v3auth(client, endpoint, &options, gophercloud.EndpointOpts{}) default: return fmt.Errorf("Unrecognized identity version: %s", chosen.ID) } } func AuthenticateV2(client *gophercloud.ProviderClient, options gophercloud.AuthOptions, eo gophercloud.EndpointOpts) error { return v2auth(client, "", options, eo) } func v2auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions, eo gophercloud.EndpointOpts) error { v2Client, err := NewIdentityV2(client, eo) if err != nil { return err } if endpoint != "" { v2Client.Endpoint = endpoint } v2Opts := tokens2.AuthOptions{ IdentityEndpoint: options.IdentityEndpoint, Username: options.Username, Password: options.Password, TenantID: options.TenantID, TenantName: options.TenantName, AllowReauth: options.AllowReauth, TokenID: options.TokenID, } result := tokens2.Create(v2Client, v2Opts) token, err := result.ExtractToken() if err != nil { return err } catalog, err := result.ExtractServiceCatalog() if err != nil { return err } if options.AllowReauth { tac := *client tac.ReauthFunc = nil tac.TokenID = "" tao := options tao.AllowReauth = false client.ReauthFunc = func() error { err := v2auth(&tac, endpoint, tao, eo) if err != nil { return err } client.TokenID = tac.TokenID return nil } } client.TokenID = token.ID client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { return V2EndpointURL(catalog, opts) } return nil } func AuthenticateV3(client *gophercloud.ProviderClient, options tokens3.AuthOptionsBuilder, eo gophercloud.EndpointOpts) error { return v3auth(client, "", options, eo) } func v3auth(client *gophercloud.ProviderClient, endpoint string, opts tokens3.AuthOptionsBuilder, eo gophercloud.EndpointOpts) error { v3Client, err := NewIdentityV3(client, eo) if err != nil { return err } if endpoint != "" { v3Client.Endpoint = endpoint } result := tokens3.Create(v3Client, opts) token, err := result.ExtractToken() if err != nil { return err } catalog, err := result.ExtractServiceCatalog() if err != nil { return err } client.TokenID = token.ID if opts.CanReauth() { tac := *client tac.ReauthFunc = nil tac.TokenID = "" var tao tokens3.AuthOptionsBuilder switch ot := opts.(type) { case *gophercloud.AuthOptions: o := *ot o.AllowReauth = false tao = &o case *tokens3.AuthOptions: o := *ot o.AllowReauth = false tao = &o default: tao = opts } client.ReauthFunc = func() error { err := v3auth(&tac, endpoint, tao, eo) if err != nil { return err } client.TokenID = tac.TokenID return nil } } client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { return V3EndpointURL(catalog, opts) } return nil } func NewIdentityV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { endpoint := client.IdentityBase + "v2.0/" clientType := "identity" var err error if !reflect.DeepEqual(eo, gophercloud.EndpointOpts{}) { eo.ApplyDefaults(clientType) endpoint, err = client.EndpointLocator(eo) if err != nil { return nil, err } } return &gophercloud.ServiceClient{ ProviderClient: client, Endpoint: endpoint, Type: clientType, }, nil } func NewIdentityV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { endpoint := client.IdentityBase + "v3/" clientType := "identity" var err error if !reflect.DeepEqual(eo, gophercloud.EndpointOpts{}) { eo.ApplyDefaults(clientType) endpoint, err = client.EndpointLocator(eo) if err != nil { return nil, err } } base, err := utils.BaseEndpoint(endpoint) if err != nil { return nil, err } base = gophercloud.NormalizeURL(base) endpoint = base + "v3/" return &gophercloud.ServiceClient{ ProviderClient: client, Endpoint: endpoint, Type: clientType, }, nil } func initClientOpts(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts, clientType string) (*gophercloud.ServiceClient, error) { sc := new(gophercloud.ServiceClient) eo.ApplyDefaults(clientType) url, err := client.EndpointLocator(eo) if err != nil { return sc, err } sc.ProviderClient = client sc.Endpoint = url sc.Type = clientType return sc, nil } func NewObjectStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "object-store") } func NewComputeV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "compute") } func NewNetworkV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { sc, err := initClientOpts(client, eo, "network") sc.ResourceBase = sc.Endpoint + "v2.0/" return sc, err } func NewBlockStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "volume") } func NewBlockStorageV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "volumev2") } func NewBlockStorageV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "volumev3") } func NewSharedFileSystemV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "sharev2") } func NewCDNV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "cdn") } func NewOrchestrationV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "orchestration") } func NewDBV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "database") }
Apache License 2.0
goki/ki
ints/ints.go
Min32
go
func Min32(a, b int32) int32 { if a < b { return a } return b }
Min32 computes the minimum of the two int32 args
https://github.com/goki/ki/blob/0b31cf293ecbf347c90990b76b0d70b8252e4132/ints/ints.go#L124-L129
package ints type Inter interface { Int() int64 } type IntSetter interface { Inter FromInt(val int64) } func Max(a, b Inter) Inter { if a.Int() > b.Int() { return a } return b } func Min(a, b Inter) Inter { if a.Int() < b.Int() { return a } return b } func Abs(a Inter) int64 { if a.Int() < 0 { return -a.Int() } return a.Int() } func MaxInt(a, b int) int { if a > b { return a } return b } func MinInt(a, b int) int { if a < b { return a } return b } func AbsInt(a int) int { if a < 0 { return -a } return a } func Max64(a, b int64) int64 { if a > b { return a } return b } func Min64(a, b int64) int64 { if a < b { return a } return b } func Abs64(a int64) int64 { if a < 0 { return -a } return a } func Max32(a, b int32) int32 { if a > b { return a } return b }
BSD 3-Clause New or Revised License
heroku/instruments
instruments.go
Snapshot
go
func (g *Gauge) Snapshot() int64 { return atomic.LoadInt64(&g.value) }
Snapshot returns the current value.
https://github.com/heroku/instruments/blob/8ff369dd114d82232c24724e902de101d56c249a/instruments.go#L238-L240
package instruments import ( "math/rand" "sync" "sync/atomic" "time" ) const rateScale = 1e-9 type Discrete interface { Snapshot() int64 } type Sample interface { Snapshot() []int64 } func Scale(o, d time.Duration) float64 { return float64(o) / float64(d) } type Counter struct { count int64 } func NewCounter() *Counter { return new(Counter) } func (c *Counter) Update(v int64) { atomic.AddInt64(&c.count, v) } func (c *Counter) Snapshot() int64 { return atomic.SwapInt64(&c.count, 0) } type Rate struct { time int64 unit time.Duration count *Counter m sync.Mutex } func NewRate() *Rate { return NewRateScale(time.Second) } func NewRateScale(d time.Duration) *Rate { return &Rate{ time: time.Now().UnixNano(), unit: d, count: NewCounter(), } } func (r *Rate) Update(v int64) { r.count.Update(v) } func (r *Rate) Snapshot() int64 { r.m.Lock() defer r.m.Unlock() now := time.Now().UnixNano() t := atomic.SwapInt64(&r.time, now) c := r.count.Snapshot() s := float64(c) / rateScale / float64(now-t) return Ceil(s * Scale(r.unit, time.Second)) } type Derive struct { rate *Rate value int64 } func NewDerive(v int64) *Derive { return &Derive{ value: v, rate: NewRate(), } } func NewDeriveScale(v int64, d time.Duration) *Derive { return &Derive{ value: v, rate: NewRateScale(d), } } func (d *Derive) Update(v int64) { p := atomic.SwapInt64(&d.value, v) d.rate.Update(v - p) } func (d *Derive) Snapshot() int64 { return d.rate.Snapshot() } type Reservoir struct { size int64 values []int64 m sync.Mutex } const defaultReservoirSize = 1028 func NewReservoir(size int64) *Reservoir { if size <= 0 { size = defaultReservoirSize } return &Reservoir{ values: make([]int64, size), } } func (r *Reservoir) Update(v int64) { r.m.Lock() defer r.m.Unlock() s := atomic.AddInt64(&r.size, 1) if int(s) <= len(r.values) { r.values[s-1] = v } else { l := rand.Int63n(s) if int(l) < len(r.values) { r.values[l] = v } } } func (r *Reservoir) Snapshot() []int64 { r.m.Lock() defer r.m.Unlock() s := atomic.SwapInt64(&r.size, 0) v := make([]int64, min(int(s), len(r.values))) copy(v, r.values) r.values = make([]int64, cap(r.values)) sorted(v) return v } type Gauge struct { value int64 } func NewGauge(v int64) *Gauge { return &Gauge{ value: v, } } func (g *Gauge) Update(v int64) { atomic.StoreInt64(&g.value, v) }
MIT License
kevinburke/travis
vendor/github.com/kevinburke/go-types/types.go
Scan
go
func (ns *NullString) Scan(value interface{}) error { if value == nil { ns.String, ns.Valid = "", false return nil } ns.String, ns.Valid = value.(string) return nil }
Scan implements the Scanner interface.
https://github.com/kevinburke/travis/blob/059cda7e30f63cb390d8dfb5bff9d50d1d74ca5b/vendor/github.com/kevinburke/go-types/types.go#L46-L53
package types import ( "database/sql/driver" "encoding/json" "errors" "strconv" ) const Version = "0.22" type NullString struct { Valid bool String string } func (ns *NullString) UnmarshalJSON(b []byte) error { if string(b) == "null" { ns.Valid = false return nil } var s string err := json.Unmarshal(b, &s) if err != nil { return err } ns.Valid = true ns.String = s return nil } func (ns NullString) MarshalJSON() ([]byte, error) { if !ns.Valid { return []byte("null"), nil } s, err := json.Marshal(ns.String) if err != nil { return []byte{}, err } return s, nil }
MIT License
temporalio/temporal
client/matching/client.go
NewClient
go
func NewClient( timeout time.Duration, longPollTimeout time.Duration, clients common.ClientCache, lb LoadBalancer, ) matchingservice.MatchingServiceClient { return &clientImpl{ timeout: timeout, longPollTimeout: longPollTimeout, clients: clients, loadBalancer: lb, } }
NewClient creates a new history service TChannel client
https://github.com/temporalio/temporal/blob/3997ae6b53724fe4436e17248eb9fe08fe8b025d/client/matching/client.go#L55-L67
package matching import ( "context" "time" enumspb "go.temporal.io/api/enums/v1" "google.golang.org/grpc" "go.temporal.io/server/api/matchingservice/v1" "go.temporal.io/server/common" ) var _ matchingservice.MatchingServiceClient = (*clientImpl)(nil) const ( DefaultTimeout = time.Minute DefaultLongPollTimeout = time.Minute * 2 ) type clientImpl struct { timeout time.Duration longPollTimeout time.Duration clients common.ClientCache loadBalancer LoadBalancer }
MIT License
tg123/go-htpasswd
htpasswd.go
Reload
go
func (bf *File) Reload(bad BadLineHandler) error { f, err := os.Open(bf.filePath) if err != nil { return err } defer f.Close() return bf.ReloadFromReader(f, bad) }
Reload rereads the htpassword file.. You will need to call this to notice any changes to the password file. This function is thread safe. Someone versed in fsnotify might make it happen automatically. Likewise you might also connect a SIGHUP handler to this function.
https://github.com/tg123/go-htpasswd/blob/4c77c3c3df7be9837269b1b534d84ef14a8059d9/htpasswd.go#L122-L131
package htpasswd import ( "bufio" "fmt" "io" "os" "strings" "sync" ) type EncodedPasswd interface { MatchesPassword(pw string) bool } type PasswdParser func(pw string) (EncodedPasswd, error) type passwdTable map[string]EncodedPasswd type BadLineHandler func(err error) type File struct { filePath string mutex sync.Mutex passwds passwdTable parsers []PasswdParser } var DefaultSystems = []PasswdParser{AcceptMd5, AcceptSha, AcceptBcrypt, AcceptSsha, AcceptCryptSha, AcceptPlain} func New(filename string, parsers []PasswdParser, bad BadLineHandler) (*File, error) { bf := File{ filePath: filename, parsers: parsers, } if err := bf.Reload(bad); err != nil { return nil, err } return &bf, nil } func NewFromReader(r io.Reader, parsers []PasswdParser, bad BadLineHandler) (*File, error) { bf := File{ parsers: parsers, } if err := bf.ReloadFromReader(r, bad); err != nil { return nil, err } return &bf, nil } func (bf *File) Match(username, password string) bool { bf.mutex.Lock() matcher, ok := bf.passwds[username] bf.mutex.Unlock() if ok && matcher.MatchesPassword(password) { return true } return false }
MIT License
crowdstrike/gofalcon
falcon/client/custom_ioa/get_patterns_parameters.go
bindParamIds
go
func (o *GetPatternsParams) bindParamIds(formats strfmt.Registry) []string { idsIR := o.Ids var idsIC []string for _, idsIIR := range idsIR { idsIIV := idsIIR idsIC = append(idsIC, idsIIV) } idsIS := swag.JoinByFormat(idsIC, "multi") return idsIS }
bindParamGetPatterns binds the parameter ids
https://github.com/crowdstrike/gofalcon/blob/c1e03b54363d20c149ede3409aa9b1dd3d64194c/falcon/client/custom_ioa/get_patterns_parameters.go#L159-L173
package custom_ioa import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) func NewGetPatternsParams() *GetPatternsParams { return &GetPatternsParams{ timeout: cr.DefaultTimeout, } } func NewGetPatternsParamsWithTimeout(timeout time.Duration) *GetPatternsParams { return &GetPatternsParams{ timeout: timeout, } } func NewGetPatternsParamsWithContext(ctx context.Context) *GetPatternsParams { return &GetPatternsParams{ Context: ctx, } } func NewGetPatternsParamsWithHTTPClient(client *http.Client) *GetPatternsParams { return &GetPatternsParams{ HTTPClient: client, } } type GetPatternsParams struct { Ids []string timeout time.Duration Context context.Context HTTPClient *http.Client } func (o *GetPatternsParams) WithDefaults() *GetPatternsParams { o.SetDefaults() return o } func (o *GetPatternsParams) SetDefaults() { } func (o *GetPatternsParams) WithTimeout(timeout time.Duration) *GetPatternsParams { o.SetTimeout(timeout) return o } func (o *GetPatternsParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } func (o *GetPatternsParams) WithContext(ctx context.Context) *GetPatternsParams { o.SetContext(ctx) return o } func (o *GetPatternsParams) SetContext(ctx context.Context) { o.Context = ctx } func (o *GetPatternsParams) WithHTTPClient(client *http.Client) *GetPatternsParams { o.SetHTTPClient(client) return o } func (o *GetPatternsParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } func (o *GetPatternsParams) WithIds(ids []string) *GetPatternsParams { o.SetIds(ids) return o } func (o *GetPatternsParams) SetIds(ids []string) { o.Ids = ids } func (o *GetPatternsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.Ids != nil { joinedIds := o.bindParamIds(reg) if err := r.SetQueryParam("ids", joinedIds...); err != nil { return err } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
MIT License
rajveermalviya/go-wayland
wayland/unstable/primary-selection-v1/primary_selection.go
AddCancelledHandler
go
func (i *PrimarySelectionSource) AddCancelledHandler(f PrimarySelectionSourceCancelledHandlerFunc) { if f == nil { return } i.cancelledHandlers = append(i.cancelledHandlers, f) }
AddCancelledHandler : adds handler for PrimarySelectionSourceCancelledEvent
https://github.com/rajveermalviya/go-wayland/blob/779b2c59733635e1318f1c0449f00682516d07ab/wayland/unstable/primary-selection-v1/primary_selection.go#L489-L495
package primary_selection import ( "reflect" "github.com/rajveermalviya/go-wayland/wayland/client" "golang.org/x/sys/unix" ) type PrimarySelectionDeviceManager struct { client.BaseProxy } func NewPrimarySelectionDeviceManager(ctx *client.Context) *PrimarySelectionDeviceManager { zwpPrimarySelectionDeviceManagerV1 := &PrimarySelectionDeviceManager{} ctx.Register(zwpPrimarySelectionDeviceManagerV1) return zwpPrimarySelectionDeviceManagerV1 } func (i *PrimarySelectionDeviceManager) CreateSource() (*PrimarySelectionSource, error) { id := NewPrimarySelectionSource(i.Context()) const opcode = 0 const rLen = 8 + 4 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 client.PutUint32(r[l:l+4], id.ID()) l += 4 err := i.Context().WriteMsg(r, nil) return id, err } func (i *PrimarySelectionDeviceManager) GetDevice(seat *client.Seat) (*PrimarySelectionDevice, error) { id := NewPrimarySelectionDevice(i.Context()) const opcode = 1 const rLen = 8 + 4 + 4 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 client.PutUint32(r[l:l+4], id.ID()) l += 4 client.PutUint32(r[l:l+4], seat.ID()) l += 4 err := i.Context().WriteMsg(r, nil) return id, err } func (i *PrimarySelectionDeviceManager) Destroy() error { defer i.Context().Unregister(i) const opcode = 2 const rLen = 8 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 err := i.Context().WriteMsg(r, nil) return err } type PrimarySelectionDevice struct { client.BaseProxy dataOfferHandlers []PrimarySelectionDeviceDataOfferHandlerFunc selectionHandlers []PrimarySelectionDeviceSelectionHandlerFunc } func NewPrimarySelectionDevice(ctx *client.Context) *PrimarySelectionDevice { zwpPrimarySelectionDeviceV1 := &PrimarySelectionDevice{} ctx.Register(zwpPrimarySelectionDeviceV1) return zwpPrimarySelectionDeviceV1 } func (i *PrimarySelectionDevice) SetSelection(source *PrimarySelectionSource, serial uint32) error { const opcode = 0 const rLen = 8 + 4 + 4 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 if source == nil { client.PutUint32(r[l:l+4], 0) l += 4 } else { client.PutUint32(r[l:l+4], source.ID()) l += 4 } client.PutUint32(r[l:l+4], uint32(serial)) l += 4 err := i.Context().WriteMsg(r, nil) return err } func (i *PrimarySelectionDevice) Destroy() error { defer i.Context().Unregister(i) const opcode = 1 const rLen = 8 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 err := i.Context().WriteMsg(r, nil) return err } type PrimarySelectionDeviceDataOfferEvent struct { Offer *PrimarySelectionOffer } type PrimarySelectionDeviceDataOfferHandlerFunc func(PrimarySelectionDeviceDataOfferEvent) func (i *PrimarySelectionDevice) AddDataOfferHandler(f PrimarySelectionDeviceDataOfferHandlerFunc) { if f == nil { return } i.dataOfferHandlers = append(i.dataOfferHandlers, f) } func (i *PrimarySelectionDevice) RemoveDataOfferHandler(f PrimarySelectionDeviceDataOfferHandlerFunc) { for j, e := range i.dataOfferHandlers { if reflect.ValueOf(e).Pointer() == reflect.ValueOf(f).Pointer() { i.dataOfferHandlers = append(i.dataOfferHandlers[:j], i.dataOfferHandlers[j+1:]...) return } } } type PrimarySelectionDeviceSelectionEvent struct { Id *PrimarySelectionOffer } type PrimarySelectionDeviceSelectionHandlerFunc func(PrimarySelectionDeviceSelectionEvent) func (i *PrimarySelectionDevice) AddSelectionHandler(f PrimarySelectionDeviceSelectionHandlerFunc) { if f == nil { return } i.selectionHandlers = append(i.selectionHandlers, f) } func (i *PrimarySelectionDevice) RemoveSelectionHandler(f PrimarySelectionDeviceSelectionHandlerFunc) { for j, e := range i.selectionHandlers { if reflect.ValueOf(e).Pointer() == reflect.ValueOf(f).Pointer() { i.selectionHandlers = append(i.selectionHandlers[:j], i.selectionHandlers[j+1:]...) return } } } func (i *PrimarySelectionDevice) Dispatch(opcode uint16, fd uintptr, data []byte) { switch opcode { case 0: if len(i.dataOfferHandlers) == 0 { return } var e PrimarySelectionDeviceDataOfferEvent l := 0 e.Offer = i.Context().GetProxy(client.Uint32(data[l : l+4])).(*PrimarySelectionOffer) l += 4 for _, f := range i.dataOfferHandlers { f(e) } case 1: if len(i.selectionHandlers) == 0 { return } var e PrimarySelectionDeviceSelectionEvent l := 0 e.Id = i.Context().GetProxy(client.Uint32(data[l : l+4])).(*PrimarySelectionOffer) l += 4 for _, f := range i.selectionHandlers { f(e) } } } type PrimarySelectionOffer struct { client.BaseProxy offerHandlers []PrimarySelectionOfferOfferHandlerFunc } func NewPrimarySelectionOffer(ctx *client.Context) *PrimarySelectionOffer { zwpPrimarySelectionOfferV1 := &PrimarySelectionOffer{} ctx.Register(zwpPrimarySelectionOfferV1) return zwpPrimarySelectionOfferV1 } func (i *PrimarySelectionOffer) Receive(mimeType string, fd uintptr) error { const opcode = 0 mimeTypeLen := client.PaddedLen(len(mimeType) + 1) rLen := 8 + (4 + mimeTypeLen) r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 client.PutString(r[l:l+(4+mimeTypeLen)], mimeType, mimeTypeLen) l += (4 + mimeTypeLen) oob := unix.UnixRights(int(fd)) err := i.Context().WriteMsg(r, oob) return err } func (i *PrimarySelectionOffer) Destroy() error { defer i.Context().Unregister(i) const opcode = 1 const rLen = 8 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 err := i.Context().WriteMsg(r, nil) return err } type PrimarySelectionOfferOfferEvent struct { MimeType string } type PrimarySelectionOfferOfferHandlerFunc func(PrimarySelectionOfferOfferEvent) func (i *PrimarySelectionOffer) AddOfferHandler(f PrimarySelectionOfferOfferHandlerFunc) { if f == nil { return } i.offerHandlers = append(i.offerHandlers, f) } func (i *PrimarySelectionOffer) RemoveOfferHandler(f PrimarySelectionOfferOfferHandlerFunc) { for j, e := range i.offerHandlers { if reflect.ValueOf(e).Pointer() == reflect.ValueOf(f).Pointer() { i.offerHandlers = append(i.offerHandlers[:j], i.offerHandlers[j+1:]...) return } } } func (i *PrimarySelectionOffer) Dispatch(opcode uint16, fd uintptr, data []byte) { switch opcode { case 0: if len(i.offerHandlers) == 0 { return } var e PrimarySelectionOfferOfferEvent l := 0 mimeTypeLen := client.PaddedLen(int(client.Uint32(data[l : l+4]))) l += 4 e.MimeType = client.String(data[l : l+mimeTypeLen]) l += mimeTypeLen for _, f := range i.offerHandlers { f(e) } } } type PrimarySelectionSource struct { client.BaseProxy sendHandlers []PrimarySelectionSourceSendHandlerFunc cancelledHandlers []PrimarySelectionSourceCancelledHandlerFunc } func NewPrimarySelectionSource(ctx *client.Context) *PrimarySelectionSource { zwpPrimarySelectionSourceV1 := &PrimarySelectionSource{} ctx.Register(zwpPrimarySelectionSourceV1) return zwpPrimarySelectionSourceV1 } func (i *PrimarySelectionSource) Offer(mimeType string) error { const opcode = 0 mimeTypeLen := client.PaddedLen(len(mimeType) + 1) rLen := 8 + (4 + mimeTypeLen) r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 client.PutString(r[l:l+(4+mimeTypeLen)], mimeType, mimeTypeLen) l += (4 + mimeTypeLen) err := i.Context().WriteMsg(r, nil) return err } func (i *PrimarySelectionSource) Destroy() error { defer i.Context().Unregister(i) const opcode = 1 const rLen = 8 r := make([]byte, rLen) l := 0 client.PutUint32(r[l:4], i.ID()) l += 4 client.PutUint32(r[l:l+4], uint32(rLen<<16|opcode&0x0000ffff)) l += 4 err := i.Context().WriteMsg(r, nil) return err } type PrimarySelectionSourceSendEvent struct { MimeType string Fd uintptr } type PrimarySelectionSourceSendHandlerFunc func(PrimarySelectionSourceSendEvent) func (i *PrimarySelectionSource) AddSendHandler(f PrimarySelectionSourceSendHandlerFunc) { if f == nil { return } i.sendHandlers = append(i.sendHandlers, f) } func (i *PrimarySelectionSource) RemoveSendHandler(f PrimarySelectionSourceSendHandlerFunc) { for j, e := range i.sendHandlers { if reflect.ValueOf(e).Pointer() == reflect.ValueOf(f).Pointer() { i.sendHandlers = append(i.sendHandlers[:j], i.sendHandlers[j+1:]...) return } } } type PrimarySelectionSourceCancelledEvent struct{} type PrimarySelectionSourceCancelledHandlerFunc func(PrimarySelectionSourceCancelledEvent)
BSD 2-Clause Simplified License
binance-chain/tss-lib
ecdsa/keygen/ecdsa-keygen.pb.go
Descriptor
go
func (*KGRound2Message2) Descriptor() ([]byte, []int) { return file_protob_ecdsa_keygen_proto_rawDescGZIP(), []int{2} }
Deprecated: Use KGRound2Message2.ProtoReflect.Descriptor instead.
https://github.com/binance-chain/tss-lib/blob/73560daec7f83d7355107ea9b5e59d16de8765be/ecdsa/keygen/ecdsa-keygen.pb.go#L213-L215
package keygen import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type KGRound1Message struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Commitment []byte `protobuf:"bytes,1,opt,name=commitment,proto3" json:"commitment,omitempty"` PaillierN []byte `protobuf:"bytes,2,opt,name=paillier_n,json=paillierN,proto3" json:"paillier_n,omitempty"` NTilde []byte `protobuf:"bytes,3,opt,name=n_tilde,json=nTilde,proto3" json:"n_tilde,omitempty"` H1 []byte `protobuf:"bytes,4,opt,name=h1,proto3" json:"h1,omitempty"` H2 []byte `protobuf:"bytes,5,opt,name=h2,proto3" json:"h2,omitempty"` Dlnproof_1 [][]byte `protobuf:"bytes,6,rep,name=dlnproof_1,json=dlnproof1,proto3" json:"dlnproof_1,omitempty"` Dlnproof_2 [][]byte `protobuf:"bytes,7,rep,name=dlnproof_2,json=dlnproof2,proto3" json:"dlnproof_2,omitempty"` } func (x *KGRound1Message) Reset() { *x = KGRound1Message{} if protoimpl.UnsafeEnabled { mi := &file_protob_ecdsa_keygen_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *KGRound1Message) String() string { return protoimpl.X.MessageStringOf(x) } func (*KGRound1Message) ProtoMessage() {} func (x *KGRound1Message) ProtoReflect() protoreflect.Message { mi := &file_protob_ecdsa_keygen_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } func (*KGRound1Message) Descriptor() ([]byte, []int) { return file_protob_ecdsa_keygen_proto_rawDescGZIP(), []int{0} } func (x *KGRound1Message) GetCommitment() []byte { if x != nil { return x.Commitment } return nil } func (x *KGRound1Message) GetPaillierN() []byte { if x != nil { return x.PaillierN } return nil } func (x *KGRound1Message) GetNTilde() []byte { if x != nil { return x.NTilde } return nil } func (x *KGRound1Message) GetH1() []byte { if x != nil { return x.H1 } return nil } func (x *KGRound1Message) GetH2() []byte { if x != nil { return x.H2 } return nil } func (x *KGRound1Message) GetDlnproof_1() [][]byte { if x != nil { return x.Dlnproof_1 } return nil } func (x *KGRound1Message) GetDlnproof_2() [][]byte { if x != nil { return x.Dlnproof_2 } return nil } type KGRound2Message1 struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Share []byte `protobuf:"bytes,1,opt,name=share,proto3" json:"share,omitempty"` } func (x *KGRound2Message1) Reset() { *x = KGRound2Message1{} if protoimpl.UnsafeEnabled { mi := &file_protob_ecdsa_keygen_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *KGRound2Message1) String() string { return protoimpl.X.MessageStringOf(x) } func (*KGRound2Message1) ProtoMessage() {} func (x *KGRound2Message1) ProtoReflect() protoreflect.Message { mi := &file_protob_ecdsa_keygen_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } func (*KGRound2Message1) Descriptor() ([]byte, []int) { return file_protob_ecdsa_keygen_proto_rawDescGZIP(), []int{1} } func (x *KGRound2Message1) GetShare() []byte { if x != nil { return x.Share } return nil } type KGRound2Message2 struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields DeCommitment [][]byte `protobuf:"bytes,1,rep,name=de_commitment,json=deCommitment,proto3" json:"de_commitment,omitempty"` } func (x *KGRound2Message2) Reset() { *x = KGRound2Message2{} if protoimpl.UnsafeEnabled { mi := &file_protob_ecdsa_keygen_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *KGRound2Message2) String() string { return protoimpl.X.MessageStringOf(x) } func (*KGRound2Message2) ProtoMessage() {} func (x *KGRound2Message2) ProtoReflect() protoreflect.Message { mi := &file_protob_ecdsa_keygen_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) }
MIT License
planetlabs/draino
internal/kubernetes/eventhandler.go
OnAdd
go
func (h *DrainingResourceEventHandler) OnAdd(obj interface{}) { n, ok := obj.(*core.Node) if !ok { return } h.HandleNode(n) }
OnAdd cordons and drains the added node.
https://github.com/planetlabs/draino/blob/9d39b53933688355ea44bf9f5517d8b9e85509e7/internal/kubernetes/eventhandler.go#L127-L133
package kubernetes import ( "context" "fmt" "strings" "time" "go.opencensus.io/stats" "go.opencensus.io/tag" "go.uber.org/zap" core "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" ) const ( DefaultDrainBuffer = 10 * time.Minute eventReasonCordonStarting = "CordonStarting" eventReasonCordonSucceeded = "CordonSucceeded" eventReasonCordonFailed = "CordonFailed" eventReasonUncordonStarting = "UncordonStarting" eventReasonUncordonSucceeded = "UncordonSucceeded" eventReasonUncordonFailed = "UncordonFailed" eventReasonDrainScheduled = "DrainScheduled" eventReasonDrainSchedulingFailed = "DrainSchedulingFailed" eventReasonDrainStarting = "DrainStarting" eventReasonDrainSucceeded = "DrainSucceeded" eventReasonDrainFailed = "DrainFailed" tagResultSucceeded = "succeeded" tagResultFailed = "failed" drainRetryAnnotationKey = "draino/drain-retry" drainRetryAnnotationValue = "true" drainoConditionsAnnotationKey = "draino.planet.com/conditions" ) var ( MeasureNodesCordoned = stats.Int64("draino/nodes_cordoned", "Number of nodes cordoned.", stats.UnitDimensionless) MeasureNodesUncordoned = stats.Int64("draino/nodes_uncordoned", "Number of nodes uncordoned.", stats.UnitDimensionless) MeasureNodesDrained = stats.Int64("draino/nodes_drained", "Number of nodes drained.", stats.UnitDimensionless) MeasureNodesDrainScheduled = stats.Int64("draino/nodes_drainScheduled", "Number of nodes drain scheduled.", stats.UnitDimensionless) TagNodeName, _ = tag.NewKey("node_name") TagResult, _ = tag.NewKey("result") ) type DrainingResourceEventHandler struct { logger *zap.Logger cordonDrainer CordonDrainer eventRecorder record.EventRecorder drainScheduler DrainScheduler lastDrainScheduledFor time.Time buffer time.Duration conditions []SuppliedCondition } type DrainingResourceEventHandlerOption func(d *DrainingResourceEventHandler) func WithLogger(l *zap.Logger) DrainingResourceEventHandlerOption { return func(h *DrainingResourceEventHandler) { h.logger = l } } func WithDrainBuffer(d time.Duration) DrainingResourceEventHandlerOption { return func(h *DrainingResourceEventHandler) { h.buffer = d } } func WithConditionsFilter(conditions []string) DrainingResourceEventHandlerOption { return func(h *DrainingResourceEventHandler) { h.conditions = ParseConditions(conditions) } } func NewDrainingResourceEventHandler(d CordonDrainer, e record.EventRecorder, ho ...DrainingResourceEventHandlerOption) *DrainingResourceEventHandler { h := &DrainingResourceEventHandler{ logger: zap.NewNop(), cordonDrainer: d, eventRecorder: e, lastDrainScheduledFor: time.Now(), buffer: DefaultDrainBuffer, } for _, o := range ho { o(h) } h.drainScheduler = NewDrainSchedules(d, e, h.buffer, h.logger) return h }
Apache License 2.0
containerbuilding/cbi
vendor/k8s.io/api/extensions/v1beta1/zz_generated.deepcopy.go
DeepCopyInto
go
func (in *DeploymentSpec) DeepCopyInto(out *DeploymentSpec) { *out = *in if in.Replicas != nil { in, out := &in.Replicas, &out.Replicas if *in == nil { *out = nil } else { *out = new(int32) **out = **in } } if in.Selector != nil { in, out := &in.Selector, &out.Selector if *in == nil { *out = nil } else { *out = new(v1.LabelSelector) (*in).DeepCopyInto(*out) } } in.Template.DeepCopyInto(&out.Template) in.Strategy.DeepCopyInto(&out.Strategy) if in.RevisionHistoryLimit != nil { in, out := &in.RevisionHistoryLimit, &out.RevisionHistoryLimit if *in == nil { *out = nil } else { *out = new(int32) **out = **in } } if in.RollbackTo != nil { in, out := &in.RollbackTo, &out.RollbackTo if *in == nil { *out = nil } else { *out = new(RollbackConfig) **out = **in } } if in.ProgressDeadlineSeconds != nil { in, out := &in.ProgressDeadlineSeconds, &out.ProgressDeadlineSeconds if *in == nil { *out = nil } else { *out = new(int32) **out = **in } } return }
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
https://github.com/containerbuilding/cbi/blob/1f3ccebc2b71abfa108e48071bf1009e5f68016c/vendor/k8s.io/api/extensions/v1beta1/zz_generated.deepcopy.go#L426-L476
package v1beta1 import ( core_v1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" intstr "k8s.io/apimachinery/pkg/util/intstr" ) func (in *AllowedFlexVolume) DeepCopyInto(out *AllowedFlexVolume) { *out = *in return } func (in *AllowedFlexVolume) DeepCopy() *AllowedFlexVolume { if in == nil { return nil } out := new(AllowedFlexVolume) in.DeepCopyInto(out) return out } func (in *AllowedHostPath) DeepCopyInto(out *AllowedHostPath) { *out = *in return } func (in *AllowedHostPath) DeepCopy() *AllowedHostPath { if in == nil { return nil } out := new(AllowedHostPath) in.DeepCopyInto(out) return out } func (in *CustomMetricCurrentStatus) DeepCopyInto(out *CustomMetricCurrentStatus) { *out = *in out.CurrentValue = in.CurrentValue.DeepCopy() return } func (in *CustomMetricCurrentStatus) DeepCopy() *CustomMetricCurrentStatus { if in == nil { return nil } out := new(CustomMetricCurrentStatus) in.DeepCopyInto(out) return out } func (in *CustomMetricCurrentStatusList) DeepCopyInto(out *CustomMetricCurrentStatusList) { *out = *in if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CustomMetricCurrentStatus, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *CustomMetricCurrentStatusList) DeepCopy() *CustomMetricCurrentStatusList { if in == nil { return nil } out := new(CustomMetricCurrentStatusList) in.DeepCopyInto(out) return out } func (in *CustomMetricTarget) DeepCopyInto(out *CustomMetricTarget) { *out = *in out.TargetValue = in.TargetValue.DeepCopy() return } func (in *CustomMetricTarget) DeepCopy() *CustomMetricTarget { if in == nil { return nil } out := new(CustomMetricTarget) in.DeepCopyInto(out) return out } func (in *CustomMetricTargetList) DeepCopyInto(out *CustomMetricTargetList) { *out = *in if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CustomMetricTarget, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *CustomMetricTargetList) DeepCopy() *CustomMetricTargetList { if in == nil { return nil } out := new(CustomMetricTargetList) in.DeepCopyInto(out) return out } func (in *DaemonSet) DeepCopyInto(out *DaemonSet) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return } func (in *DaemonSet) DeepCopy() *DaemonSet { if in == nil { return nil } out := new(DaemonSet) in.DeepCopyInto(out) return out } func (in *DaemonSet) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *DaemonSetCondition) DeepCopyInto(out *DaemonSetCondition) { *out = *in in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) return } func (in *DaemonSetCondition) DeepCopy() *DaemonSetCondition { if in == nil { return nil } out := new(DaemonSetCondition) in.DeepCopyInto(out) return out } func (in *DaemonSetList) DeepCopyInto(out *DaemonSetList) { *out = *in out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]DaemonSet, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *DaemonSetList) DeepCopy() *DaemonSetList { if in == nil { return nil } out := new(DaemonSetList) in.DeepCopyInto(out) return out } func (in *DaemonSetList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *DaemonSetSpec) DeepCopyInto(out *DaemonSetSpec) { *out = *in if in.Selector != nil { in, out := &in.Selector, &out.Selector if *in == nil { *out = nil } else { *out = new(v1.LabelSelector) (*in).DeepCopyInto(*out) } } in.Template.DeepCopyInto(&out.Template) in.UpdateStrategy.DeepCopyInto(&out.UpdateStrategy) if in.RevisionHistoryLimit != nil { in, out := &in.RevisionHistoryLimit, &out.RevisionHistoryLimit if *in == nil { *out = nil } else { *out = new(int32) **out = **in } } return } func (in *DaemonSetSpec) DeepCopy() *DaemonSetSpec { if in == nil { return nil } out := new(DaemonSetSpec) in.DeepCopyInto(out) return out } func (in *DaemonSetStatus) DeepCopyInto(out *DaemonSetStatus) { *out = *in if in.CollisionCount != nil { in, out := &in.CollisionCount, &out.CollisionCount if *in == nil { *out = nil } else { *out = new(int32) **out = **in } } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]DaemonSetCondition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *DaemonSetStatus) DeepCopy() *DaemonSetStatus { if in == nil { return nil } out := new(DaemonSetStatus) in.DeepCopyInto(out) return out } func (in *DaemonSetUpdateStrategy) DeepCopyInto(out *DaemonSetUpdateStrategy) { *out = *in if in.RollingUpdate != nil { in, out := &in.RollingUpdate, &out.RollingUpdate if *in == nil { *out = nil } else { *out = new(RollingUpdateDaemonSet) (*in).DeepCopyInto(*out) } } return } func (in *DaemonSetUpdateStrategy) DeepCopy() *DaemonSetUpdateStrategy { if in == nil { return nil } out := new(DaemonSetUpdateStrategy) in.DeepCopyInto(out) return out } func (in *Deployment) DeepCopyInto(out *Deployment) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return } func (in *Deployment) DeepCopy() *Deployment { if in == nil { return nil } out := new(Deployment) in.DeepCopyInto(out) return out } func (in *Deployment) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *DeploymentCondition) DeepCopyInto(out *DeploymentCondition) { *out = *in in.LastUpdateTime.DeepCopyInto(&out.LastUpdateTime) in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) return } func (in *DeploymentCondition) DeepCopy() *DeploymentCondition { if in == nil { return nil } out := new(DeploymentCondition) in.DeepCopyInto(out) return out } func (in *DeploymentList) DeepCopyInto(out *DeploymentList) { *out = *in out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Deployment, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } func (in *DeploymentList) DeepCopy() *DeploymentList { if in == nil { return nil } out := new(DeploymentList) in.DeepCopyInto(out) return out } func (in *DeploymentList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } func (in *DeploymentRollback) DeepCopyInto(out *DeploymentRollback) { *out = *in out.TypeMeta = in.TypeMeta if in.UpdatedAnnotations != nil { in, out := &in.UpdatedAnnotations, &out.UpdatedAnnotations *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } out.RollbackTo = in.RollbackTo return } func (in *DeploymentRollback) DeepCopy() *DeploymentRollback { if in == nil { return nil } out := new(DeploymentRollback) in.DeepCopyInto(out) return out } func (in *DeploymentRollback) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil }
Apache License 2.0
temporalio/temporal
common/persistence/dataInterfaces_mock.go
CreateTasks
go
func (m *MockTaskManager) CreateTasks(request *CreateTasksRequest) (*CreateTasksResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateTasks", request) ret0, _ := ret[0].(*CreateTasksResponse) ret1, _ := ret[1].(error) return ret0, ret1 }
CreateTasks mocks base method.
https://github.com/temporalio/temporal/blob/3997ae6b53724fe4436e17248eb9fe08fe8b025d/common/persistence/dataInterfaces_mock.go#L833-L839
package persistence import ( reflect "reflect" gomock "github.com/golang/mock/gomock" ) type MockCloseable struct { ctrl *gomock.Controller recorder *MockCloseableMockRecorder } type MockCloseableMockRecorder struct { mock *MockCloseable } func NewMockCloseable(ctrl *gomock.Controller) *MockCloseable { mock := &MockCloseable{ctrl: ctrl} mock.recorder = &MockCloseableMockRecorder{mock} return mock } func (m *MockCloseable) EXPECT() *MockCloseableMockRecorder { return m.recorder } func (m *MockCloseable) Close() { m.ctrl.T.Helper() m.ctrl.Call(m, "Close") } func (mr *MockCloseableMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockCloseable)(nil).Close)) } type MockShardManager struct { ctrl *gomock.Controller recorder *MockShardManagerMockRecorder } type MockShardManagerMockRecorder struct { mock *MockShardManager } func NewMockShardManager(ctrl *gomock.Controller) *MockShardManager { mock := &MockShardManager{ctrl: ctrl} mock.recorder = &MockShardManagerMockRecorder{mock} return mock } func (m *MockShardManager) EXPECT() *MockShardManagerMockRecorder { return m.recorder } func (m *MockShardManager) Close() { m.ctrl.T.Helper() m.ctrl.Call(m, "Close") } func (mr *MockShardManagerMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockShardManager)(nil).Close)) } func (m *MockShardManager) CreateShard(request *CreateShardRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateShard", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockShardManagerMockRecorder) CreateShard(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateShard", reflect.TypeOf((*MockShardManager)(nil).CreateShard), request) } func (m *MockShardManager) GetName() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetName") ret0, _ := ret[0].(string) return ret0 } func (mr *MockShardManagerMockRecorder) GetName() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetName", reflect.TypeOf((*MockShardManager)(nil).GetName)) } func (m *MockShardManager) GetShard(request *GetShardRequest) (*GetShardResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetShard", request) ret0, _ := ret[0].(*GetShardResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockShardManagerMockRecorder) GetShard(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetShard", reflect.TypeOf((*MockShardManager)(nil).GetShard), request) } func (m *MockShardManager) UpdateShard(request *UpdateShardRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateShard", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockShardManagerMockRecorder) UpdateShard(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateShard", reflect.TypeOf((*MockShardManager)(nil).UpdateShard), request) } type MockExecutionManager struct { ctrl *gomock.Controller recorder *MockExecutionManagerMockRecorder } type MockExecutionManagerMockRecorder struct { mock *MockExecutionManager } func NewMockExecutionManager(ctrl *gomock.Controller) *MockExecutionManager { mock := &MockExecutionManager{ctrl: ctrl} mock.recorder = &MockExecutionManagerMockRecorder{mock} return mock } func (m *MockExecutionManager) EXPECT() *MockExecutionManagerMockRecorder { return m.recorder } func (m *MockExecutionManager) AddTasks(request *AddTasksRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddTasks", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) AddTasks(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTasks", reflect.TypeOf((*MockExecutionManager)(nil).AddTasks), request) } func (m *MockExecutionManager) AppendHistoryNodes(request *AppendHistoryNodesRequest) (*AppendHistoryNodesResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppendHistoryNodes", request) ret0, _ := ret[0].(*AppendHistoryNodesResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) AppendHistoryNodes(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppendHistoryNodes", reflect.TypeOf((*MockExecutionManager)(nil).AppendHistoryNodes), request) } func (m *MockExecutionManager) Close() { m.ctrl.T.Helper() m.ctrl.Call(m, "Close") } func (mr *MockExecutionManagerMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockExecutionManager)(nil).Close)) } func (m *MockExecutionManager) CompleteReplicationTask(request *CompleteReplicationTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompleteReplicationTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) CompleteReplicationTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompleteReplicationTask", reflect.TypeOf((*MockExecutionManager)(nil).CompleteReplicationTask), request) } func (m *MockExecutionManager) CompleteTimerTask(request *CompleteTimerTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompleteTimerTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) CompleteTimerTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompleteTimerTask", reflect.TypeOf((*MockExecutionManager)(nil).CompleteTimerTask), request) } func (m *MockExecutionManager) CompleteTransferTask(request *CompleteTransferTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompleteTransferTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) CompleteTransferTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompleteTransferTask", reflect.TypeOf((*MockExecutionManager)(nil).CompleteTransferTask), request) } func (m *MockExecutionManager) CompleteVisibilityTask(request *CompleteVisibilityTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompleteVisibilityTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) CompleteVisibilityTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompleteVisibilityTask", reflect.TypeOf((*MockExecutionManager)(nil).CompleteVisibilityTask), request) } func (m *MockExecutionManager) ConflictResolveWorkflowExecution(request *ConflictResolveWorkflowExecutionRequest) (*ConflictResolveWorkflowExecutionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ConflictResolveWorkflowExecution", request) ret0, _ := ret[0].(*ConflictResolveWorkflowExecutionResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) ConflictResolveWorkflowExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConflictResolveWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).ConflictResolveWorkflowExecution), request) } func (m *MockExecutionManager) CreateWorkflowExecution(request *CreateWorkflowExecutionRequest) (*CreateWorkflowExecutionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateWorkflowExecution", request) ret0, _ := ret[0].(*CreateWorkflowExecutionResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) CreateWorkflowExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).CreateWorkflowExecution), request) } func (m *MockExecutionManager) DeleteCurrentWorkflowExecution(request *DeleteCurrentWorkflowExecutionRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteCurrentWorkflowExecution", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) DeleteCurrentWorkflowExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).DeleteCurrentWorkflowExecution), request) } func (m *MockExecutionManager) DeleteHistoryBranch(request *DeleteHistoryBranchRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteHistoryBranch", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) DeleteHistoryBranch(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteHistoryBranch", reflect.TypeOf((*MockExecutionManager)(nil).DeleteHistoryBranch), request) } func (m *MockExecutionManager) DeleteReplicationTaskFromDLQ(request *DeleteReplicationTaskFromDLQRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteReplicationTaskFromDLQ", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) DeleteReplicationTaskFromDLQ(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteReplicationTaskFromDLQ", reflect.TypeOf((*MockExecutionManager)(nil).DeleteReplicationTaskFromDLQ), request) } func (m *MockExecutionManager) DeleteWorkflowExecution(request *DeleteWorkflowExecutionRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteWorkflowExecution", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) DeleteWorkflowExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).DeleteWorkflowExecution), request) } func (m *MockExecutionManager) ForkHistoryBranch(request *ForkHistoryBranchRequest) (*ForkHistoryBranchResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ForkHistoryBranch", request) ret0, _ := ret[0].(*ForkHistoryBranchResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) ForkHistoryBranch(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForkHistoryBranch", reflect.TypeOf((*MockExecutionManager)(nil).ForkHistoryBranch), request) } func (m *MockExecutionManager) GetAllHistoryTreeBranches(request *GetAllHistoryTreeBranchesRequest) (*GetAllHistoryTreeBranchesResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAllHistoryTreeBranches", request) ret0, _ := ret[0].(*GetAllHistoryTreeBranchesResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetAllHistoryTreeBranches(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllHistoryTreeBranches", reflect.TypeOf((*MockExecutionManager)(nil).GetAllHistoryTreeBranches), request) } func (m *MockExecutionManager) GetCurrentExecution(request *GetCurrentExecutionRequest) (*GetCurrentExecutionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCurrentExecution", request) ret0, _ := ret[0].(*GetCurrentExecutionResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetCurrentExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentExecution", reflect.TypeOf((*MockExecutionManager)(nil).GetCurrentExecution), request) } func (m *MockExecutionManager) GetHistoryTree(request *GetHistoryTreeRequest) (*GetHistoryTreeResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetHistoryTree", request) ret0, _ := ret[0].(*GetHistoryTreeResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetHistoryTree(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHistoryTree", reflect.TypeOf((*MockExecutionManager)(nil).GetHistoryTree), request) } func (m *MockExecutionManager) GetName() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetName") ret0, _ := ret[0].(string) return ret0 } func (mr *MockExecutionManagerMockRecorder) GetName() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetName", reflect.TypeOf((*MockExecutionManager)(nil).GetName)) } func (m *MockExecutionManager) GetReplicationTask(request *GetReplicationTaskRequest) (*GetReplicationTaskResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetReplicationTask", request) ret0, _ := ret[0].(*GetReplicationTaskResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetReplicationTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReplicationTask", reflect.TypeOf((*MockExecutionManager)(nil).GetReplicationTask), request) } func (m *MockExecutionManager) GetReplicationTasks(request *GetReplicationTasksRequest) (*GetReplicationTasksResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetReplicationTasks", request) ret0, _ := ret[0].(*GetReplicationTasksResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetReplicationTasks(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReplicationTasks", reflect.TypeOf((*MockExecutionManager)(nil).GetReplicationTasks), request) } func (m *MockExecutionManager) GetReplicationTasksFromDLQ(request *GetReplicationTasksFromDLQRequest) (*GetReplicationTasksFromDLQResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetReplicationTasksFromDLQ", request) ret0, _ := ret[0].(*GetReplicationTasksFromDLQResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetReplicationTasksFromDLQ(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReplicationTasksFromDLQ", reflect.TypeOf((*MockExecutionManager)(nil).GetReplicationTasksFromDLQ), request) } func (m *MockExecutionManager) GetTimerTask(request *GetTimerTaskRequest) (*GetTimerTaskResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTimerTask", request) ret0, _ := ret[0].(*GetTimerTaskResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetTimerTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimerTask", reflect.TypeOf((*MockExecutionManager)(nil).GetTimerTask), request) } func (m *MockExecutionManager) GetTimerTasks(request *GetTimerTasksRequest) (*GetTimerTasksResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTimerTasks", request) ret0, _ := ret[0].(*GetTimerTasksResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetTimerTasks(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimerTasks", reflect.TypeOf((*MockExecutionManager)(nil).GetTimerTasks), request) } func (m *MockExecutionManager) GetTransferTask(request *GetTransferTaskRequest) (*GetTransferTaskResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTransferTask", request) ret0, _ := ret[0].(*GetTransferTaskResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetTransferTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTransferTask", reflect.TypeOf((*MockExecutionManager)(nil).GetTransferTask), request) } func (m *MockExecutionManager) GetTransferTasks(request *GetTransferTasksRequest) (*GetTransferTasksResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetTransferTasks", request) ret0, _ := ret[0].(*GetTransferTasksResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetTransferTasks(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTransferTasks", reflect.TypeOf((*MockExecutionManager)(nil).GetTransferTasks), request) } func (m *MockExecutionManager) GetVisibilityTask(request *GetVisibilityTaskRequest) (*GetVisibilityTaskResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetVisibilityTask", request) ret0, _ := ret[0].(*GetVisibilityTaskResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetVisibilityTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVisibilityTask", reflect.TypeOf((*MockExecutionManager)(nil).GetVisibilityTask), request) } func (m *MockExecutionManager) GetVisibilityTasks(request *GetVisibilityTasksRequest) (*GetVisibilityTasksResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetVisibilityTasks", request) ret0, _ := ret[0].(*GetVisibilityTasksResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetVisibilityTasks(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVisibilityTasks", reflect.TypeOf((*MockExecutionManager)(nil).GetVisibilityTasks), request) } func (m *MockExecutionManager) GetWorkflowExecution(request *GetWorkflowExecutionRequest) (*GetWorkflowExecutionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetWorkflowExecution", request) ret0, _ := ret[0].(*GetWorkflowExecutionResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) GetWorkflowExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).GetWorkflowExecution), request) } func (m *MockExecutionManager) ListConcreteExecutions(request *ListConcreteExecutionsRequest) (*ListConcreteExecutionsResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListConcreteExecutions", request) ret0, _ := ret[0].(*ListConcreteExecutionsResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) ListConcreteExecutions(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListConcreteExecutions", reflect.TypeOf((*MockExecutionManager)(nil).ListConcreteExecutions), request) } func (m *MockExecutionManager) PutReplicationTaskToDLQ(request *PutReplicationTaskToDLQRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PutReplicationTaskToDLQ", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) PutReplicationTaskToDLQ(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutReplicationTaskToDLQ", reflect.TypeOf((*MockExecutionManager)(nil).PutReplicationTaskToDLQ), request) } func (m *MockExecutionManager) RangeCompleteReplicationTask(request *RangeCompleteReplicationTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RangeCompleteReplicationTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) RangeCompleteReplicationTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RangeCompleteReplicationTask", reflect.TypeOf((*MockExecutionManager)(nil).RangeCompleteReplicationTask), request) } func (m *MockExecutionManager) RangeCompleteTimerTask(request *RangeCompleteTimerTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RangeCompleteTimerTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) RangeCompleteTimerTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RangeCompleteTimerTask", reflect.TypeOf((*MockExecutionManager)(nil).RangeCompleteTimerTask), request) } func (m *MockExecutionManager) RangeCompleteTransferTask(request *RangeCompleteTransferTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RangeCompleteTransferTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) RangeCompleteTransferTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RangeCompleteTransferTask", reflect.TypeOf((*MockExecutionManager)(nil).RangeCompleteTransferTask), request) } func (m *MockExecutionManager) RangeCompleteVisibilityTask(request *RangeCompleteVisibilityTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RangeCompleteVisibilityTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) RangeCompleteVisibilityTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RangeCompleteVisibilityTask", reflect.TypeOf((*MockExecutionManager)(nil).RangeCompleteVisibilityTask), request) } func (m *MockExecutionManager) RangeDeleteReplicationTaskFromDLQ(request *RangeDeleteReplicationTaskFromDLQRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RangeDeleteReplicationTaskFromDLQ", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockExecutionManagerMockRecorder) RangeDeleteReplicationTaskFromDLQ(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RangeDeleteReplicationTaskFromDLQ", reflect.TypeOf((*MockExecutionManager)(nil).RangeDeleteReplicationTaskFromDLQ), request) } func (m *MockExecutionManager) ReadHistoryBranch(request *ReadHistoryBranchRequest) (*ReadHistoryBranchResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReadHistoryBranch", request) ret0, _ := ret[0].(*ReadHistoryBranchResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) ReadHistoryBranch(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadHistoryBranch", reflect.TypeOf((*MockExecutionManager)(nil).ReadHistoryBranch), request) } func (m *MockExecutionManager) ReadHistoryBranchByBatch(request *ReadHistoryBranchRequest) (*ReadHistoryBranchByBatchResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReadHistoryBranchByBatch", request) ret0, _ := ret[0].(*ReadHistoryBranchByBatchResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) ReadHistoryBranchByBatch(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadHistoryBranchByBatch", reflect.TypeOf((*MockExecutionManager)(nil).ReadHistoryBranchByBatch), request) } func (m *MockExecutionManager) ReadRawHistoryBranch(request *ReadHistoryBranchRequest) (*ReadRawHistoryBranchResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReadRawHistoryBranch", request) ret0, _ := ret[0].(*ReadRawHistoryBranchResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) ReadRawHistoryBranch(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadRawHistoryBranch", reflect.TypeOf((*MockExecutionManager)(nil).ReadRawHistoryBranch), request) } func (m *MockExecutionManager) TrimHistoryBranch(request *TrimHistoryBranchRequest) (*TrimHistoryBranchResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TrimHistoryBranch", request) ret0, _ := ret[0].(*TrimHistoryBranchResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) TrimHistoryBranch(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TrimHistoryBranch", reflect.TypeOf((*MockExecutionManager)(nil).TrimHistoryBranch), request) } func (m *MockExecutionManager) UpdateWorkflowExecution(request *UpdateWorkflowExecutionRequest) (*UpdateWorkflowExecutionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UpdateWorkflowExecution", request) ret0, _ := ret[0].(*UpdateWorkflowExecutionResponse) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockExecutionManagerMockRecorder) UpdateWorkflowExecution(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateWorkflowExecution", reflect.TypeOf((*MockExecutionManager)(nil).UpdateWorkflowExecution), request) } type MockTaskManager struct { ctrl *gomock.Controller recorder *MockTaskManagerMockRecorder } type MockTaskManagerMockRecorder struct { mock *MockTaskManager } func NewMockTaskManager(ctrl *gomock.Controller) *MockTaskManager { mock := &MockTaskManager{ctrl: ctrl} mock.recorder = &MockTaskManagerMockRecorder{mock} return mock } func (m *MockTaskManager) EXPECT() *MockTaskManagerMockRecorder { return m.recorder } func (m *MockTaskManager) Close() { m.ctrl.T.Helper() m.ctrl.Call(m, "Close") } func (mr *MockTaskManagerMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockTaskManager)(nil).Close)) } func (m *MockTaskManager) CompleteTask(request *CompleteTaskRequest) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompleteTask", request) ret0, _ := ret[0].(error) return ret0 } func (mr *MockTaskManagerMockRecorder) CompleteTask(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompleteTask", reflect.TypeOf((*MockTaskManager)(nil).CompleteTask), request) } func (m *MockTaskManager) CompleteTasksLessThan(request *CompleteTasksLessThanRequest) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompleteTasksLessThan", request) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockTaskManagerMockRecorder) CompleteTasksLessThan(request interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompleteTasksLessThan", reflect.TypeOf((*MockTaskManager)(nil).CompleteTasksLessThan), request) }
MIT License
rveen/ogdl
block.go
OgdlTypes
go
func (p *Parser) OgdlTypes() { n, u := p.Space() if u == 0 { return } for i := n; i > 0; i-- { p.UnreadByte() } p.tree(n, true) }
OgdlTypes is the main function for parsing OGDL text. This version tries to convert unquoted strings that can be parsed as ints, floats or bools to their corresponding type in Go (string | int64 | float64 | bool).
https://github.com/rveen/ogdl/blob/2f8576ce7bddccdb1483edb4dbb1e3c6de9d1637/block.go#L33-L42
package ogdl import ( "errors" ) func (p *Parser) Ogdl() { n, u := p.Space() if u == 0 { return } for i := n; i > 0; i-- { p.UnreadByte() } p.tree(n, false) }
BSD 2-Clause Simplified License
google/simhospital
pkg/message/messages.go
BuildPathologyORRO02
go
func BuildPathologyORRO02(h *HeaderInfo, p *ir.PatientInfo, o *ir.Order, msgTime time.Time) (*HL7Message, error) { msgType := &Type{ MessageType: ORR, TriggerEvent: "O02", } var segments []string msh, err := BuildMSH(msgTime, msgType, h) if err != nil { return nil, errors.Wrap(err, "cannot build MSH segment") } segments = append(segments, msh) msa, err := BuildMSA(o.MessageControlIDOriginalOrder) if err != nil { return nil, errors.Wrap(err, "MSA build MSH segment") } segments = append(segments, msa) pid, err := BuildPID(p.Person) if err != nil { return nil, errors.Wrap(err, "cannot build PID segment") } segments = append(segments, pid) orc, err := BuildORC(o) if err != nil { return nil, errors.Wrap(err, "cannot build ORC segment") } segments = append(segments, orc) return &HL7Message{ Type: msgType, Message: strings.Join(segments, SegmentTerminator), }, nil }
BuildPathologyORRO02 builds and returns a HL7 ORR^O02 message.
https://github.com/google/simhospital/blob/db2c1db3fe37718f8e12426e2ac4d2df803efc16/pkg/message/messages.go#L549-L580
package message import ( "bytes" "fmt" "strings" "text/template" "time" "github.com/pkg/errors" "github.com/google/simhospital/pkg/constants" "github.com/google/simhospital/pkg/hl7" "github.com/google/simhospital/pkg/ir" "github.com/google/simhospital/pkg/logging" ) const ( ADT = "ADT" ORM = "ORM" ORR = "ORR" ORU = "ORU" MDM = "MDM" ) const DiagnosticServIDMDOC = "MDOC" const SegmentTerminator = constants.SegmentTerminatorStr const ( listItemsSeparator = "~" componentSeparator = "^" escapedComponentSeparator = "\\S\\" subComponentSeparator = "&" escapedSubComponentSeparator = "\\T\\" lineBreak = "\n" escapedLineBreak = "\\.br\\" backwardSlash = "\\" escapedBackwardSlash = "\\E\\" ) type HL7Message struct { Type *Type Message string } type Type struct { MessageType string TriggerEvent string } type HeaderInfo struct { SendingApplication string SendingFacility string ReceivingApplication string ReceivingFacility string MessageControlID string } var ( log = logging.ForCallerPackage() funcMap = template.FuncMap{ "HL7_date": ToHL7Date, "HL7_repeated": toHL7RepeatedField, "expand_mrns": expandMRNs, "HL7_unit": toHL7Unit, "escape_HL7": escapeHL7, } ) func ToHL7Date(t ir.Formattable) (string, error) { nt, ok := t.(ir.NullTime) if ok && !nt.Valid { return "", nil } if nt.Location() != time.UTC { return "", fmt.Errorf("found time with non-UTC location: %v", nt) } if nt.Midnight { localT := t.In(hl7.Location) t = time.Date(localT.Year(), localT.Month(), localT.Day(), 0, 0, 0, 0, hl7.Location) } return t.In(hl7.Location).Format("20060102150405"), nil } func toHL7RepeatedField(s string) string { return strings.Replace(s, "\n", listItemsSeparator, -1) } func expandMRNs(mrns []string) (string, error) { fields := make([]string, len(mrns)) for i, m := range mrns { f, err := executeTemplate(parsedCXMRNTemplate, struct { MRN string }{m}) if err != nil { return "", errors.Wrap(err, "cannot expand MRNs") } fields[i] = f } return strings.Join(fields, listItemsSeparator), nil } func toHL7Unit(s string) string { return strings.Replace(s, componentSeparator, escapedComponentSeparator, -1) } func escapeHL7(s string) string { r := strings.NewReplacer( componentSeparator, escapedComponentSeparator, subComponentSeparator, escapedSubComponentSeparator, lineBreak, escapedLineBreak, backwardSlash, escapedBackwardSlash, ) return r.Replace(s) } const ( MSH = "MSH" MSA = "MSA" EVN = "EVN" PID = "PID" ORC = "ORC" OBR = "OBR" OBRClinicalNote = "OBRClinicalNote" OBX = "OBX" OBXClinicalNote = "OBXClinicalNote" OBXForMDM = "OBXForMDM" PV1 = "PV1" PV2 = "PV2" NK1 = "NK1" AL1 = "AL1" NTE = "NTE" MRG = "MRG" DG1 = "DG1" PD1 = "PD1" PR1 = "PR1" TXA = "TXA" ) const ( locationTemplate = "LocationTmpl" doctorTemplate = "DoctorTmpl" personNameTemplate = "PersonNameTmpl" addressTemplate = "AddressTmpl" homeNumberTemplate = "HomeNumberTmpl" ceTemplate = "CETmpl" ceNoteTemplate = "CENoteTmpl" ceAdmitReasonTemplate = "CEAdmitReasonTmpl" cxVisitTemplate = "CXVisitTmpl" cxMRNTemplate = "CXMRNTmpl" primFacTemplate = "PrimFacTmpl" noteTemplate = "NoteTmpl" ) var ( locationTmpl = "{{.Poc}}^{{.Room}}^{{.Bed}}^{{.Facility}}^^{{.LocationType}}^{{.Building}}^{{.Floor}}" doctorTmpl = "{{.ID}}^{{.Surname}}^{{.FirstName}}^^^{{.Prefix}}^^^DRNBR^PRSNL^^^ORGDR" personNameTmpl = "{{.Surname}}^{{.FirstName}}^{{.MiddleName}}^{{.Suffix}}^{{.Prefix}}^{{.Degree}}^CURRENT" addressTmpl = "{{.FirstLine}}^{{.SecondLine}}^{{.City}}^^{{.PostalCode}}^{{.Country}}^{{.Type}}" homeNumberTmpl = "{{.}}^HOME" ceTmpl = "{{escape_HL7 .ID}}^{{escape_HL7 .Text}}^{{.CodingSystem}}^^{{escape_HL7 .AlternateText}}" ceNoteTmpl = "{{.DocumentType}}^{{.DocumentType}}" ceAdmitReasonTmpl = "^{{.}}" primFacTmpl = "{{.Organization}}^^{{.ID}}" cxVisitTmpl = "{{.}}^^^^visitid" cxMRNTmpl = "{{.MRN}}^^^SIMULATOR MRN^MRN" stOBXNoteVal = "^^{{.ContentType}}^{{.DocumentEncoding}}^{{escape_HL7 .DocumentContent}}" parsedCXMRNTemplate = mustParseTemplateWithoutFuncs(cxMRNTemplate, cxMRNTmpl) ) var templates = map[string]*template.Template{ MSH: mustParseTemplate(MSH, "MSH|^~\\&|{{.Header.SendingApplication}}|{{.Header.SendingFacility}}|{{.Header.ReceivingApplication}}|{{.Header.ReceivingFacility}}|{{HL7_date .T}}||{{.MsgType.MessageType}}^{{.MsgType.TriggerEvent}}|{{.Header.MessageControlID}}|T|2.3|||AL||44|ASCII"), MSA: mustParseTemplate(MSA, "MSA|AA|{{.OrderMessageControlID}}"), EVN: mustParseTemplates(EVN, map[string]string{ doctorTemplate: doctorTmpl, EVN: `EVN|{{.MsgType.TriggerEvent}}|{{HL7_date .T}}|{{HL7_date .DateTimePlannedEvent}}||{{template "DoctorTmpl" .Operator}}|{{HL7_date .EventOccurredDateTime}}`, }), PID: mustParseTemplates(PID, map[string]string{ personNameTemplate: personNameTmpl, addressTemplate: addressTmpl, homeNumberTemplate: homeNumberTmpl, ceTemplate: ceTmpl, cxMRNTemplate: cxMRNTmpl, PID: `PID|1|{{template "CXMRNTmpl" .}}|{{template "CXMRNTmpl" .}}~{{.NHS}}^^^NHSNBR^NHSNMBR||{{template "PersonNameTmpl" .}}||{{HL7_date .Birth}}|{{.Gender}}|||{{template "AddressTmpl" .Address}}||{{template "HomeNumberTmpl" .PhoneNumber}}|||||||||{{template "CETmpl" .Ethnicity}}|||||||{{HL7_date .DateOfDeath}}|{{.DeathIndicator}}`, }), MRG: mustParseTemplate(MRG, "MRG|{{expand_mrns .MRNs}}|"), ORC: mustParseTemplate(ORC, "ORC|{{.OrderControl}}|{{.Placer}}|{{.Filler}}||{{.OrderStatus}}||||{{HL7_date .OrderDateTime}}"), OBR: mustParseTemplates(OBR, map[string]string{ ceTemplate: ceTmpl, doctorTemplate: doctorTmpl, OBR: `OBR|1|{{.Placer}}|{{.Filler}}|{{template "CETmpl" .OrderProfile}}||{{HL7_date .OrderDateTime}}|{{HL7_date .CollectedDateTime}}|||||||{{HL7_date .ReceivedInLabDateTime}}|{{.SpecimenSource}}|{{template "DoctorTmpl" .OrderingProvider}}||||||{{HL7_date .ReportedDateTime}}||{{.DiagnosticServID}}|{{.ResultsStatus}}||1`, }), OBRClinicalNote: mustParseTemplates(OBR, map[string]string{ ceTemplate: ceTmpl, doctorTemplate: doctorTmpl, OBR: `OBR|1|{{.Placer}}|{{.DocumentID}}|{{template "CETmpl" .OrderProfile}}||{{HL7_date .OrderDateTime}}|{{HL7_date .CollectedDateTime}}|||||||{{HL7_date .ReceivedInLabDateTime}}|{{.SpecimenSource}}|{{template "DoctorTmpl" .OrderingProvider}}||||||{{HL7_date .ReportedDateTime}}||{{.DiagnosticServID}}|{{.ResultsStatus}}||1`, }), OBX: mustParseTemplates(OBX, map[string]string{ ceTemplate: ceTmpl, OBX: `OBX|{{.ID}}|{{.ValueType}}|{{template "CETmpl" .TestName}}||{{HL7_repeated .Value}}|{{HL7_unit .Unit}}|{{escape_HL7 .Range}}|{{.AbnormalFlag}}|||{{.Status}}|||{{HL7_date .ObservationDateTime}}||`, }), OBXClinicalNote: mustParseTemplates(OBX, map[string]string{ ceNoteTemplate: ceNoteTmpl, noteTemplate: stOBXNoteVal, doctorTemplate: doctorTmpl, OBX: `OBX|{{.ID}}|{{.ValueType}}|{{template "CENoteTmpl" .ClinicalNote}}||{{template "NoteTmpl" .Content}}|||||||||{{HL7_date .ObservationDateTime}}||{{template "DoctorTmpl" .OrderingProvider}}`, }), OBXForMDM: mustParseTemplates(OBX, map[string]string{ ceTemplate: ceTmpl, OBX: `OBX|{{.ID}}|TX|{{template "CETmpl" .ObservationIdentifier}}|1|{{.Content}}||||||F||||||`, }), PV1: mustParseTemplates(PV1, map[string]string{ locationTemplate: locationTmpl, doctorTemplate: doctorTmpl, cxVisitTemplate: cxVisitTmpl, PV1: `PV1|1|{{.Class}}|{{template "LocationTmpl" .Location}}|28b||{{template "LocationTmpl" .PriorLocation}}|{{template "DoctorTmpl" .AttendingDoctor}}|||{{.HospitalService}}|{{template "LocationTmpl" .TemporaryLocation}}|||||||{{.Type}}|{{template "CXVisitTmpl" .VisitID}}||||||||||||||||||||||{{.AccountStatus}}|{{template "LocationTmpl" .PendingLocation}}|{{template "LocationTmpl" .PriorTemporaryLocation}}|{{HL7_date .AdmissionDate}}|{{HL7_date .DischargeDate}}|`, }), PV2: mustParseTemplates(PV2, map[string]string{ locationTemplate: locationTmpl, ceAdmitReasonTemplate: ceAdmitReasonTmpl, PV2: `PV2|{{template "LocationTmpl" .PriorPendingLocation}}||{{template "CEAdmitReasonTmpl" .AdmitReason}}|||||{{HL7_date .ExpectedAdmitDateTime}}|{{HL7_date .ExpectedDischargeDateTime}}`, }), NK1: mustParseTemplates(NK1, map[string]string{ personNameTemplate: personNameTmpl, addressTemplate: addressTmpl, homeNumberTemplate: homeNumberTmpl, ceTemplate: ceTmpl, NK1: `NK1|{{.ID}}|{{template "PersonNameTmpl" .}}|{{template "CETmpl" .Relationship}}|{{template "AddressTmpl" .Address}}|{{template "HomeNumberTmpl" .PhoneNumber}}||{{template "CETmpl" .ContactRole}}||||||||{{.Gender}}|`, }), AL1: mustParseTemplates(AL1, map[string]string{ ceTemplate: ceTmpl, AL1: `AL1|{{.ID}}|{{.Type}}|{{template "CETmpl" .Description}}|{{.Severity}}|{{.Reaction}}|{{HL7_date .IdentificationDateTime}}`, }), NTE: mustParseTemplate(NTE, `NTE|{{.ID}}||{{.Note}}|`), DG1: mustParseTemplates(DG1, map[string]string{ ceTemplate: ceTmpl, doctorTemplate: doctorTmpl, DG1: `DG1|{{.ID}}|SNMCT|{{template "CETmpl" .Description}}|{{.Description.Text}}|{{HL7_date .DateTime}}|{{.Type}}|||||||||0|{{template "DoctorTmpl" .Clinician}}`, }), PD1: mustParseTemplates(PD1, map[string]string{ primFacTemplate: primFacTmpl, PD1: `PD1|||{{template "PrimFacTmpl" .PrimaryFacility}}|`, }), PR1: mustParseTemplates(PR1, map[string]string{ ceTemplate: ceTmpl, doctorTemplate: doctorTmpl, PR1: `PR1|{{.ID}}|SNMCT|{{template "CETmpl" .Description}}|{{.Description.Text}}|{{HL7_date .DateTime}}|{{.Type}}||||||{{template "DoctorTmpl" .Clinician}}||0||`, }), TXA: mustParseTemplates(TXA, map[string]string{ doctorTemplate: doctorTmpl, TXA: `TXA|1|{{.DocumentType}}||{{HL7_date .ActivityDateTime}}|{{template "DoctorTmpl" .AttendingDoctor}}|||{{HL7_date .EditDateTime}}||||{{.UniqueDocumentNumber}}|||||{{.DocumentCompletionStatus}}||||||`, }), } func BuildDocumentNotificationMDMT02(h *HeaderInfo, p *ir.PatientInfo, d *ir.Document, eventTime time.Time, msgTime time.Time) (*HL7Message, error) { msgType := &Type{ MessageType: MDM, TriggerEvent: "T02", } var segments []string msh, err := BuildMSH(msgTime, msgType, h) if err != nil { return nil, errors.Wrap(err, "cannot build MSH segment") } segments = append(segments, msh) evn, err := BuildEVN(eventTime, msgType, ir.NewInvalidTime(), p.AttendingDoctor, ir.NewInvalidTime()) if err != nil { return nil, errors.Wrap(err, "cannot build EVN segment") } segments = append(segments, evn) pid, err := BuildPID(p.Person) if err != nil { return nil, errors.Wrap(err, "cannot build PID segment") } segments = append(segments, pid) pv1, err := BuildPV1(p) if err != nil { return nil, errors.Wrap(err, "cannot build PV1 segment") } segments = append(segments, pv1) txa, err := BuildTXA(p, d) if err != nil { return nil, errors.Wrap(err, "cannot build TXA segment") } segments = append(segments, txa) for id, note := range d.ContentLine { obx, err := BuildOBXForMDM(id+1, d.ObservationIdentifier, note) if err != nil { return nil, errors.Wrap(err, "cannot build OBX segment") } segments = append(segments, obx) } return &HL7Message{ Type: msgType, Message: strings.Join(segments, SegmentTerminator), }, nil } func BuildResultORUR01(h *HeaderInfo, p *ir.PatientInfo, o *ir.Order, msgTime time.Time) (*HL7Message, error) { msgType := &Type{ MessageType: ORU, TriggerEvent: "R01", } segments, err := segmentsORU(h, p, o, msgTime, msgType) if err != nil { return nil, err } return &HL7Message{ Type: msgType, Message: strings.Join(segments, SegmentTerminator), }, nil } func BuildResultORUR03(h *HeaderInfo, p *ir.PatientInfo, o *ir.Order, msgTime time.Time) (*HL7Message, error) { msgType := &Type{ MessageType: ORU, TriggerEvent: "R03", } segments, err := segmentsORU(h, p, o, msgTime, msgType) if err != nil { return nil, err } return &HL7Message{ Type: msgType, Message: strings.Join(segments, SegmentTerminator), }, nil } func BuildResultORUR32(h *HeaderInfo, p *ir.PatientInfo, o *ir.Order, msgTime time.Time) (*HL7Message, error) { msgType := &Type{ MessageType: ORU, TriggerEvent: "R32", } segments, err := segmentsORU(h, p, o, msgTime, msgType) if err != nil { return nil, err } return &HL7Message{ Type: msgType, Message: strings.Join(segments, SegmentTerminator), }, nil } func segmentsORU(h *HeaderInfo, p *ir.PatientInfo, o *ir.Order, msgTime time.Time, msgType *Type) ([]string, error) { var segments []string msh, err := BuildMSH(msgTime, msgType, h) if err != nil { return nil, errors.Wrap(err, "cannot build MSH segment") } segments = append(segments, msh) pid, err := BuildPID(p.Person) if err != nil { return nil, errors.Wrap(err, "cannot build PID segment") } segments = append(segments, pid) pv1, err := BuildPV1(p) if err != nil { return nil, errors.Wrap(err, "cannot build PV1 segment") } segments = append(segments, pv1) orc, err := BuildORC(o) if err != nil { return nil, errors.Wrap(err, "cannot build ORC segment") } segments = append(segments, orc) obr, err := BuildOBR(o) if err != nil { return nil, errors.Wrap(err, "cannot build OBR segment") } segments = append(segments, obr) if o.DiagnosticServID == DiagnosticServIDMDOC { return clinicalNotesOBX(o, segments) } return resultsOBX(o, segments) } func clinicalNotesOBX(o *ir.Order, segments []string) ([]string, error) { for _, result := range o.Results { for id := range result.ClinicalNote.Contents { obx, err := BuildOBXForClinicalNote(id+1, id, result, o) if err != nil { return nil, errors.Wrap(err, "cannot build OBX segment") } segments = append(segments, obx) } } return segments, nil } func resultsOBX(o *ir.Order, segments []string) ([]string, error) { for id, result := range o.Results { obx, err := BuildOBX(o.NumberOfPreviousResults+id+1, result, o) if err != nil { return nil, errors.Wrap(err, "cannot build OBX segment") } segments = append(segments, obx) for noteID, note := range result.Notes { nte, err := BuildNTE(noteID, note) if err != nil { return nil, errors.Wrap(err, "cannot build NTE segment") } segments = append(segments, nte) } } return segments, nil } func BuildOrderORMO01(h *HeaderInfo, p *ir.PatientInfo, o *ir.Order, msgTime time.Time) (*HL7Message, error) { msgType := &Type{ MessageType: ORM, TriggerEvent: "O01", } var segments []string msh, err := BuildMSH(msgTime, msgType, h) if err != nil { return nil, errors.Wrap(err, "cannot build MSH segment") } segments = append(segments, msh) pid, err := BuildPID(p.Person) if err != nil { return nil, errors.Wrap(err, "cannot build PID segment") } segments = append(segments, pid) pv1, err := BuildPV1(p) if err != nil { return nil, errors.Wrap(err, "cannot build PV1 segment") } segments = append(segments, pv1) orc, err := BuildORC(o) if err != nil { return nil, errors.Wrap(err, "cannot build ORC segment") } segments = append(segments, orc) obr, err := BuildOBR(o) if err != nil { return nil, errors.Wrap(err, "cannot build OBR segment") } segments = append(segments, obr) for noteID, note := range o.NotesForORM { nte, err := BuildNTE(noteID, note) if err != nil { return nil, errors.Wrap(err, "cannot build NTE segment") } segments = append(segments, nte) } for id, result := range o.ResultsForORM { obx, err := BuildOBX(id+1, result, o) if err != nil { return nil, errors.Wrap(err, "cannot build OBX segment") } segments = append(segments, obx) for noteID, note := range result.Notes { nte, err := BuildNTE(noteID, note) if err != nil { return nil, errors.Wrap(err, "cannot build NTE segment") } segments = append(segments, nte) } } return &HL7Message{ Type: msgType, Message: strings.Join(segments, SegmentTerminator), }, nil }
Apache License 2.0
chenhg5/collection
map_collection.go
Merge
go
func (c MapCollection) Merge(i interface{}) Collection { m := i.(map[string]interface{}) var d = copyMap(c.value) for key, value := range m { d[key] = value } return MapCollection{ value: d, } }
Merge merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection.
https://github.com/chenhg5/collection/blob/f403b87088f9c6d09c5a94fb64d8a85b8019c810/map_collection.go#L281-L292
package collection import ( "encoding/json" "fmt" "github.com/mitchellh/mapstructure" ) type MapCollection struct { value map[string]interface{} BaseCollection } func (c MapCollection) Only(keys []string) Collection { var ( d MapCollection m = make(map[string]interface{}, 0) ) for _, k := range keys { m[k] = c.value[k] } d.value = m d.length = len(m) return d } func (c MapCollection) ToStruct(dist interface{}) { if err := mapstructure.Decode(c.value, dist); err != nil { panic(err) } } func (c MapCollection) Select(keys ...string) Collection { n := copyMap(c.value) for key := range n { exist := false for i := 0; i < len(keys); i++ { if keys[i] == key { exist = true break } } if !exist { delete(n, key) } } return MapCollection{ value: n, } } func (c MapCollection) Prepend(values ...interface{}) Collection { var m = copyMap(c.value) m[values[0].(string)] = values[1] return MapCollection{m, BaseCollection{length: len(m)}} } func (c MapCollection) ToMap() map[string]interface{} { return c.value } func (c MapCollection) Contains(value ...interface{}) bool { if callback, ok := value[0].(CB); ok { for k, v := range c.value { if callback(k, v) { return true } } return false } for _, v := range c.value { if v == value[0] { return true } } return false } func (c MapCollection) Dd() { dd(c) } func (c MapCollection) Dump() { dump(c) } func (c MapCollection) DiffAssoc(m map[string]interface{}) Collection { var d = make(map[string]interface{}, 0) for key, value := range m { if v, ok := c.value[key]; ok { if v != value { d[key] = value } } } return MapCollection{ value: d, } } func (c MapCollection) DiffKeys(m map[string]interface{}) Collection { var d = make(map[string]interface{}, 0) for key, value := range c.value { if _, ok := m[key]; !ok { d[key] = value } } return MapCollection{ value: d, } } func (c MapCollection) Each(cb func(item, value interface{}) (interface{}, bool)) Collection { var d = make(map[string]interface{}, 0) var ( newValue interface{} stop = false ) for key, value := range c.value { if !stop { newValue, stop = cb(key, value) d[key] = newValue } else { d[key] = value } } return MapCollection{ value: d, } } func (c MapCollection) Every(cb CB) bool { for key, value := range c.value { if !cb(key, value) { return false } } return true } func (c MapCollection) Except(keys []string) Collection { var d = copyMap(c.value) for _, key := range keys { delete(d, key) } return MapCollection{ value: d, } } func (c MapCollection) FlatMap(cb func(value interface{}) interface{}) Collection { var d = make(map[string]interface{}, 0) for key, value := range c.value { d[key] = cb(value) } return MapCollection{ value: d, } } func (c MapCollection) Flip() Collection { var d = make(map[string]interface{}, 0) for key, value := range c.value { d[fmt.Sprintf("%v", value)] = key } return MapCollection{ value: d, } } func (c MapCollection) Forget(k string) Collection { var d = copyMap(c.value) for key := range c.value { if key == k { delete(d, key) } } return MapCollection{ value: d, } } func (c MapCollection) Get(k string, v ...interface{}) interface{} { if len(v) > 0 { if value, ok := c.value[k]; ok { return value } else { return v[0] } } else { return c.value[k] } } func (c MapCollection) Has(keys ...string) bool { for _, key := range keys { exist := false for kk := range c.value { if key == kk { exist = true break } } if !exist { return false } } return true } func (c MapCollection) IntersectByKeys(m map[string]interface{}) Collection { var d = make(map[string]interface{}, 0) for key, value := range c.value { for kk := range m { if kk == key { d[kk] = value } } } return MapCollection{ value: d, } } func (c MapCollection) IsEmpty() bool { return len(c.value) == 0 } func (c MapCollection) IsNotEmpty() bool { return len(c.value) != 0 } func (c MapCollection) Keys() Collection { var d = make([]string, 0) for key := range c.value { d = append(d, key) } return StringArrayCollection{ value: d, } }
MIT License
vivena/babelweb2
ws/multicastGroup.go
NewListenerGroup
go
func NewListenerGroup() *Listenergroup { lg := new(Listenergroup) lg.listeners = list.New() return lg }
NewListenerGroup function to call if you want a new Listenergroup
https://github.com/vivena/babelweb2/blob/dbbe0ab73cccaa65a98b89303749e81ac725aa8b/ws/multicastGroup.go#L29-L33
package ws import ( "container/list" "sync" "github.com/Vivena/babelweb2/parser" ) type Listener struct { Channel chan parser.SBabelUpdate } func NewListener() *Listener { l := new(Listener) l.Channel = make(chan parser.SBabelUpdate) return l } type Listenergroup struct { sync.Mutex listeners *list.List }
MIT License
ianremmler/ode
mass.go
SetBox
go
func (m *Mass) SetBox(density float64, lens Vector3) { c := &C.dMass{} C.dMassSetBox(c, C.dReal(density), C.dReal(lens[0]), C.dReal(lens[1]), C.dReal(lens[2])) m.fromC(c) }
SetBox sets the mass for a box of given properties.
https://github.com/ianremmler/ode/blob/b062ec7b88b9c10919d5a00f8e6a757ca6a7b9d7/mass.go#L104-L109
package ode import "C" type Mass struct { Center Vector3 Inertia Matrix3 Mass float64 } func (m *Mass) toC(c *C.dMass) { c.mass = C.dReal(m.Mass) Vector(m.Center).toC((*C.dReal)(&c.c[0])) Matrix(m.Inertia).toC((*C.dReal)(&c.I[0])) } func (m *Mass) fromC(c *C.dMass) { m.Mass = float64(c.mass) Vector(m.Center).fromC((*C.dReal)(&c.c[0])) Matrix(m.Inertia).fromC((*C.dReal)(&c.I[0])) } func NewMass() *Mass { return &Mass{ Center: NewVector3(), Inertia: NewMatrix3(), } } func (m *Mass) Check() bool { c := &C.dMass{} m.toC(c) return C.dMassCheck(c) != 0 } func (m *Mass) SetZero() { c := &C.dMass{} C.dMassSetZero(c) m.fromC(c) } func (m *Mass) SetParams(mass float64, com Vector3, inert Matrix3) { c := &C.dMass{} C.dMassSetParameters(c, C.dReal(mass), C.dReal(com[0]), C.dReal(com[1]), C.dReal(com[2]), C.dReal(inert[0][0]), C.dReal(inert[1][1]), C.dReal(inert[2][2]), C.dReal(inert[0][1]), C.dReal(inert[0][2]), C.dReal(inert[1][3])) m.fromC(c) } func (m *Mass) SetSphere(density, radius float64) { c := &C.dMass{} C.dMassSetSphere(c, C.dReal(density), C.dReal(radius)) m.fromC(c) } func (m *Mass) SetSphereTotal(totalMass, radius float64) { c := &C.dMass{} C.dMassSetSphereTotal(c, C.dReal(totalMass), C.dReal(radius)) m.fromC(c) } func (m *Mass) SetCapsule(density float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCapsule(c, C.dReal(density), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } func (m *Mass) SetCapsuleTotal(totalMass float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCapsuleTotal(c, C.dReal(totalMass), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } func (m *Mass) SetCylinder(density float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCylinder(c, C.dReal(density), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } func (m *Mass) SetCylinderTotal(totalMass float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCylinderTotal(c, C.dReal(totalMass), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) }
MIT License
bbqgophers/qpid
vendor/github.com/hybridgroup/gobot/platforms/leap/parser.go
Y
go
func (h *Hand) Y() float64 { return h.PalmPosition[1] }
Y returns hand y value
https://github.com/bbqgophers/qpid/blob/3f64f60bf13d69b51132ed0085f88c27b065e256/vendor/github.com/hybridgroup/gobot/platforms/leap/parser.go#L74-L76
package leap import ( "encoding/json" ) type Gesture struct { Direction []float64 `json:"direction"` Duration int `json:"duration"` Hands []Hand `json:"hands"` ID int `json:"id"` Pointables []Pointable `json:"pointables"` Position []float64 `json:"position"` Speed float64 `json:"speed"` StartPosition []float64 `json:"StartPosition"` State string `json:"state"` Type string `json:"type"` } type Hand struct { Direction []float64 `json:"direction"` ID int `json:"id"` PalmNormal []float64 `json:"palmNormal"` PalmPosition []float64 `json:"PalmPosition"` PalmVelocity []float64 `json:"PalmVelocity"` R [][]float64 `json:"r"` S float64 `json:"s"` SphereCenter []float64 `json:"sphereCenter"` SphereRadius float64 `json:"sphereRadius"` StabilizedPalmPosition []float64 `json:"stabilizedPalmPosition"` T []float64 `json:"t"` TimeVisible float64 `json:"TimeVisible"` } type Pointable struct { Direction []float64 `json:"direction"` HandID int `json:"handId"` ID int `json:"id"` Length float64 `json:"length"` StabilizedTipPosition []float64 `json:"stabilizedTipPosition"` TimeVisible float64 `json:"timeVisible"` TipPosition []float64 `json:"tipPosition"` TipVelocity []float64 `json:"tipVelocity"` Tool bool `json:"tool"` TouchDistance float64 `json:"touchDistance"` TouchZone string `json:"touchZone"` } type InteractionBox struct { Center []int `json:"center"` Size []float64 `json:"size"` } type Frame struct { CurrentFrameRate float64 `json:"currentFrameRate"` Gestures []Gesture `json:"gestures"` Hands []Hand `json:"hands"` ID int `json:"id"` InteractionBox InteractionBox `json:"interactionBox"` Pointables []Pointable `json:"pointables"` R [][]float64 `json:"r"` S float64 `json:"s"` T []float64 `json:"t"` Timestamp int `json:"timestamp"` } func (h *Hand) X() float64 { return h.PalmPosition[0] }
MIT License
cloudwego/kitex
pkg/remote/codec/header_codec.go
encode
go
func (m meshHeader) encode(ctx context.Context, message remote.Message, payloadBuf, out remote.ByteBuffer) error { return nil }
lint:ignore U1000 until encode is used
https://github.com/cloudwego/kitex/blob/c1c542f7fc276068bdf1c88ed626d31f5ee69bb5/pkg/remote/codec/header_codec.go#L412-L415
package codec import ( "context" "encoding/binary" "fmt" "io" "github.com/cloudwego/kitex/pkg/klog" "github.com/cloudwego/kitex/pkg/remote" "github.com/cloudwego/kitex/pkg/remote/codec/perrors" "github.com/cloudwego/kitex/pkg/serviceinfo" ) const ( TTHeaderMagic uint32 = 0x10000000 MeshHeaderMagic uint32 = 0xFFAF0000 MeshHeaderLenMask uint32 = 0x0000FFFF FlagsMask uint32 = 0x0000FFFF MethodMask uint32 = 0x41000000 MaxFrameSize uint32 = 0x3FFFFFFF MaxHeaderSize uint32 = 65536 ) type HeaderFlags uint16 const ( HeaderFlagsKey string = "HeaderFlags" HeaderFlagSupportOutOfOrder HeaderFlags = 0x01 HeaderFlagDuplexReverse HeaderFlags = 0x08 HeaderFlagSASL HeaderFlags = 0x10 ) const ( TTHeaderMetaSize = 14 ) type ProtocolID uint8 const ( ProtocolIDThriftBinary ProtocolID = 0x00 ProtocolIDThriftCompact ProtocolID = 0x02 ProtocolIDProtobufKitex ProtocolID = 0x03 ProtocolIDDefault = ProtocolIDThriftBinary ) type InfoIDType uint8 const ( InfoIDPadding InfoIDType = 0 InfoIDKeyValue InfoIDType = 0x01 InfoIDIntKeyValue InfoIDType = 0x10 InfoIDACLToken InfoIDType = 0x11 ) type ttHeader struct{} func (t ttHeader) encode(ctx context.Context, message remote.Message, out remote.ByteBuffer) (totalLenField []byte, err error) { var headerMeta []byte headerMeta, err = out.Malloc(TTHeaderMetaSize) if err != nil { return nil, perrors.NewProtocolErrorWithMsg(fmt.Sprintf("ttHeader malloc header meta failed, %s", err.Error())) } totalLenField = headerMeta[0:4] headerInfoSizeField := headerMeta[12:14] binary.BigEndian.PutUint32(headerMeta[4:8], TTHeaderMagic+uint32(getFlags(message))) binary.BigEndian.PutUint32(headerMeta[8:12], uint32(message.RPCInfo().Invocation().SeqID())) var transformIDs []uint8 if err = WriteByte(byte(getProtocolID(message.ProtocolInfo())), out); err != nil { return nil, perrors.NewProtocolErrorWithMsg(fmt.Sprintf("ttHeader write protocol id failed, %s", err.Error())) } if err = WriteByte(byte(len(transformIDs)), out); err != nil { return nil, perrors.NewProtocolErrorWithMsg(fmt.Sprintf("ttHeader write transformIDs length failed, %s", err.Error())) } for tid := range transformIDs { if err = WriteByte(byte(tid), out); err != nil { return nil, perrors.NewProtocolErrorWithMsg(fmt.Sprintf("ttHeader write transformIDs failed, %s", err.Error())) } } headerInfoSize := 1 + 1 + len(transformIDs) headerInfoSize, err = writeKVInfo(headerInfoSize, message, out) if err != nil { return nil, perrors.NewProtocolErrorWithMsg(fmt.Sprintf("ttHeader write kv info failed, %s", err.Error())) } binary.BigEndian.PutUint16(headerInfoSizeField, uint16(headerInfoSize/4)) return totalLenField, err } func (t ttHeader) decode(ctx context.Context, message remote.Message, in remote.ByteBuffer) error { headerMeta, err := in.Next(TTHeaderMetaSize) if err != nil { return perrors.NewProtocolError(err) } if !IsTTHeader(headerMeta) { return perrors.NewProtocolErrorWithMsg("not TTHeader protocol") } totalLen := Bytes2Uint32NoCheck(headerMeta[:Size32]) flags := Bytes2Uint16NoCheck(headerMeta[Size16*3:]) setFlags(flags, message) seqID := Bytes2Uint32NoCheck(headerMeta[Size32*2 : Size32*3]) if err = SetOrCheckSeqID(int32(seqID), message); err != nil { klog.Warnf("the seqID in TTHeader check failed, err=%s", err.Error()) } headerInfoSize := Bytes2Uint16NoCheck(headerMeta[Size32*3:TTHeaderMetaSize]) * 4 if uint32(headerInfoSize) > MaxHeaderSize || headerInfoSize < 2 { return perrors.NewProtocolErrorWithMsg(fmt.Sprintf("invalid header length[%d]", headerInfoSize)) } var headerInfo []byte if headerInfo, err = in.Next(int(headerInfoSize)); err != nil { return perrors.NewProtocolError(err) } if err = checkProtocalID(headerInfo[0], message); err != nil { return err } hdIdx := 2 transformIDNum := int(headerInfo[1]) if int(headerInfoSize)-hdIdx < transformIDNum { return perrors.NewProtocolErrorWithType(perrors.InvalidData, fmt.Sprintf("need read %d transformIDs, but not enough", transformIDNum)) } transformIDs := make([]uint8, transformIDNum) for i := 0; i < transformIDNum; i++ { transformIDs[i] = headerInfo[hdIdx] hdIdx++ } if err := readKVInfo(hdIdx, headerInfo, message); err != nil { return perrors.NewProtocolErrorWithMsg(fmt.Sprintf("ttTHeader read kv info failed, %s", err.Error())) } message.SetPayloadLen(int(totalLen - uint32(headerInfoSize) + Size32 - TTHeaderMetaSize)) return err } func writeKVInfo(writtenSize int, message remote.Message, out remote.ByteBuffer) (writeSize int, err error) { writeSize = writtenSize tm := message.TransInfo() strKVSize := len(tm.TransStrInfo()) if strKVSize > 0 { if err = WriteByte(byte(InfoIDKeyValue), out); err != nil { return writeSize, err } if err = WriteUint16(uint16(strKVSize), out); err != nil { return writeSize, err } writeSize += 3 for key, val := range tm.TransStrInfo() { keyWLen, err := WriteString2BLen(key, out) if err != nil { return writeSize, err } valWLen, err := WriteString2BLen(val, out) if err != nil { return writeSize, err } writeSize = writeSize + keyWLen + valWLen } } intKVSize := len(tm.TransIntInfo()) if intKVSize > 0 { if err = WriteByte(byte(InfoIDIntKeyValue), out); err != nil { return writeSize, err } if err = WriteUint16(uint16(intKVSize), out); err != nil { return writeSize, err } writeSize += 3 for key, val := range tm.TransIntInfo() { if err = WriteUint16(key, out); err != nil { return writeSize, err } valWLen, err := WriteString2BLen(val, out) if err != nil { return writeSize, err } writeSize = writeSize + 2 + valWLen } } padding := (4 - writeSize%4) % 4 paddingBuf, err := out.Malloc(padding) if err != nil { return writeSize, err } for i := 0; i < len(paddingBuf); i++ { paddingBuf[i] = byte(0) } writeSize += padding return } func readKVInfo(idx int, buf []byte, message remote.Message) error { intInfo := message.TransInfo().TransIntInfo() strInfo := message.TransInfo().TransStrInfo() for { infoID, err := Bytes2Uint8(buf, idx) idx++ if err != nil { if err == io.EOF { break } else { return err } } switch InfoIDType(infoID) { case InfoIDPadding: continue case InfoIDKeyValue: _, err := readStrKVInfo(&idx, buf, strInfo) if err != nil { return err } case InfoIDIntKeyValue: _, err := readIntKVInfo(&idx, buf, intInfo) if err != nil { return err } case InfoIDACLToken: err = skipACLToken(&idx, buf) if err != nil { return err } default: return fmt.Errorf("invalid infoIDType[%#x]", infoID) } } return nil } func readIntKVInfo(idx *int, buf []byte, info map[uint16]string) (has bool, err error) { kvSize, err := Bytes2Uint16(buf, *idx) *idx += 2 if err != nil { return false, fmt.Errorf("error reading int kv info size: %s", err.Error()) } if kvSize <= 0 { return false, nil } for i := uint16(0); i < kvSize; i++ { key, err := Bytes2Uint16(buf, *idx) *idx += 2 if err != nil { return false, fmt.Errorf("error reading int kv info: %s", err.Error()) } val, n, err := ReadString2BLen(buf, *idx) *idx += n if err != nil { return false, fmt.Errorf("error reading int kv info: %s", err.Error()) } info[key] = val } return true, nil } func readStrKVInfo(idx *int, buf []byte, info map[string]string) (has bool, err error) { kvSize, err := Bytes2Uint16(buf, *idx) *idx += 2 if err != nil { return false, fmt.Errorf("error reading str kv info size: %s", err.Error()) } if kvSize <= 0 { return false, nil } for i := uint16(0); i < kvSize; i++ { key, n, err := ReadString2BLen(buf, *idx) *idx += n if err != nil { return false, fmt.Errorf("error reading str kv info: %s", err.Error()) } val, n, err := ReadString2BLen(buf, *idx) *idx += n if err != nil { return false, fmt.Errorf("error reading str kv info: %s", err.Error()) } info[key] = val } return true, nil } func skipACLToken(idx *int, buf []byte) error { _, n, err := ReadString2BLen(buf, *idx) *idx += n if err != nil { return fmt.Errorf("error reading acl token: %s", err.Error()) } return nil } func getFlags(message remote.Message) HeaderFlags { var headerFlags HeaderFlags if message.Tags() != nil && message.Tags()[HeaderFlagsKey] != nil { headerFlags = message.Tags()[HeaderFlagsKey].(HeaderFlags) } return headerFlags } func setFlags(flags uint16, message remote.Message) { if message.MessageType() == remote.Call { message.Tags()[HeaderFlagsKey] = flags } } func getProtocolID(pi remote.ProtocolInfo) ProtocolID { switch pi.CodecType { case serviceinfo.Protobuf: return ProtocolIDProtobufKitex } return ProtocolIDDefault } func checkProtocalID(protoID uint8, message remote.Message) error { switch protoID { case uint8(ProtocolIDProtobufKitex): case uint8(ProtocolIDThriftBinary): default: return fmt.Errorf("unsupport ProtocolID[%d]", protoID) } return nil } type meshHeader struct{}
Apache License 2.0
konveyor/move2kube
transformer/classes/dockerfile/windows/utils.go
parseSolutionFile
go
func parseSolutionFile(inputPath string) ([]string, error) { solFileTxt, err := ioutil.ReadFile(inputPath) if err != nil { return nil, fmt.Errorf("could not open the solution file: %s", err) } projectPaths := make([]string, 0) projBlockRegex := regexp.MustCompile(dotnet.ProjBlock) l := projBlockRegex.FindAllStringSubmatch(string(solFileTxt), -1) for _, path := range l { if len(path) == 0 { continue } projectPaths = append(projectPaths, path[0]) } separator := fmt.Sprintf("%c", os.PathSeparator) for i, c := range projectPaths { c = strings.Trim(c, `"`) if runtime.GOOS != "windows" { c = strings.ReplaceAll(c, `\`, separator) } projectPaths[i] = c } return projectPaths, nil }
parseSolutionFile parses the solution file for cs project file paths
https://github.com/konveyor/move2kube/blob/70982af31410f4c2e729e2083ccfbcd03329600c/transformer/classes/dockerfile/windows/utils.go#L67-L90
package windows import ( "fmt" "io/ioutil" "os" "regexp" "runtime" "strings" "github.com/konveyor/move2kube/types/source/dotnet" ) func isSilverlight(configuration dotnet.CSProj) (bool, error) { if configuration.ItemGroups == nil || len(configuration.ItemGroups) == 0 { return false, fmt.Errorf("no item groups in project file to parse") } for _, ig := range configuration.ItemGroups { if ig.Contents == nil || len(ig.Contents) == 0 { continue } for _, r := range ig.Contents { if dotnet.WebSLLib.MatchString(r.Include) { return true, nil } } } return false, nil } func isWeb(configuration dotnet.CSProj) (bool, error) { if configuration.ItemGroups == nil || len(configuration.ItemGroups) == 0 { return false, fmt.Errorf("no item groups in project file to parse") } for _, ig := range configuration.ItemGroups { if ig.References == nil || len(ig.References) == 0 { continue } for _, r := range ig.References { if dotnet.WebLib.MatchString(r.Include) { return true, nil } } } return false, nil }
Apache License 2.0
kubernetes-sigs/cluster-proportional-autoscaler
vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go
Patch
go
func (c *priorityClasses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.PriorityClass, err error) { result = &v1beta1.PriorityClass{} err = c.client.Patch(pt). Resource("priorityclasses"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }
Patch applies the patch and returns the patched priorityClass.
https://github.com/kubernetes-sigs/cluster-proportional-autoscaler/blob/84a3b6968fd47e25a9ba5039ee29b47219b7e9c4/vendor/k8s.io/client-go/kubernetes/typed/scheduling/v1beta1/priorityclass.go#L154-L164
package v1beta1 import ( "time" v1beta1 "k8s.io/api/scheduling/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" scheme "k8s.io/client-go/kubernetes/scheme" rest "k8s.io/client-go/rest" ) type PriorityClassesGetter interface { PriorityClasses() PriorityClassInterface } type PriorityClassInterface interface { Create(*v1beta1.PriorityClass) (*v1beta1.PriorityClass, error) Update(*v1beta1.PriorityClass) (*v1beta1.PriorityClass, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*v1beta1.PriorityClass, error) List(opts v1.ListOptions) (*v1beta1.PriorityClassList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.PriorityClass, err error) PriorityClassExpansion } type priorityClasses struct { client rest.Interface } func newPriorityClasses(c *SchedulingV1beta1Client) *priorityClasses { return &priorityClasses{ client: c.RESTClient(), } } func (c *priorityClasses) Get(name string, options v1.GetOptions) (result *v1beta1.PriorityClass, err error) { result = &v1beta1.PriorityClass{} err = c.client.Get(). Resource("priorityclasses"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(). Into(result) return } func (c *priorityClasses) List(opts v1.ListOptions) (result *v1beta1.PriorityClassList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1beta1.PriorityClassList{} err = c.client.Get(). Resource("priorityclasses"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(). Into(result) return } func (c *priorityClasses) Watch(opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Resource("priorityclasses"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch() } func (c *priorityClasses) Create(priorityClass *v1beta1.PriorityClass) (result *v1beta1.PriorityClass, err error) { result = &v1beta1.PriorityClass{} err = c.client.Post(). Resource("priorityclasses"). Body(priorityClass). Do(). Into(result) return } func (c *priorityClasses) Update(priorityClass *v1beta1.PriorityClass) (result *v1beta1.PriorityClass, err error) { result = &v1beta1.PriorityClass{} err = c.client.Put(). Resource("priorityclasses"). Name(priorityClass.Name). Body(priorityClass). Do(). Into(result) return } func (c *priorityClasses) Delete(name string, options *v1.DeleteOptions) error { return c.client.Delete(). Resource("priorityclasses"). Name(name). Body(options). Do(). Error() } func (c *priorityClasses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { var timeout time.Duration if listOptions.TimeoutSeconds != nil { timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second } return c.client.Delete(). Resource("priorityclasses"). VersionedParams(&listOptions, scheme.ParameterCodec). Timeout(timeout). Body(options). Do(). Error() }
Apache License 2.0
bonedaddy/go-compound
bindings/cusdc/cusdc.go
ReduceReserves
go
func (_Bindings *BindingsTransactor) ReduceReserves(opts *bind.TransactOpts, reduceAmount *big.Int) (*types.Transaction, error) { return _Bindings.contract.Transact(opts, "_reduceReserves", reduceAmount) }
ReduceReserves is a paid mutator transaction binding the contract method 0x601a0bf1. Solidity: function _reduceReserves(uint256 reduceAmount) returns(uint256)
https://github.com/bonedaddy/go-compound/blob/f63a814daddc6c73e9831ab4fb23faeffe647bd0/bindings/cusdc/cusdc.go#L831-L833
package bindings import ( "math/big" "strings" ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" ) var ( _ = big.NewInt _ = strings.NewReader _ = ethereum.NotFound _ = abi.U256 _ = bind.Bind _ = common.Big1 _ = types.BloomLookup _ = event.NewSubscription ) const BindingsABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x06fdde03\"},{\"constant\":false,\"inputs\":[{\"name\":\"spender\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x095ea7b3\"},{\"constant\":false,\"inputs\":[{\"name\":\"repayAmount\",\"type\":\"uint256\"}],\"name\":\"repayBorrow\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x0e752702\"},{\"constant\":true,\"inputs\":[],\"name\":\"reserveFactorMantissa\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x173b9904\"},{\"constant\":false,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"borrowBalanceCurrent\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x17bfdfbc\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x18160ddd\"},{\"constant\":true,\"inputs\":[],\"name\":\"exchangeRateStored\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x182df0f5\"},{\"constant\":false,\"inputs\":[{\"name\":\"src\",\"type\":\"address\"},{\"name\":\"dst\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x23b872dd\"},{\"constant\":false,\"inputs\":[{\"name\":\"borrower\",\"type\":\"address\"},{\"name\":\"repayAmount\",\"type\":\"uint256\"}],\"name\":\"repayBorrowBehalf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x2608f818\"},{\"constant\":true,\"inputs\":[],\"name\":\"pendingAdmin\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x26782247\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x313ce567\"},{\"constant\":false,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOfUnderlying\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x3af9e669\"},{\"constant\":true,\"inputs\":[],\"name\":\"getCash\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x3b1d21a2\"},{\"constant\":false,\"inputs\":[{\"name\":\"newComptroller\",\"type\":\"address\"}],\"name\":\"_setComptroller\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x4576b5db\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalBorrows\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x47bd3718\"},{\"constant\":true,\"inputs\":[],\"name\":\"comptroller\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x5fe3b567\"},{\"constant\":false,\"inputs\":[{\"name\":\"reduceAmount\",\"type\":\"uint256\"}],\"name\":\"_reduceReserves\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x601a0bf1\"},{\"constant\":true,\"inputs\":[],\"name\":\"initialExchangeRateMantissa\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x675d972c\"},{\"constant\":true,\"inputs\":[],\"name\":\"accrualBlockNumber\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x6c540baf\"},{\"constant\":true,\"inputs\":[],\"name\":\"underlying\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x6f307dc3\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x70a08231\"},{\"constant\":false,\"inputs\":[],\"name\":\"totalBorrowsCurrent\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x73acee98\"},{\"constant\":false,\"inputs\":[{\"name\":\"redeemAmount\",\"type\":\"uint256\"}],\"name\":\"redeemUnderlying\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0x852a12e3\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalReserves\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x8f840ddd\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x95d89b41\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"borrowBalanceStored\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0x95dd9193\"},{\"constant\":false,\"inputs\":[{\"name\":\"mintAmount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xa0712d68\"},{\"constant\":false,\"inputs\":[],\"name\":\"accrueInterest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xa6afed95\"},{\"constant\":false,\"inputs\":[{\"name\":\"dst\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xa9059cbb\"},{\"constant\":true,\"inputs\":[],\"name\":\"borrowIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xaa5af0fd\"},{\"constant\":true,\"inputs\":[],\"name\":\"supplyRatePerBlock\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xae9d70b0\"},{\"constant\":false,\"inputs\":[{\"name\":\"liquidator\",\"type\":\"address\"},{\"name\":\"borrower\",\"type\":\"address\"},{\"name\":\"seizeTokens\",\"type\":\"uint256\"}],\"name\":\"seize\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xb2a02ff1\"},{\"constant\":false,\"inputs\":[{\"name\":\"newPendingAdmin\",\"type\":\"address\"}],\"name\":\"_setPendingAdmin\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xb71d1a0c\"},{\"constant\":false,\"inputs\":[],\"name\":\"exchangeRateCurrent\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xbd6d894d\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"address\"}],\"name\":\"getAccountSnapshot\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xc37f68e2\"},{\"constant\":false,\"inputs\":[{\"name\":\"borrowAmount\",\"type\":\"uint256\"}],\"name\":\"borrow\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xc5ebeaec\"},{\"constant\":false,\"inputs\":[{\"name\":\"redeemTokens\",\"type\":\"uint256\"}],\"name\":\"redeem\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xdb006a75\"},{\"constant\":true,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"},{\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xdd62ed3e\"},{\"constant\":false,\"inputs\":[],\"name\":\"_acceptAdmin\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xe9c714f2\"},{\"constant\":false,\"inputs\":[{\"name\":\"newInterestRateModel\",\"type\":\"address\"}],\"name\":\"_setInterestRateModel\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xf2b3abbd\"},{\"constant\":true,\"inputs\":[],\"name\":\"interestRateModel\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xf3fdb15a\"},{\"constant\":false,\"inputs\":[{\"name\":\"borrower\",\"type\":\"address\"},{\"name\":\"repayAmount\",\"type\":\"uint256\"},{\"name\":\"cTokenCollateral\",\"type\":\"address\"}],\"name\":\"liquidateBorrow\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xf5e3c462\"},{\"constant\":true,\"inputs\":[],\"name\":\"admin\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xf851a440\"},{\"constant\":true,\"inputs\":[],\"name\":\"borrowRatePerBlock\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xf8f9da28\"},{\"constant\":false,\"inputs\":[{\"name\":\"newReserveFactorMantissa\",\"type\":\"uint256\"}],\"name\":\"_setReserveFactor\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"signature\":\"0xfca7820b\"},{\"constant\":true,\"inputs\":[],\"name\":\"isCToken\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\",\"signature\":\"0xfe9c44ae\"},{\"inputs\":[{\"name\":\"underlying_\",\"type\":\"address\"},{\"name\":\"comptroller_\",\"type\":\"address\"},{\"name\":\"interestRateModel_\",\"type\":\"address\"},{\"name\":\"initialExchangeRateMantissa_\",\"type\":\"uint256\"},{\"name\":\"name_\",\"type\":\"string\"},{\"name\":\"symbol_\",\"type\":\"string\"},{\"name\":\"decimals_\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\",\"signature\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"interestAccumulated\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"borrowIndex\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalBorrows\",\"type\":\"uint256\"}],\"name\":\"AccrueInterest\",\"type\":\"event\",\"signature\":\"0x875352fb3fadeb8c0be7cbbe8ff761b308fa7033470cd0287f02f3436fd76cb9\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"minter\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"mintAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"mintTokens\",\"type\":\"uint256\"}],\"name\":\"Mint\",\"type\":\"event\",\"signature\":\"0x4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"redeemer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"redeemAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"redeemTokens\",\"type\":\"uint256\"}],\"name\":\"Redeem\",\"type\":\"event\",\"signature\":\"0xe5b754fb1abb7f01b499791d0b820ae3b6af3424ac1c59768edb53f4ec31a929\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"borrowAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"accountBorrows\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalBorrows\",\"type\":\"uint256\"}],\"name\":\"Borrow\",\"type\":\"event\",\"signature\":\"0x13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab80\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"payer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"repayAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"accountBorrows\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalBorrows\",\"type\":\"uint256\"}],\"name\":\"RepayBorrow\",\"type\":\"event\",\"signature\":\"0x1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a1\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"liquidator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"borrower\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"repayAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"cTokenCollateral\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"seizeTokens\",\"type\":\"uint256\"}],\"name\":\"LiquidateBorrow\",\"type\":\"event\",\"signature\":\"0x298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb52\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"oldPendingAdmin\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"newPendingAdmin\",\"type\":\"address\"}],\"name\":\"NewPendingAdmin\",\"type\":\"event\",\"signature\":\"0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"oldAdmin\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"NewAdmin\",\"type\":\"event\",\"signature\":\"0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"oldComptroller\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"newComptroller\",\"type\":\"address\"}],\"name\":\"NewComptroller\",\"type\":\"event\",\"signature\":\"0x7ac369dbd14fa5ea3f473ed67cc9d598964a77501540ba6751eb0b3decf5870d\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"oldInterestRateModel\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"newInterestRateModel\",\"type\":\"address\"}],\"name\":\"NewMarketInterestRateModel\",\"type\":\"event\",\"signature\":\"0xedffc32e068c7c95dfd4bdfd5c4d939a084d6b11c4199eac8436ed234d72f926\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"oldReserveFactorMantissa\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"newReserveFactorMantissa\",\"type\":\"uint256\"}],\"name\":\"NewReserveFactor\",\"type\":\"event\",\"signature\":\"0xaaa68312e2ea9d50e16af5068410ab56e1a1fd06037b1a35664812c30f821460\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"admin\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"reduceAmount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"newTotalReserves\",\"type\":\"uint256\"}],\"name\":\"ReservesReduced\",\"type\":\"event\",\"signature\":\"0x3bad0c59cf2f06e7314077049f48a93578cd16f5ef92329f1dab1420a99c177e\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"error\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"info\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"detail\",\"type\":\"uint256\"}],\"name\":\"Failure\",\"type\":\"event\",\"signature\":\"0x45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\",\"signature\":\"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\",\"signature\":\"0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925\"}]" type Bindings struct { BindingsCaller BindingsTransactor BindingsFilterer } type BindingsCaller struct { contract *bind.BoundContract } type BindingsTransactor struct { contract *bind.BoundContract } type BindingsFilterer struct { contract *bind.BoundContract } type BindingsSession struct { Contract *Bindings CallOpts bind.CallOpts TransactOpts bind.TransactOpts } type BindingsCallerSession struct { Contract *BindingsCaller CallOpts bind.CallOpts } type BindingsTransactorSession struct { Contract *BindingsTransactor TransactOpts bind.TransactOpts } type BindingsRaw struct { Contract *Bindings } type BindingsCallerRaw struct { Contract *BindingsCaller } type BindingsTransactorRaw struct { Contract *BindingsTransactor } func NewBindings(address common.Address, backend bind.ContractBackend) (*Bindings, error) { contract, err := bindBindings(address, backend, backend, backend) if err != nil { return nil, err } return &Bindings{BindingsCaller: BindingsCaller{contract: contract}, BindingsTransactor: BindingsTransactor{contract: contract}, BindingsFilterer: BindingsFilterer{contract: contract}}, nil } func NewBindingsCaller(address common.Address, caller bind.ContractCaller) (*BindingsCaller, error) { contract, err := bindBindings(address, caller, nil, nil) if err != nil { return nil, err } return &BindingsCaller{contract: contract}, nil } func NewBindingsTransactor(address common.Address, transactor bind.ContractTransactor) (*BindingsTransactor, error) { contract, err := bindBindings(address, nil, transactor, nil) if err != nil { return nil, err } return &BindingsTransactor{contract: contract}, nil } func NewBindingsFilterer(address common.Address, filterer bind.ContractFilterer) (*BindingsFilterer, error) { contract, err := bindBindings(address, nil, nil, filterer) if err != nil { return nil, err } return &BindingsFilterer{contract: contract}, nil } func bindBindings(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader(BindingsABI)) if err != nil { return nil, err } return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil } func (_Bindings *BindingsRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { return _Bindings.Contract.BindingsCaller.contract.Call(opts, result, method, params...) } func (_Bindings *BindingsRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { return _Bindings.Contract.BindingsTransactor.contract.Transfer(opts) } func (_Bindings *BindingsRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { return _Bindings.Contract.BindingsTransactor.contract.Transact(opts, method, params...) } func (_Bindings *BindingsCallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { return _Bindings.Contract.contract.Call(opts, result, method, params...) } func (_Bindings *BindingsTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { return _Bindings.Contract.contract.Transfer(opts) } func (_Bindings *BindingsTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { return _Bindings.Contract.contract.Transact(opts, method, params...) } func (_Bindings *BindingsCaller) AccrualBlockNumber(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "accrualBlockNumber") return *ret0, err } func (_Bindings *BindingsSession) AccrualBlockNumber() (*big.Int, error) { return _Bindings.Contract.AccrualBlockNumber(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) AccrualBlockNumber() (*big.Int, error) { return _Bindings.Contract.AccrualBlockNumber(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Admin(opts *bind.CallOpts) (common.Address, error) { var ( ret0 = new(common.Address) ) out := ret0 err := _Bindings.contract.Call(opts, out, "admin") return *ret0, err } func (_Bindings *BindingsSession) Admin() (common.Address, error) { return _Bindings.Contract.Admin(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) Admin() (common.Address, error) { return _Bindings.Contract.Admin(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Allowance(opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "allowance", owner, spender) return *ret0, err } func (_Bindings *BindingsSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { return _Bindings.Contract.Allowance(&_Bindings.CallOpts, owner, spender) } func (_Bindings *BindingsCallerSession) Allowance(owner common.Address, spender common.Address) (*big.Int, error) { return _Bindings.Contract.Allowance(&_Bindings.CallOpts, owner, spender) } func (_Bindings *BindingsCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "balanceOf", owner) return *ret0, err } func (_Bindings *BindingsSession) BalanceOf(owner common.Address) (*big.Int, error) { return _Bindings.Contract.BalanceOf(&_Bindings.CallOpts, owner) } func (_Bindings *BindingsCallerSession) BalanceOf(owner common.Address) (*big.Int, error) { return _Bindings.Contract.BalanceOf(&_Bindings.CallOpts, owner) } func (_Bindings *BindingsCaller) BorrowBalanceStored(opts *bind.CallOpts, account common.Address) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "borrowBalanceStored", account) return *ret0, err } func (_Bindings *BindingsSession) BorrowBalanceStored(account common.Address) (*big.Int, error) { return _Bindings.Contract.BorrowBalanceStored(&_Bindings.CallOpts, account) } func (_Bindings *BindingsCallerSession) BorrowBalanceStored(account common.Address) (*big.Int, error) { return _Bindings.Contract.BorrowBalanceStored(&_Bindings.CallOpts, account) } func (_Bindings *BindingsCaller) BorrowIndex(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "borrowIndex") return *ret0, err } func (_Bindings *BindingsSession) BorrowIndex() (*big.Int, error) { return _Bindings.Contract.BorrowIndex(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) BorrowIndex() (*big.Int, error) { return _Bindings.Contract.BorrowIndex(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) BorrowRatePerBlock(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "borrowRatePerBlock") return *ret0, err } func (_Bindings *BindingsSession) BorrowRatePerBlock() (*big.Int, error) { return _Bindings.Contract.BorrowRatePerBlock(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) BorrowRatePerBlock() (*big.Int, error) { return _Bindings.Contract.BorrowRatePerBlock(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Comptroller(opts *bind.CallOpts) (common.Address, error) { var ( ret0 = new(common.Address) ) out := ret0 err := _Bindings.contract.Call(opts, out, "comptroller") return *ret0, err } func (_Bindings *BindingsSession) Comptroller() (common.Address, error) { return _Bindings.Contract.Comptroller(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) Comptroller() (common.Address, error) { return _Bindings.Contract.Comptroller(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Decimals(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "decimals") return *ret0, err } func (_Bindings *BindingsSession) Decimals() (*big.Int, error) { return _Bindings.Contract.Decimals(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) Decimals() (*big.Int, error) { return _Bindings.Contract.Decimals(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) ExchangeRateStored(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "exchangeRateStored") return *ret0, err } func (_Bindings *BindingsSession) ExchangeRateStored() (*big.Int, error) { return _Bindings.Contract.ExchangeRateStored(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) ExchangeRateStored() (*big.Int, error) { return _Bindings.Contract.ExchangeRateStored(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) GetAccountSnapshot(opts *bind.CallOpts, account common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, error) { var ( ret0 = new(*big.Int) ret1 = new(*big.Int) ret2 = new(*big.Int) ret3 = new(*big.Int) ) out := &[]interface{}{ ret0, ret1, ret2, ret3, } err := _Bindings.contract.Call(opts, out, "getAccountSnapshot", account) return *ret0, *ret1, *ret2, *ret3, err } func (_Bindings *BindingsSession) GetAccountSnapshot(account common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, error) { return _Bindings.Contract.GetAccountSnapshot(&_Bindings.CallOpts, account) } func (_Bindings *BindingsCallerSession) GetAccountSnapshot(account common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, error) { return _Bindings.Contract.GetAccountSnapshot(&_Bindings.CallOpts, account) } func (_Bindings *BindingsCaller) GetCash(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "getCash") return *ret0, err } func (_Bindings *BindingsSession) GetCash() (*big.Int, error) { return _Bindings.Contract.GetCash(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) GetCash() (*big.Int, error) { return _Bindings.Contract.GetCash(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) InitialExchangeRateMantissa(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "initialExchangeRateMantissa") return *ret0, err } func (_Bindings *BindingsSession) InitialExchangeRateMantissa() (*big.Int, error) { return _Bindings.Contract.InitialExchangeRateMantissa(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) InitialExchangeRateMantissa() (*big.Int, error) { return _Bindings.Contract.InitialExchangeRateMantissa(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) InterestRateModel(opts *bind.CallOpts) (common.Address, error) { var ( ret0 = new(common.Address) ) out := ret0 err := _Bindings.contract.Call(opts, out, "interestRateModel") return *ret0, err } func (_Bindings *BindingsSession) InterestRateModel() (common.Address, error) { return _Bindings.Contract.InterestRateModel(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) InterestRateModel() (common.Address, error) { return _Bindings.Contract.InterestRateModel(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) IsCToken(opts *bind.CallOpts) (bool, error) { var ( ret0 = new(bool) ) out := ret0 err := _Bindings.contract.Call(opts, out, "isCToken") return *ret0, err } func (_Bindings *BindingsSession) IsCToken() (bool, error) { return _Bindings.Contract.IsCToken(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) IsCToken() (bool, error) { return _Bindings.Contract.IsCToken(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Name(opts *bind.CallOpts) (string, error) { var ( ret0 = new(string) ) out := ret0 err := _Bindings.contract.Call(opts, out, "name") return *ret0, err } func (_Bindings *BindingsSession) Name() (string, error) { return _Bindings.Contract.Name(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) Name() (string, error) { return _Bindings.Contract.Name(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) PendingAdmin(opts *bind.CallOpts) (common.Address, error) { var ( ret0 = new(common.Address) ) out := ret0 err := _Bindings.contract.Call(opts, out, "pendingAdmin") return *ret0, err } func (_Bindings *BindingsSession) PendingAdmin() (common.Address, error) { return _Bindings.Contract.PendingAdmin(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) PendingAdmin() (common.Address, error) { return _Bindings.Contract.PendingAdmin(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) ReserveFactorMantissa(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "reserveFactorMantissa") return *ret0, err } func (_Bindings *BindingsSession) ReserveFactorMantissa() (*big.Int, error) { return _Bindings.Contract.ReserveFactorMantissa(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) ReserveFactorMantissa() (*big.Int, error) { return _Bindings.Contract.ReserveFactorMantissa(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) SupplyRatePerBlock(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "supplyRatePerBlock") return *ret0, err } func (_Bindings *BindingsSession) SupplyRatePerBlock() (*big.Int, error) { return _Bindings.Contract.SupplyRatePerBlock(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) SupplyRatePerBlock() (*big.Int, error) { return _Bindings.Contract.SupplyRatePerBlock(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Symbol(opts *bind.CallOpts) (string, error) { var ( ret0 = new(string) ) out := ret0 err := _Bindings.contract.Call(opts, out, "symbol") return *ret0, err } func (_Bindings *BindingsSession) Symbol() (string, error) { return _Bindings.Contract.Symbol(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) Symbol() (string, error) { return _Bindings.Contract.Symbol(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) TotalBorrows(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "totalBorrows") return *ret0, err } func (_Bindings *BindingsSession) TotalBorrows() (*big.Int, error) { return _Bindings.Contract.TotalBorrows(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) TotalBorrows() (*big.Int, error) { return _Bindings.Contract.TotalBorrows(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "totalReserves") return *ret0, err } func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) { return _Bindings.Contract.TotalReserves(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) { return _Bindings.Contract.TotalReserves(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { var ( ret0 = new(*big.Int) ) out := ret0 err := _Bindings.contract.Call(opts, out, "totalSupply") return *ret0, err } func (_Bindings *BindingsSession) TotalSupply() (*big.Int, error) { return _Bindings.Contract.TotalSupply(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) TotalSupply() (*big.Int, error) { return _Bindings.Contract.TotalSupply(&_Bindings.CallOpts) } func (_Bindings *BindingsCaller) Underlying(opts *bind.CallOpts) (common.Address, error) { var ( ret0 = new(common.Address) ) out := ret0 err := _Bindings.contract.Call(opts, out, "underlying") return *ret0, err } func (_Bindings *BindingsSession) Underlying() (common.Address, error) { return _Bindings.Contract.Underlying(&_Bindings.CallOpts) } func (_Bindings *BindingsCallerSession) Underlying() (common.Address, error) { return _Bindings.Contract.Underlying(&_Bindings.CallOpts) } func (_Bindings *BindingsTransactor) AcceptAdmin(opts *bind.TransactOpts) (*types.Transaction, error) { return _Bindings.contract.Transact(opts, "_acceptAdmin") } func (_Bindings *BindingsSession) AcceptAdmin() (*types.Transaction, error) { return _Bindings.Contract.AcceptAdmin(&_Bindings.TransactOpts) } func (_Bindings *BindingsTransactorSession) AcceptAdmin() (*types.Transaction, error) { return _Bindings.Contract.AcceptAdmin(&_Bindings.TransactOpts) }
Apache License 2.0
leonelquinteros/gotext
domain.go
SetNC
go
func (do *Domain) SetNC(id, plural, ctx string, n int, str string) { pluralForm := do.pluralForm(n) do.trMutex.Lock() do.pluralMutex.Lock() defer do.trMutex.Unlock() defer do.pluralMutex.Unlock() if context, ok := do.contexts[ctx]; ok { if trans, hasTrans := context[id]; hasTrans { trans.SetN(pluralForm, str) } else { trans = NewTranslation() trans.ID = id trans.SetN(pluralForm, str) context[id] = trans } } else { trans := NewTranslation() trans.ID = id trans.SetN(pluralForm, str) do.contexts[ctx] = map[string]*Translation{ id: trans, } } }
Set the (N)th plural form for the given string in the given context
https://github.com/leonelquinteros/gotext/blob/5e27e8b5e0aa70081ef44c4778d8df30e1e7cc70/domain.go#L354-L380
package gotext import ( "bytes" "encoding/gob" "sort" "strconv" "strings" "sync" "golang.org/x/text/language" "github.com/leonelquinteros/gotext/plurals" ) type Domain struct { Headers HeaderMap Language string tag language.Tag PluralForms string headerComments []string nplurals int plural string pluralforms plurals.Expression translations map[string]*Translation contexts map[string]map[string]*Translation pluralTranslations map[string]*Translation trMutex sync.RWMutex pluralMutex sync.RWMutex trBuffer *Translation ctxBuffer string refBuffer string } type HeaderMap map[string][]string func (m HeaderMap) Add(key, value string) { m[key] = append(m[key], value) } func (m HeaderMap) Del(key string) { delete(m, key) } func (m HeaderMap) Get(key string) string { if m == nil { return "" } v := m[key] if len(v) == 0 { return "" } return v[0] } func (m HeaderMap) Set(key, value string) { m[key] = []string{value} } func (m HeaderMap) Values(key string) []string { if m == nil { return nil } return m[key] } func NewDomain() *Domain { domain := new(Domain) domain.Headers = make(HeaderMap) domain.headerComments = make([]string, 0) domain.translations = make(map[string]*Translation) domain.contexts = make(map[string]map[string]*Translation) domain.pluralTranslations = make(map[string]*Translation) return domain } func (do *Domain) pluralForm(n int) int { do.pluralMutex.RLock() defer do.pluralMutex.RUnlock() if do.pluralforms == nil { if n == 1 { return 0 } return 1 } return do.pluralforms.Eval(uint32(n)) } func (do *Domain) parseHeaders() { raw := "" if _, ok := do.translations[raw]; ok { raw = do.translations[raw].Get() } languageKey := "Language" pluralFormsKey := "Plural-Forms" rawLines := strings.Split(raw, "\n") for _, line := range rawLines { if len(line) == 0 { continue } colonIdx := strings.Index(line, ":") if colonIdx < 0 { continue } key := line[:colonIdx] lowerKey := strings.ToLower(key) if lowerKey == strings.ToLower(languageKey) { languageKey = key } else if lowerKey == strings.ToLower(pluralFormsKey) { pluralFormsKey = key } value := strings.TrimSpace(line[colonIdx+1:]) do.Headers.Add(key, value) } do.Language = do.Headers.Get(languageKey) do.tag = language.Make(do.Language) do.PluralForms = do.Headers.Get(pluralFormsKey) if do.PluralForms == "" { return } pfs := strings.Split(do.PluralForms, ";") for _, i := range pfs { vs := strings.SplitN(i, "=", 2) if len(vs) != 2 { continue } switch strings.TrimSpace(vs[0]) { case "nplurals": do.nplurals, _ = strconv.Atoi(vs[1]) case "plural": do.plural = vs[1] if expr, err := plurals.Compile(do.plural); err == nil { do.pluralforms = expr } } } } func (do *Domain) DropStaleTranslations() { do.trMutex.Lock() do.pluralMutex.Lock() defer do.trMutex.Unlock() defer do.pluralMutex.Unlock() for name, ctx := range do.contexts { for id, trans := range ctx { if trans.IsStale() { delete(ctx, id) } } if len(ctx) == 0 { delete(do.contexts, name) } } for id, trans := range do.translations { if trans.IsStale() { delete(do.translations, id) } } } func (do *Domain) SetRefs(str string, refs []string) { do.trMutex.Lock() do.pluralMutex.Lock() defer do.trMutex.Unlock() defer do.pluralMutex.Unlock() if trans, ok := do.translations[str]; ok { trans.Refs = refs } else { trans = NewTranslation() trans.ID = str trans.SetRefs(refs) do.translations[str] = trans } } func (do *Domain) GetRefs(str string) []string { do.trMutex.RLock() defer do.trMutex.RUnlock() if do.translations != nil { if trans, ok := do.translations[str]; ok { return trans.Refs } } return nil } func (do *Domain) Set(id, str string) { do.trMutex.Lock() do.pluralMutex.Lock() defer do.trMutex.Unlock() defer do.pluralMutex.Unlock() if trans, ok := do.translations[id]; ok { trans.Set(str) } else { trans = NewTranslation() trans.ID = id trans.Set(str) do.translations[str] = trans } } func (do *Domain) Get(str string, vars ...interface{}) string { do.trMutex.RLock() defer do.trMutex.RUnlock() if do.translations != nil { if _, ok := do.translations[str]; ok { return Printf(do.translations[str].Get(), vars...) } } return Printf(str, vars...) } func (do *Domain) SetN(id, plural string, n int, str string) { pluralForm := do.pluralForm(n) do.trMutex.Lock() do.pluralMutex.Lock() defer do.trMutex.Unlock() defer do.pluralMutex.Unlock() if trans, ok := do.translations[id]; ok { trans.SetN(pluralForm, str) } else { trans = NewTranslation() trans.ID = id trans.PluralID = plural trans.SetN(pluralForm, str) do.translations[str] = trans } } func (do *Domain) GetN(str, plural string, n int, vars ...interface{}) string { do.trMutex.RLock() defer do.trMutex.RUnlock() if do.translations != nil { if _, ok := do.translations[str]; ok { return Printf(do.translations[str].GetN(do.pluralForm(n)), vars...) } } if do.pluralForm(n) == 0 { return Printf(str, vars...) } return Printf(plural, vars...) } func (do *Domain) SetC(id, ctx, str string) { do.trMutex.Lock() do.pluralMutex.Lock() defer do.trMutex.Unlock() defer do.pluralMutex.Unlock() if context, ok := do.contexts[ctx]; ok { if trans, hasTrans := context[id]; hasTrans { trans.Set(str) } else { trans = NewTranslation() trans.ID = id trans.Set(str) context[id] = trans } } else { trans := NewTranslation() trans.ID = id trans.Set(str) do.contexts[ctx] = map[string]*Translation{ id: trans, } } } func (do *Domain) GetC(str, ctx string, vars ...interface{}) string { do.trMutex.RLock() defer do.trMutex.RUnlock() if do.contexts != nil { if _, ok := do.contexts[ctx]; ok { if do.contexts[ctx] != nil { if _, ok := do.contexts[ctx][str]; ok { return Printf(do.contexts[ctx][str].Get(), vars...) } } } } return Printf(str, vars...) }
MIT License
vito/booklit
errors.go
PrettyPrint
go
func (err TitleTwiceError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) fmt.Fprintf(out, "The section's title was first set here:\n\n") err.TitleLocation.AnnotateLocation(out) fmt.Fprintln(out, "Maybe the second \\title should be in a \\section{...}?") }
PrettyPrint prints the error message and a snippet of the source code where the error occurred. If the error returned by the function is a PrettyError, PrettyPrint is called and its output is indented. Otherwise, the error is printed normally.
https://github.com/vito/booklit/blob/f2f26aa3ef5ab94603abee238d7f262f5eb6bd66/errors.go#L295-L304
package booklit import ( "bufio" "bytes" "fmt" "html/template" "io" "net/http" "os" "path/filepath" "strings" "github.com/segmentio/textio" "github.com/vito/booklit/ast" "github.com/vito/booklit/errhtml" ) var errorTmpl *template.Template func init() { errorTmpl = template.New("errors").Funcs(template.FuncMap{ "error": func(err error) (template.HTML, error) { buf := new(bytes.Buffer) if prettyErr, ok := err.(PrettyError); ok { renderErr := prettyErr.PrettyHTML(buf) if renderErr != nil { return "", renderErr } return template.HTML(buf.String()), nil } return template.HTML( `<pre class="raw-error">` + template.HTMLEscapeString(err.Error()) + `</pre>`, ), nil }, "annotate": func(loc ErrorLocation) (template.HTML, error) { buf := new(bytes.Buffer) err := loc.AnnotatedHTML(buf) if err != nil { return "", err } return template.HTML(buf.String()), nil }, }) for _, asset := range errhtml.AssetNames() { info, err := errhtml.AssetInfo(asset) if err != nil { panic(err) } content := strings.TrimRight(string(errhtml.MustAsset(asset)), "\n") _, err = errorTmpl.New(filepath.Base(info.Name())).Parse(content) if err != nil { panic(err) } } } func ErrorResponse(w http.ResponseWriter, err error) { renderErr := errorTmpl.Lookup("page.tmpl").Execute(w, err) if renderErr != nil { fmt.Fprintf(w, "failed to render error page: %s", renderErr) } } type PrettyError interface { error PrettyPrint(io.Writer) PrettyHTML(io.Writer) error } type ParseError struct { Err error ErrorLocation } func (err ParseError) Error() string { return fmt.Sprintf("parse error: %s", err.Err) } func (err ParseError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) } func (err ParseError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("parse-error.tmpl").Execute(out, err) } type UnknownTagError struct { TagName string SimilarTags []Tag ErrorLocation } func (err UnknownTagError) Error() string { return fmt.Sprintf("unknown tag '%s'", err.TagName) } func (err UnknownTagError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) if len(err.SimilarTags) == 0 { fmt.Fprintf(out, "I couldn't find any similar tags. :(\n") } else { fmt.Fprintf(out, "These tags seem similar:\n\n") for _, tag := range err.SimilarTags { fmt.Fprintf(out, "- %s\n", tag.Name) } fmt.Fprintf(out, "\nDid you mean one of these?\n") } } func (err UnknownTagError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("unknown-tag.tmpl").Execute(out, err) } type AmbiguousReferenceError struct { TagName string DefinedLocations []ErrorLocation ErrorLocation } func (err AmbiguousReferenceError) Error() string { return fmt.Sprintf( "ambiguous target for tag '%s'", err.TagName, ) } func (err AmbiguousReferenceError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) fmt.Fprintf(out, "The same tag was defined in the following locations:\n\n") for _, loc := range err.DefinedLocations { fmt.Fprintf(out, "- %s:\n", loc.FilePath) loc.AnnotateLocation(textio.NewPrefixWriter(out, " ")) } fmt.Fprintf(out, "Tags must be unique so I know where to link to!\n") } func (err AmbiguousReferenceError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("ambiguous-reference.tmpl").Execute(out, err) } type UndefinedFunctionError struct { Function string ErrorLocation } func (err UndefinedFunctionError) Error() string { return fmt.Sprintf( "undefined function \\%s", err.Function, ) } func (err UndefinedFunctionError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("%s", err)) fmt.Fprintln(out) err.AnnotateLocation(out) } func (err UndefinedFunctionError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("undefined-function.tmpl").Execute(out, err) } type FailedFunctionError struct { Function string Err error ErrorLocation } func (err FailedFunctionError) Error() string { return fmt.Sprintf( "function \\%s returned an error: %s", err.Function, err.Err, ) } func (err FailedFunctionError) PrettyPrint(out io.Writer) { fmt.Fprintln(out, err.Annotate("function \\%s returned an error", err.Function)) fmt.Fprintln(out) err.AnnotateLocation(out) if prettyErr, ok := err.Err.(PrettyError); ok { prettyErr.PrettyPrint(textio.NewPrefixWriter(out, " ")) } else { fmt.Fprintf(out, "\x1b[33m%s\x1b[0m\n", err.Err) } } func (err FailedFunctionError) PrettyHTML(out io.Writer) error { return errorTmpl.Lookup("function-error.tmpl").Execute(out, err) } type TitleTwiceError struct { TitleLocation ErrorLocation ErrorLocation } func (err TitleTwiceError) Error() string { return "cannot set title twice" }
MIT License
luksa/statefulset-scaledown-controller
vendor/k8s.io/client-go/kubernetes/typed/core/v1/fake/fake_namespace.go
Patch
go
func (c *FakeNamespaces) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *core_v1.Namespace, err error) { obj, err := c.Fake. Invokes(testing.NewRootPatchSubresourceAction(namespacesResource, name, data, subresources...), &core_v1.Namespace{}) if obj == nil { return nil, err } return obj.(*core_v1.Namespace), err }
Patch applies the patch and returns the patched namespace.
https://github.com/luksa/statefulset-scaledown-controller/blob/22d2e550e4c8272bab437fa0532394c4fb14fbd7/vendor/k8s.io/client-go/kubernetes/typed/core/v1/fake/fake_namespace.go#L124-L131
package fake import ( core_v1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" ) type FakeNamespaces struct { Fake *FakeCoreV1 } var namespacesResource = schema.GroupVersionResource{Group: "", Version: "v1", Resource: "namespaces"} var namespacesKind = schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Namespace"} func (c *FakeNamespaces) Get(name string, options v1.GetOptions) (result *core_v1.Namespace, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(namespacesResource, name), &core_v1.Namespace{}) if obj == nil { return nil, err } return obj.(*core_v1.Namespace), err } func (c *FakeNamespaces) List(opts v1.ListOptions) (result *core_v1.NamespaceList, err error) { obj, err := c.Fake. Invokes(testing.NewRootListAction(namespacesResource, namespacesKind, opts), &core_v1.NamespaceList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &core_v1.NamespaceList{} for _, item := range obj.(*core_v1.NamespaceList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } func (c *FakeNamespaces) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewRootWatchAction(namespacesResource, opts)) } func (c *FakeNamespaces) Create(namespace *core_v1.Namespace) (result *core_v1.Namespace, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateAction(namespacesResource, namespace), &core_v1.Namespace{}) if obj == nil { return nil, err } return obj.(*core_v1.Namespace), err } func (c *FakeNamespaces) Update(namespace *core_v1.Namespace) (result *core_v1.Namespace, err error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateAction(namespacesResource, namespace), &core_v1.Namespace{}) if obj == nil { return nil, err } return obj.(*core_v1.Namespace), err } func (c *FakeNamespaces) UpdateStatus(namespace *core_v1.Namespace) (*core_v1.Namespace, error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateSubresourceAction(namespacesResource, "status", namespace), &core_v1.Namespace{}) if obj == nil { return nil, err } return obj.(*core_v1.Namespace), err } func (c *FakeNamespaces) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewRootDeleteAction(namespacesResource, name), &core_v1.Namespace{}) return err } func (c *FakeNamespaces) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewRootDeleteCollectionAction(namespacesResource, listOptions) _, err := c.Fake.Invokes(action, &core_v1.NamespaceList{}) return err }
Apache License 2.0
yakumioto/alkaid
third_party/github.com/hyperledger/fabric/protoutil/proputils.go
GetActionFromEnvelope
go
func GetActionFromEnvelope(envBytes []byte) (*peer.ChaincodeAction, error) { env, err := GetEnvelopeFromBlock(envBytes) if err != nil { return nil, err } return GetActionFromEnvelopeMsg(env) }
GetActionFromEnvelope extracts a ChaincodeAction message from a serialized Envelope TODO: fix function name as per FAB-11831
https://github.com/yakumioto/alkaid/blob/6fe960aff55c3acf5a2541b61fff07d6ce0342dc/third_party/github.com/hyperledger/fabric/protoutil/proputils.go#L204-L210
package protoutil import ( "crypto/sha256" "encoding/hex" "time" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes" "github.com/hyperledger/fabric-protos-go/common" "github.com/hyperledger/fabric-protos-go/peer" "github.com/pkg/errors" ) func CreateChaincodeProposal(typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) { return CreateChaincodeProposalWithTransient(typ, channelID, cis, creator, nil) } func CreateChaincodeProposalWithTransient(typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) { nonce, err := getRandomNonce() if err != nil { return nil, "", err } txid := ComputeTxID(nonce, creator) return CreateChaincodeProposalWithTxIDNonceAndTransient(txid, typ, channelID, cis, nonce, creator, transientMap) } func CreateChaincodeProposalWithTxIDAndTransient(typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, creator []byte, txid string, transientMap map[string][]byte) (*peer.Proposal, string, error) { nonce, err := getRandomNonce() if err != nil { return nil, "", err } if txid == "" { txid = ComputeTxID(nonce, creator) } return CreateChaincodeProposalWithTxIDNonceAndTransient(txid, typ, channelID, cis, nonce, creator, transientMap) } func CreateChaincodeProposalWithTxIDNonceAndTransient(txid string, typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, nonce, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) { ccHdrExt := &peer.ChaincodeHeaderExtension{ChaincodeId: cis.ChaincodeSpec.ChaincodeId} ccHdrExtBytes, err := proto.Marshal(ccHdrExt) if err != nil { return nil, "", errors.Wrap(err, "error marshaling ChaincodeHeaderExtension") } cisBytes, err := proto.Marshal(cis) if err != nil { return nil, "", errors.Wrap(err, "error marshaling ChaincodeInvocationSpec") } ccPropPayload := &peer.ChaincodeProposalPayload{Input: cisBytes, TransientMap: transientMap} ccPropPayloadBytes, err := proto.Marshal(ccPropPayload) if err != nil { return nil, "", errors.Wrap(err, "error marshaling ChaincodeProposalPayload") } var epoch uint64 timestamp, err := ptypes.TimestampProto(time.Now().UTC()) if err != nil { return nil, "", errors.Wrap(err, "error validating Timestamp") } hdr := &common.Header{ ChannelHeader: MarshalOrPanic( &common.ChannelHeader{ Type: int32(typ), TxId: txid, Timestamp: timestamp, ChannelId: channelID, Extension: ccHdrExtBytes, Epoch: epoch, }, ), SignatureHeader: MarshalOrPanic( &common.SignatureHeader{ Nonce: nonce, Creator: creator, }, ), } hdrBytes, err := proto.Marshal(hdr) if err != nil { return nil, "", err } prop := &peer.Proposal{ Header: hdrBytes, Payload: ccPropPayloadBytes, } return prop, txid, nil } func GetBytesProposalResponsePayload(hash []byte, response *peer.Response, result []byte, event []byte, ccid *peer.ChaincodeID) ([]byte, error) { cAct := &peer.ChaincodeAction{ Events: event, Results: result, Response: response, ChaincodeId: ccid, } cActBytes, err := proto.Marshal(cAct) if err != nil { return nil, errors.Wrap(err, "error marshaling ChaincodeAction") } prp := &peer.ProposalResponsePayload{ Extension: cActBytes, ProposalHash: hash, } prpBytes, err := proto.Marshal(prp) return prpBytes, errors.Wrap(err, "error marshaling ProposalResponsePayload") } func GetBytesChaincodeProposalPayload(cpp *peer.ChaincodeProposalPayload) ([]byte, error) { cppBytes, err := proto.Marshal(cpp) return cppBytes, errors.Wrap(err, "error marshaling ChaincodeProposalPayload") } func GetBytesResponse(res *peer.Response) ([]byte, error) { resBytes, err := proto.Marshal(res) return resBytes, errors.Wrap(err, "error marshaling Response") } func GetBytesChaincodeEvent(event *peer.ChaincodeEvent) ([]byte, error) { eventBytes, err := proto.Marshal(event) return eventBytes, errors.Wrap(err, "error marshaling ChaincodeEvent") } func GetBytesChaincodeActionPayload(cap *peer.ChaincodeActionPayload) ([]byte, error) { capBytes, err := proto.Marshal(cap) return capBytes, errors.Wrap(err, "error marshaling ChaincodeActionPayload") } func GetBytesProposalResponse(pr *peer.ProposalResponse) ([]byte, error) { respBytes, err := proto.Marshal(pr) return respBytes, errors.Wrap(err, "error marshaling ProposalResponse") } func GetBytesHeader(hdr *common.Header) ([]byte, error) { bytes, err := proto.Marshal(hdr) return bytes, errors.Wrap(err, "error marshaling Header") } func GetBytesSignatureHeader(hdr *common.SignatureHeader) ([]byte, error) { bytes, err := proto.Marshal(hdr) return bytes, errors.Wrap(err, "error marshaling SignatureHeader") } func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) { bytes, err := proto.Marshal(tx) return bytes, errors.Wrap(err, "error unmarshaling Transaction") } func GetBytesPayload(payl *common.Payload) ([]byte, error) { bytes, err := proto.Marshal(payl) return bytes, errors.Wrap(err, "error marshaling Payload") } func GetBytesEnvelope(env *common.Envelope) ([]byte, error) { bytes, err := proto.Marshal(env) return bytes, errors.Wrap(err, "error marshaling Envelope") }
MIT License
e-xpertsolutions/go-cluster
vendor/gonum.org/v1/gonum/blas/gonum/gonum.go
blocks
go
func blocks(dim, bsize int) int { return (dim + bsize - 1) / bsize }
blocks returns the number of divisions of the dimension length with the given block size.
https://github.com/e-xpertsolutions/go-cluster/blob/e7d603cda15011510443752447981d0420e45102/vendor/gonum.org/v1/gonum/blas/gonum/gonum.go#L126-L128
package gonum import "math" type Implementation struct{} const ( negativeN = "blas: n < 0" zeroIncX = "blas: zero x index increment" zeroIncY = "blas: zero y index increment" badLenX = "blas: x index out of range" badLenY = "blas: y index out of range" mLT0 = "blas: m < 0" nLT0 = "blas: n < 0" kLT0 = "blas: k < 0" kLLT0 = "blas: kL < 0" kULT0 = "blas: kU < 0" badUplo = "blas: illegal triangle" badTranspose = "blas: illegal transpose" badDiag = "blas: illegal diagonal" badSide = "blas: illegal side" badLdA = "blas: index of a out of range" badLdB = "blas: index of b out of range" badLdC = "blas: index of c out of range" badX = "blas: x index out of range" badY = "blas: y index out of range" ) const ( blockSize = 64 minParBlock = 4 buffMul = 4 ) type subMul struct { i, j int } func max(a, b int) int { if a > b { return a } return b } func min(a, b int) int { if a > b { return b } return a } func checkSMatrix(name byte, m, n int, a []float32, lda int) { if m < 0 { panic(mLT0) } if n < 0 { panic(nLT0) } if lda < n { panic("blas: illegal stride of " + string(name)) } if len(a) < (m-1)*lda+n { panic("blas: index of " + string(name) + " out of range") } } func checkDMatrix(name byte, m, n int, a []float64, lda int) { if m < 0 { panic(mLT0) } if n < 0 { panic(nLT0) } if lda < n { panic("blas: illegal stride of " + string(name)) } if len(a) < (m-1)*lda+n { panic("blas: index of " + string(name) + " out of range") } } func checkZMatrix(name byte, m, n int, a []complex128, lda int) { if m < 0 { panic(mLT0) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic("blas: illegal stride of " + string(name)) } if len(a) < (m-1)*lda+n { panic("blas: insufficient " + string(name) + " matrix slice length") } } func checkZVector(name byte, n int, x []complex128, incX int) { if n < 0 { panic(nLT0) } if incX == 0 { panic(zeroIncX) } if (incX > 0 && (n-1)*incX >= len(x)) || (incX < 0 && (1-n)*incX >= len(x)) { panic("blas: insufficient " + string(name) + " vector slice length") } }
BSD 3-Clause New or Revised License
leonzyang/agent
vendor/google.golang.org/grpc/server.go
handleRawConn
go
func (s *Server) handleRawConn(rawConn net.Conn) { if s.quit.HasFired() { rawConn.Close() return } rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) conn, authInfo, err := s.useTransportAuthenticator(rawConn) if err != nil { if err != credentials.ErrConnDispatched { s.mu.Lock() s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) s.mu.Unlock() channelz.Warningf(s.channelzID, "grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) rawConn.Close() } rawConn.SetDeadline(time.Time{}) return } st := s.newHTTP2Transport(conn, authInfo) if st == nil { return } rawConn.SetDeadline(time.Time{}) if !s.addConn(st) { return } go func() { s.serveStreams(st) s.removeConn(st) }() }
handleRawConn forks a goroutine to handle a just-accepted connection that has not had any I/O performed on it yet.
https://github.com/leonzyang/agent/blob/9e2cc1db1e699409f7c38e3d7228858b8f532b49/vendor/google.golang.org/grpc/server.go#L671-L706
package grpc import ( "context" "errors" "fmt" "io" "math" "net" "net/http" "reflect" "runtime" "strings" "sync" "sync/atomic" "time" "golang.org/x/net/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding" "google.golang.org/grpc/encoding/proto" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) const ( defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4 defaultServerMaxSendMessageSize = math.MaxInt32 ) var statusOK = status.New(codes.OK, "") type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error) type MethodDesc struct { MethodName string Handler methodHandler } type ServiceDesc struct { ServiceName string HandlerType interface{} Methods []MethodDesc Streams []StreamDesc Metadata interface{} } type service struct { server interface{} md map[string]*MethodDesc sd map[string]*StreamDesc mdata interface{} } type Server struct { opts serverOptions mu sync.Mutex lis map[net.Listener]bool conns map[transport.ServerTransport]bool serve bool drain bool cv *sync.Cond m map[string]*service events trace.EventLog quit *grpcsync.Event done *grpcsync.Event channelzRemoveOnce sync.Once serveWG sync.WaitGroup channelzID int64 czData *channelzData } type serverOptions struct { creds credentials.TransportCredentials codec baseCodec cp Compressor dc Decompressor unaryInt UnaryServerInterceptor streamInt StreamServerInterceptor chainUnaryInts []UnaryServerInterceptor chainStreamInts []StreamServerInterceptor inTapHandle tap.ServerInHandle statsHandler stats.Handler maxConcurrentStreams uint32 maxReceiveMessageSize int maxSendMessageSize int unknownStreamDesc *StreamDesc keepaliveParams keepalive.ServerParameters keepalivePolicy keepalive.EnforcementPolicy initialWindowSize int32 initialConnWindowSize int32 writeBufferSize int readBufferSize int connectionTimeout time.Duration maxHeaderListSize *uint32 headerTableSize *uint32 } var defaultServerOptions = serverOptions{ maxReceiveMessageSize: defaultServerMaxReceiveMessageSize, maxSendMessageSize: defaultServerMaxSendMessageSize, connectionTimeout: 120 * time.Second, writeBufferSize: defaultWriteBufSize, readBufferSize: defaultReadBufSize, } type ServerOption interface { apply(*serverOptions) } type EmptyServerOption struct{} func (EmptyServerOption) apply(*serverOptions) {} type funcServerOption struct { f func(*serverOptions) } func (fdo *funcServerOption) apply(do *serverOptions) { fdo.f(do) } func newFuncServerOption(f func(*serverOptions)) *funcServerOption { return &funcServerOption{ f: f, } } func WriteBufferSize(s int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.writeBufferSize = s }) } func ReadBufferSize(s int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.readBufferSize = s }) } func InitialWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialWindowSize = s }) } func InitialConnWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialConnWindowSize = s }) } func KeepaliveParams(kp keepalive.ServerParameters) ServerOption { if kp.Time > 0 && kp.Time < time.Second { grpclog.Warning("Adjusting keepalive ping interval to minimum period of 1s") kp.Time = time.Second } return newFuncServerOption(func(o *serverOptions) { o.keepaliveParams = kp }) } func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.keepalivePolicy = kep }) } func CustomCodec(codec Codec) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.codec = codec }) } func RPCCompressor(cp Compressor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.cp = cp }) } func RPCDecompressor(dc Decompressor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.dc = dc }) } func MaxMsgSize(m int) ServerOption { return MaxRecvMsgSize(m) } func MaxRecvMsgSize(m int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.maxReceiveMessageSize = m }) } func MaxSendMsgSize(m int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.maxSendMessageSize = m }) } func MaxConcurrentStreams(n uint32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.maxConcurrentStreams = n }) } func Creds(c credentials.TransportCredentials) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.creds = c }) } func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { if o.unaryInt != nil { panic("The unary server interceptor was already set and may not be reset.") } o.unaryInt = i }) } func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.chainUnaryInts = append(o.chainUnaryInts, interceptors...) }) } func StreamInterceptor(i StreamServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { if o.streamInt != nil { panic("The stream server interceptor was already set and may not be reset.") } o.streamInt = i }) } func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.chainStreamInts = append(o.chainStreamInts, interceptors...) }) } func InTapHandle(h tap.ServerInHandle) ServerOption { return newFuncServerOption(func(o *serverOptions) { if o.inTapHandle != nil { panic("The tap handle was already set and may not be reset.") } o.inTapHandle = h }) } func StatsHandler(h stats.Handler) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.statsHandler = h }) } func UnknownServiceHandler(streamHandler StreamHandler) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.unknownStreamDesc = &StreamDesc{ StreamName: "unknown_service_handler", Handler: streamHandler, ClientStreams: true, ServerStreams: true, } }) } func ConnectionTimeout(d time.Duration) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.connectionTimeout = d }) } func MaxHeaderListSize(s uint32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.maxHeaderListSize = &s }) } func HeaderTableSize(s uint32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.headerTableSize = &s }) } func NewServer(opt ...ServerOption) *Server { opts := defaultServerOptions for _, o := range opt { o.apply(&opts) } s := &Server{ lis: make(map[net.Listener]bool), opts: opts, conns: make(map[transport.ServerTransport]bool), m: make(map[string]*service), quit: grpcsync.NewEvent(), done: grpcsync.NewEvent(), czData: new(channelzData), } chainUnaryServerInterceptors(s) chainStreamServerInterceptors(s) s.cv = sync.NewCond(&s.mu) if EnableTracing { _, file, line, _ := runtime.Caller(1) s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line)) } if channelz.IsOn() { s.channelzID = channelz.RegisterServer(&channelzServer{s}, "") } return s } func (s *Server) printf(format string, a ...interface{}) { if s.events != nil { s.events.Printf(format, a...) } } func (s *Server) errorf(format string, a ...interface{}) { if s.events != nil { s.events.Errorf(format, a...) } } func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) { ht := reflect.TypeOf(sd.HandlerType).Elem() st := reflect.TypeOf(ss) if !st.Implements(ht) { grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht) } s.register(sd, ss) } func (s *Server) register(sd *ServiceDesc, ss interface{}) { s.mu.Lock() defer s.mu.Unlock() s.printf("RegisterService(%q)", sd.ServiceName) if s.serve { grpclog.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName) } if _, ok := s.m[sd.ServiceName]; ok { grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName) } srv := &service{ server: ss, md: make(map[string]*MethodDesc), sd: make(map[string]*StreamDesc), mdata: sd.Metadata, } for i := range sd.Methods { d := &sd.Methods[i] srv.md[d.MethodName] = d } for i := range sd.Streams { d := &sd.Streams[i] srv.sd[d.StreamName] = d } s.m[sd.ServiceName] = srv } type MethodInfo struct { Name string IsClientStream bool IsServerStream bool } type ServiceInfo struct { Methods []MethodInfo Metadata interface{} } func (s *Server) GetServiceInfo() map[string]ServiceInfo { ret := make(map[string]ServiceInfo) for n, srv := range s.m { methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd)) for m := range srv.md { methods = append(methods, MethodInfo{ Name: m, IsClientStream: false, IsServerStream: false, }) } for m, d := range srv.sd { methods = append(methods, MethodInfo{ Name: m, IsClientStream: d.ClientStreams, IsServerStream: d.ServerStreams, }) } ret[n] = ServiceInfo{ Methods: methods, Metadata: srv.mdata, } } return ret } var ErrServerStopped = errors.New("grpc: the server has been stopped") func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { if s.opts.creds == nil { return rawConn, nil, nil } return s.opts.creds.ServerHandshake(rawConn) } type listenSocket struct { net.Listener channelzID int64 } func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { return &channelz.SocketInternalMetric{ SocketOptions: channelz.GetSocketOption(l.Listener), LocalAddr: l.Listener.Addr(), } } func (l *listenSocket) Close() error { err := l.Listener.Close() if channelz.IsOn() { channelz.RemoveEntry(l.channelzID) } return err } func (s *Server) Serve(lis net.Listener) error { s.mu.Lock() s.printf("serving") s.serve = true if s.lis == nil { s.mu.Unlock() lis.Close() return ErrServerStopped } s.serveWG.Add(1) defer func() { s.serveWG.Done() if s.quit.HasFired() { <-s.done.Done() } }() ls := &listenSocket{Listener: lis} s.lis[ls] = true if channelz.IsOn() { ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String()) } s.mu.Unlock() defer func() { s.mu.Lock() if s.lis != nil && s.lis[ls] { ls.Close() delete(s.lis, ls) } s.mu.Unlock() }() var tempDelay time.Duration for { rawConn, err := lis.Accept() if err != nil { if ne, ok := err.(interface { Temporary() bool }); ok && ne.Temporary() { if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if max := 1 * time.Second; tempDelay > max { tempDelay = max } s.mu.Lock() s.printf("Accept error: %v; retrying in %v", err, tempDelay) s.mu.Unlock() timer := time.NewTimer(tempDelay) select { case <-timer.C: case <-s.quit.Done(): timer.Stop() return nil } continue } s.mu.Lock() s.printf("done serving; Accept = %v", err) s.mu.Unlock() if s.quit.HasFired() { return nil } return err } tempDelay = 0 s.serveWG.Add(1) go func() { s.handleRawConn(rawConn) s.serveWG.Done() }() } }
Apache License 2.0
apache/dubbo-go
protocol/rpc_status.go
GetBlackListInvokers
go
func GetBlackListInvokers(blockSize int) []Invoker { resultIvks := make([]Invoker, 0, 16) invokerBlackList.Range(func(k, v interface{}) bool { resultIvks = append(resultIvks, v.(Invoker)) return true }) if blockSize > len(resultIvks) { return resultIvks } return resultIvks[:blockSize] }
GetBlackListInvokers get at most size of blockSize invokers from black list
https://github.com/apache/dubbo-go/blob/bfca099a8346be25ecf44f535a035f7a1fabd225/protocol/rpc_status.go#L225-L235
package protocol import ( "sync" "sync/atomic" "time" ) import ( uberAtomic "go.uber.org/atomic" ) import ( "dubbo.apache.org/dubbo-go/v3/common" "dubbo.apache.org/dubbo-go/v3/common/constant" "dubbo.apache.org/dubbo-go/v3/common/logger" ) var ( methodStatistics sync.Map serviceStatistic sync.Map invokerBlackList sync.Map blackListCacheDirty uberAtomic.Bool blackListRefreshing int32 ) func init() { blackListCacheDirty.Store(false) } type RPCStatus struct { active int32 failed int32 total int32 totalElapsed int64 failedElapsed int64 maxElapsed int64 failedMaxElapsed int64 succeededMaxElapsed int64 successiveRequestFailureCount int32 lastRequestFailedTimestamp int64 } func (rpc *RPCStatus) GetActive() int32 { return atomic.LoadInt32(&rpc.active) } func (rpc *RPCStatus) GetFailed() int32 { return atomic.LoadInt32(&rpc.failed) } func (rpc *RPCStatus) GetTotal() int32 { return atomic.LoadInt32(&rpc.total) } func (rpc *RPCStatus) GetTotalElapsed() int64 { return atomic.LoadInt64(&rpc.totalElapsed) } func (rpc *RPCStatus) GetFailedElapsed() int64 { return atomic.LoadInt64(&rpc.failedElapsed) } func (rpc *RPCStatus) GetMaxElapsed() int64 { return atomic.LoadInt64(&rpc.maxElapsed) } func (rpc *RPCStatus) GetFailedMaxElapsed() int64 { return atomic.LoadInt64(&rpc.failedMaxElapsed) } func (rpc *RPCStatus) GetSucceededMaxElapsed() int64 { return atomic.LoadInt64(&rpc.succeededMaxElapsed) } func (rpc *RPCStatus) GetLastRequestFailedTimestamp() int64 { return atomic.LoadInt64(&rpc.lastRequestFailedTimestamp) } func (rpc *RPCStatus) GetSuccessiveRequestFailureCount() int32 { return atomic.LoadInt32(&rpc.successiveRequestFailureCount) } func GetURLStatus(url *common.URL) *RPCStatus { rpcStatus, found := serviceStatistic.Load(url.Key()) if !found { rpcStatus, _ = serviceStatistic.LoadOrStore(url.Key(), &RPCStatus{}) } return rpcStatus.(*RPCStatus) } func GetMethodStatus(url *common.URL, methodName string) *RPCStatus { identifier := url.Key() methodMap, found := methodStatistics.Load(identifier) if !found { methodMap, _ = methodStatistics.LoadOrStore(identifier, &sync.Map{}) } methodActive := methodMap.(*sync.Map) rpcStatus, found := methodActive.Load(methodName) if !found { rpcStatus, _ = methodActive.LoadOrStore(methodName, &RPCStatus{}) } status := rpcStatus.(*RPCStatus) return status } func BeginCount(url *common.URL, methodName string) { beginCount0(GetURLStatus(url)) beginCount0(GetMethodStatus(url, methodName)) } func EndCount(url *common.URL, methodName string, elapsed int64, succeeded bool) { endCount0(GetURLStatus(url), elapsed, succeeded) endCount0(GetMethodStatus(url, methodName), elapsed, succeeded) } func beginCount0(rpcStatus *RPCStatus) { atomic.AddInt32(&rpcStatus.active, 1) } func endCount0(rpcStatus *RPCStatus, elapsed int64, succeeded bool) { atomic.AddInt32(&rpcStatus.active, -1) atomic.AddInt32(&rpcStatus.total, 1) atomic.AddInt64(&rpcStatus.totalElapsed, elapsed) if rpcStatus.maxElapsed < elapsed { atomic.StoreInt64(&rpcStatus.maxElapsed, elapsed) } if succeeded { if rpcStatus.succeededMaxElapsed < elapsed { atomic.StoreInt64(&rpcStatus.succeededMaxElapsed, elapsed) } atomic.StoreInt32(&rpcStatus.successiveRequestFailureCount, 0) } else { atomic.StoreInt64(&rpcStatus.lastRequestFailedTimestamp, CurrentTimeMillis()) atomic.AddInt32(&rpcStatus.successiveRequestFailureCount, 1) atomic.AddInt32(&rpcStatus.failed, 1) atomic.AddInt64(&rpcStatus.failedElapsed, elapsed) if rpcStatus.failedMaxElapsed < elapsed { atomic.StoreInt64(&rpcStatus.failedMaxElapsed, elapsed) } } } func CurrentTimeMillis() int64 { return time.Now().UnixNano() / int64(time.Millisecond) } func CleanAllStatus() { delete1 := func(key, _ interface{}) bool { methodStatistics.Delete(key) return true } methodStatistics.Range(delete1) delete2 := func(key, _ interface{}) bool { serviceStatistic.Delete(key) return true } serviceStatistic.Range(delete2) delete3 := func(key, _ interface{}) bool { invokerBlackList.Delete(key) return true } invokerBlackList.Range(delete3) } func GetInvokerHealthyStatus(invoker Invoker) bool { _, found := invokerBlackList.Load(invoker.GetURL().Key()) return !found } func SetInvokerUnhealthyStatus(invoker Invoker) { invokerBlackList.Store(invoker.GetURL().Key(), invoker) logger.Info("Add invoker ip = ", invoker.GetURL().Location, " to black list") blackListCacheDirty.Store(true) } func RemoveInvokerUnhealthyStatus(invoker Invoker) { invokerBlackList.Delete(invoker.GetURL().Key()) logger.Info("Remove invoker ip = ", invoker.GetURL().Location, " from black list") blackListCacheDirty.Store(true) }
Apache License 2.0
edgegallery/mecm-apprulemgr
controllers/rulemgr.go
CreateAppRuleConfig
go
func (c *AppRuleController) CreateAppRuleConfig() { log.Info("Application Rule Config create request received.") c.HandleAppRuleConfig(util.Post) }
CreateAppRuleConfig Configures app rule
https://github.com/edgegallery/mecm-apprulemgr/blob/a4d14f478df413803ee4648fdae3c917048f0903/controllers/rulemgr.go#L54-L57
package controllers import ( "encoding/json" "errors" "github.com/astaxie/beego" log "github.com/sirupsen/logrus" "mecm-apprulemgr/models" "mecm-apprulemgr/util" "net/http" "strings" "unsafe" ) const ( appdRule = "appd_rule_rec" appdRuleId = "appd_rule_id" failedToMarshal = "failed to marshal request" lastInsertIdNotSupported = "LastInsertId is not supported by this driver" toDatabase = "to database." operation = "] Operation [" resource = " Resource [" applicationJson = "application/json" ) type AppRuleController struct { beego.Controller Db Database } func (c *AppRuleController) HealthCheck() { _, _ = c.Ctx.ResponseWriter.Write([]byte("ok")) }
Apache License 2.0
nuclio/nuclio
pkg/processor/cloudevent/mockevent.go
GetHeaderByteSlice
go
func (me *mockEvent) GetHeaderByteSlice(key string) []byte { args := me.Called(key) return args.Get(0).([]byte) }
GetHeaderByteSlice returns the header by name as a byte slice
https://github.com/nuclio/nuclio/blob/1103106864b77aec023ce868db8774c43b297eb2/pkg/processor/cloudevent/mockevent.go#L78-L81
package cloudevent import ( "time" "github.com/nuclio/nuclio-sdk-go" "github.com/stretchr/testify/mock" ) type mockEvent struct { mock.Mock triggerInfoProvider nuclio.TriggerInfoProvider } func (me *mockEvent) GetID() nuclio.ID { args := me.Called() return args.Get(0).(nuclio.ID) } func (me *mockEvent) SetID(id nuclio.ID) { me.Called() } func (me *mockEvent) SetTriggerInfoProvider(triggerInfoProvider nuclio.TriggerInfoProvider) { me.Called(triggerInfoProvider) me.triggerInfoProvider = triggerInfoProvider } func (me *mockEvent) GetTriggerInfo() nuclio.TriggerInfoProvider { return me.triggerInfoProvider } func (me *mockEvent) GetContentType() string { args := me.Called() return args.String(0) } func (me *mockEvent) GetBody() []byte { args := me.Called() return args.Get(0).([]byte) } func (me *mockEvent) GetBodyObject() interface{} { args := me.Called() return args.Get(0) } func (me *mockEvent) GetHeader(key string) interface{} { args := me.Called(key) return args.String(0) }
Apache License 2.0
cppforlife/knctl
vendor/github.com/spf13/cobra/doc/yaml_docs.go
GenYamlTreeCustom
go
func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error { for _, c := range cmd.Commands() { if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { continue } if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil { return err } } basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml" filename := filepath.Join(dir, basename) f, err := os.Create(filename) if err != nil { return err } defer f.Close() if _, err := io.WriteString(f, filePrepender(filename)); err != nil { return err } if err := GenYamlCustom(cmd, f, linkHandler); err != nil { return err } return nil }
GenYamlTreeCustom creates yaml structured ref files.
https://github.com/cppforlife/knctl/blob/47e523d82b9d655d8648fe36d371a084b4613945/vendor/github.com/spf13/cobra/doc/yaml_docs.go#L58-L83
package doc import ( "fmt" "io" "os" "path/filepath" "sort" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" "gopkg.in/yaml.v2" ) type cmdOption struct { Name string Shorthand string `yaml:",omitempty"` DefaultValue string `yaml:"default_value,omitempty"` Usage string `yaml:",omitempty"` } type cmdDoc struct { Name string Synopsis string `yaml:",omitempty"` Description string `yaml:",omitempty"` Options []cmdOption `yaml:",omitempty"` InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"` Example string `yaml:",omitempty"` SeeAlso []string `yaml:"see_also,omitempty"` } func GenYamlTree(cmd *cobra.Command, dir string) error { identity := func(s string) string { return s } emptyStr := func(s string) string { return "" } return GenYamlTreeCustom(cmd, dir, emptyStr, identity) }
Apache License 2.0
contiv/vpp
plugins/crd/datastore/vpp_data_store.go
SetNodeTelemetry
go
func (vds *VppDataStore) SetNodeTelemetry(nodeName string, nTele map[string]telemetrymodel.NodeTelemetry) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeTelemetry for node %s", nodeName) } node.NodeTelemetry = nTele return nil }
SetNodeTelemetry is a simple function to set a nodes telemetry data given its name.
https://github.com/contiv/vpp/blob/c6ed55900e77dd14b8705dc6fa6d90f7a8b70b56/plugins/crd/datastore/vpp_data_store.go#L288-L298
package datastore import ( "fmt" "sort" "strconv" "strings" "sync" "github.com/pkg/errors" "github.com/contiv/vpp/plugins/crd/cache/telemetrymodel" "github.com/contiv/vpp/plugins/ipnet" "github.com/contiv/vpp/plugins/ipnet/restapi" "go.ligato.io/cn-infra/v2/health/statuscheck/model/status" ) type VppDataStore struct { lock *sync.Mutex NodeMap map[string]*telemetrymodel.Node LoopIPMap map[string]*telemetrymodel.Node GigEIPMap map[string]*telemetrymodel.Node LoopMACMap map[string]*telemetrymodel.Node HostIPMap map[string]*telemetrymodel.Node } func (vds *VppDataStore) CreateNode(ID uint32, nodeName, IPAddr string) error { vds.lock.Lock() defer vds.lock.Unlock() if _, ok := vds.retrieveNode(nodeName); ok { return fmt.Errorf("node %s already exists", nodeName) } n := &telemetrymodel.Node{ NodeInfo: &telemetrymodel.NodeInfo{IPAddr: IPAddr, ID: ID, Name: nodeName}, } n.PodMap = make(map[string]*telemetrymodel.Pod) vds.NodeMap[nodeName] = n if IPAddr != "" { ipa := strings.Split(IPAddr, "/") vds.GigEIPMap[ipa[0]] = n } return nil } func (vds *VppDataStore) RetrieveNode(nodeName string) (n *telemetrymodel.Node, err error) { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if ok { return node, nil } return nil, fmt.Errorf("node %s not found", nodeName) } func (vds *VppDataStore) DeleteNode(nodeName string) error { vds.lock.Lock() defer vds.lock.Unlock() nodeID, err := strconv.Atoi(nodeName) if err != nil { return fmt.Errorf("invalid nodeId %s", nodeName) } for _, node := range vds.NodeMap { if node.ID == uint32(nodeID) { for _, intf := range node.NodeInterfaces { if intf.Value.Name == ipnet.DefaultVxlanBVIInterfaceName { delete(vds.LoopMACMap, intf.Value.PhysAddress) for _, ip := range intf.Value.IpAddresses { delete(vds.LoopIPMap, ip) } } } delete(vds.NodeMap, node.Name) delete(vds.GigEIPMap, node.IPAddr) return nil } } return fmt.Errorf("node %s does not exist", nodeName) } func (vds *VppDataStore) RetrieveAllNodes() []*telemetrymodel.Node { vds.lock.Lock() defer vds.lock.Unlock() var str []string for k := range vds.NodeMap { str = append(str, k) } var nList []*telemetrymodel.Node sort.Strings(str) for _, v := range str { n, _ := vds.retrieveNode(v) nList = append(nList, n) } return nList } func (vds *VppDataStore) UpdateNode(ID uint32, nodeName, IPAddr string) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.NodeMap[nodeName] if !ok { return errors.Errorf("Node with name %+vds not found in vpp cache", nodeName) } node.IPAddr = IPAddr node.ID = ID if IPAddr != "" { ipa := strings.Split(IPAddr, "/") vds.GigEIPMap[ipa[0]] = node } return nil } func (vds *VppDataStore) ClearCache() { for _, node := range vds.NodeMap { node.NodeInterfaces = nil node.NodeBridgeDomains = nil node.NodeL2Fibs = nil node.NodeLiveness = nil node.NodeTelemetry = nil node.NodeIPArp = nil } vds.LoopMACMap = make(map[string]*telemetrymodel.Node) vds.LoopIPMap = make(map[string]*telemetrymodel.Node) vds.HostIPMap = make(map[string]*telemetrymodel.Node) } func (vds *VppDataStore) ReinitializeCache() { vds.ClearCache() vds.NodeMap = make(map[string]*telemetrymodel.Node) } func (vds *VppDataStore) DumpCache() { fmt.Printf("NodeMap: %+v\n", vds.NodeMap) fmt.Printf("LoopMACMap: %+v\n", vds.LoopMACMap) fmt.Printf("GigEIPMap: %+v\n", vds.GigEIPMap) fmt.Printf("HostIPMap: %+v\n", vds.HostIPMap) fmt.Printf("LoopIPMap: %+v\n", vds.LoopIPMap) } func NewVppDataStore() (n *VppDataStore) { return &VppDataStore{ lock: &sync.Mutex{}, NodeMap: make(map[string]*telemetrymodel.Node), LoopIPMap: make(map[string]*telemetrymodel.Node), GigEIPMap: make(map[string]*telemetrymodel.Node), LoopMACMap: make(map[string]*telemetrymodel.Node), HostIPMap: make(map[string]*telemetrymodel.Node), } } func (vds *VppDataStore) SetNodeLiveness(nodeName string, nLive *status.AgentStatus) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeLiveness for node %s", nodeName) } node.NodeLiveness = nLive return nil } func (vds *VppDataStore) SetNodeInterfaces(nodeName string, nInt telemetrymodel.NodeInterfaces) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeInterfaces for node %s", nodeName) } node.NodeInterfaces = make(telemetrymodel.NodeInterfaceMap) for _, iface := range nInt { node.NodeInterfaces[iface.Metadata.SwIfIndex] = iface } return nil } func (vds *VppDataStore) SetLinuxInterfaces(nodeName string, nInt telemetrymodel.LinuxInterfaces) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeInterfaces for node %s", nodeName) } node.LinuxInterfaces = nInt return nil } func (vds *VppDataStore) SetNodeStaticRoutes(nodeName string, nSrs telemetrymodel.NodeStaticRoutes) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeStaticRoutes for node %s", nodeName) } node.NodeStaticRoutes = nSrs return nil } func (vds *VppDataStore) SetNodeBridgeDomain(nodeName string, nBridge telemetrymodel.NodeBridgeDomains) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeBridgeDomains for node %s", nodeName) } node.NodeBridgeDomains = nBridge return nil } func (vds *VppDataStore) SetNodeL2Fibs(nodeName string, nL2F telemetrymodel.NodeL2FibTable) error { vds.lock.Lock() defer vds.lock.Unlock() node, ok := vds.retrieveNode(nodeName) if !ok { return fmt.Errorf("failed to set NodeL2Fibs for node %s", nodeName) } node.NodeL2Fibs = nL2F return nil }
Apache License 2.0
wi2l/fizz
markdown/builder.go
Table
go
func (b *Builder) Table(table [][]string, align []TableAlignment) *Builder { if len(table) < 2 { return b } idxAlign := func(idx int) TableAlignment { alen := len(align) if alen == 0 || idx > alen-1 { return defaultAlign } return align[idx] } headerLen := len(table[0]) colsLens := make([]int, headerLen) for x, line := range table { for y := range line { cl := max(charLen(table[x][y]), colsLens[y]) if cl < minCellSize { colsLens[y] = minCellSize } else { colsLens[y] = cl } } } sb := strings.Builder{} for x, line := range table { if x == 1 { var cols []string for j, l := range colsLens { switch idxAlign(j) { case AlignRight: cols = append(cols, fmt.Sprintf("%s:", strings.Repeat("-", l-1))) case AlignCenter: cols = append(cols, fmt.Sprintf(":%s:", strings.Repeat("-", l-2))) case AlignLeft: cols = append(cols, strings.Repeat("-", l)) } } sb.WriteString(joinCols(cols)) sb.WriteByte('\n') } cols := make([]string, len(table[0])) for y, cl := range colsLens { var cell string if y <= len(line)-1 { cell = line[y] } if cell == "" { cols[y] = strings.Repeat(" ", cl) } else { cell = reCRLN.ReplaceAllString(cell, " ") cols[y] = padSpaces(cell, cl, idxAlign(y)) } } sb.WriteString(joinCols(cols)) sb.WriteByte('\n') } b.writeln(sb.String()) return b }
Table adds a table from the given two-dimensional interface array to the markdown content. The first row of the array is considered as the table header. Align represents the alignment of each column, left to right. If the alignment of a column is not defined, the rigth alignment will be used instead as default.
https://github.com/wi2l/fizz/blob/d0b235e1c18db64d5fcb3206fb912d490a6af1a5/markdown/builder.go#L228-L301
package markdown import ( "fmt" "math" "regexp" "strings" "golang.org/x/text/unicode/norm" ) type TableAlignment uint8 const ( AlignLeft TableAlignment = iota AlignCenter AlignRight ) var reCRLN = regexp.MustCompile(`\r?\n`) type Builder struct { markdown string } func (b *Builder) String() string { return strings.TrimSpace(b.nl().markdown) } func (b *Builder) Block() *Builder { return new(Builder) } func (b *Builder) Line(text string) *Builder { return b.write(text) } func (b *Builder) P(text string) *Builder { return b.writeln(text).nl() } func (b *Builder) H1(text string) *Builder { return b.writeln(header(text, 1)).nl() } func (b *Builder) H2(text string) *Builder { return b.writeln(header(text, 2)).nl() } func (b *Builder) H3(text string) *Builder { return b.writeln(header(text, 3)).nl() } func (b *Builder) H4(text string) *Builder { return b.writeln(header(text, 4)).nl() } func (b *Builder) H5(text string) *Builder { return b.writeln(header(text, 5)).nl() } func (b *Builder) H6(text string) *Builder { return b.writeln(header(text, 6)).nl() } func header(text string, level int) string { text = reCRLN.ReplaceAllString(text, " ") return fmt.Sprintf("%s %s", strings.Repeat("#", level), strings.TrimSpace(text)) } func (b *Builder) nl() *Builder { return b.write("\n") } func (b *Builder) AltH1(header string) *Builder { header = reCRLN.ReplaceAllString(header, " ") header = strings.TrimSpace(header) return b.writeln(header).writeln(strings.Repeat("=", charLen(header))).nl() } func (b *Builder) AltH2(header string) *Builder { header = reCRLN.ReplaceAllString(header, " ") header = strings.TrimSpace(header) return b.writeln(header).writeln(strings.Repeat("-", charLen(header))).nl() } func (b *Builder) HR() *Builder { return b.P("---------------------------------------") } func (b *Builder) BR() *Builder { return b.write(" \n") } func (b *Builder) InlineCode(code string) string { return fmt.Sprintf("`%s`", code) } func (b *Builder) Code(code, lang string) *Builder { return b. writelnf("```%s", lang). writeln(code). writeln("```"). nl() } func (b *Builder) Emphasis(text string) string { return b.Italic(text) } func (b *Builder) Italic(text string) string { return fmt.Sprintf("*%s*", text) } func (b *Builder) StrongEmphasis(text string) string { return b.Bold(text) } func (b *Builder) Bold(text string) string { return fmt.Sprintf("**%s**", text) } func (b *Builder) CombinedEmphasis(text string) string { return fmt.Sprintf("**_%s_**", text) } func (b *Builder) Strikethrough(text string) string { return fmt.Sprintf("~~%s~~", text) } func (b *Builder) Link(url, title string) string { return fmt.Sprintf("[%s](%s)", title, url) } func (b *Builder) Image(url, title string) string { return fmt.Sprintf("![%s](%s)", title, url) } func (b *Builder) Blockquote(text string) *Builder { lines := strings.Split(text, "\n") var newLines []string for _, l := range lines { newLines = append(newLines, strings.TrimSpace("> "+l)) } content := strings.Join(newLines, "\n") return b.P(content) } func (b *Builder) BulletedList(list ...interface{}) *Builder { for _, el := range list { lines := strings.Split(fmt.Sprintf("%s", el), "\n") for i, l := range lines { if i == 0 { b.writelnf("* %s", l) } else { b.writelnf(" %s", l) } } } return b.nl() } func (b *Builder) NumberedList(list ...interface{}) *Builder { for i, el := range list { lines := strings.Split(fmt.Sprintf("%s", el), "\n") for j, l := range lines { if j == 0 { b.writelnf("%d. %s", i+1, l) } else { b.writelnf(" %s", l) } } } return b.nl() } const ( minCellSize = 3 defaultAlign = AlignLeft )
MIT License
synthetichealth/gofhir
vendor/github.com/intervention-engine/fhir/search/mongo_search.go
periodSelector
go
func periodSelector(d *DateParam) bson.M { switch d.Prefix { case EQ: return bson.M{ "start.time": bson.M{ "$gte": d.Date.RangeLowIncl(), }, "end.time": bson.M{ "$lt": d.Date.RangeHighExcl(), }, } case GT: return bson.M{ "$or": []bson.M{ bson.M{ "end.time": bson.M{ "$gt": d.Date.RangeLowIncl(), }, }, bson.M{ "$ne": nil, "end": nil, }, }, } case LT: return bson.M{ "$or": []bson.M{ bson.M{ "start.time": bson.M{ "$lt": d.Date.RangeLowIncl(), }, }, bson.M{ "$ne": nil, "start": nil, }, }, } case GE: return bson.M{ "$or": []bson.M{ bson.M{ "start.time": bson.M{ "$gte": d.Date.RangeLowIncl(), }, }, bson.M{ "end.time": bson.M{ "$gt": d.Date.RangeLowIncl(), }, }, bson.M{ "$ne": nil, "end": nil, }, }, } case LE: return bson.M{ "$or": []bson.M{ bson.M{ "end.time": bson.M{ "$lt": d.Date.RangeHighExcl(), }, }, bson.M{ "start.time": bson.M{ "$lt": d.Date.RangeLowIncl(), }, }, bson.M{ "$ne": nil, "start": nil, }, }, } case SA: return bson.M{ "start.time": bson.M{ "$gte": d.Date.RangeHighExcl(), }, } case EB: return bson.M{ "end.time": bson.M{ "$lt": d.Date.RangeLowIncl(), }, } } panic(createUnsupportedSearchError("MSG_PARAM_INVALID", fmt.Sprintf("Parameter \"%s\" content is invalid", d.Name))) }
Note that this solution is not 100% correct because we don't represent dates as ranges in the database -- but the FHIR spec calls for this sort of behavior to correctly implement these searches. An easy example is that while 2012-01-01 should be compared as the range from 00:00:00.000 to 23:59:59.999, we currently only compare against 00:00:00.000 -- so some things that should match, might not. TODO: Fix this via more complex search criteria (not likely feasible) or by a different representation in the database (e.g., storing upper and lower bounds of dates in the DB).
https://github.com/synthetichealth/gofhir/blob/7dca2ca1547e744319f4db51489c67b58aedb7a3/vendor/github.com/intervention-engine/fhir/search/mongo_search.go#L332-L427
package search import ( "fmt" "net/http" "regexp" "strings" "github.com/intervention-engine/fhir/models" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type MongoSearcher struct { db *mgo.Database } func NewMongoSearcher(db *mgo.Database) *MongoSearcher { return &MongoSearcher{db} } func (m *MongoSearcher) GetDB() *mgo.Database { return m.db } func (m *MongoSearcher) CreateQuery(query Query) *mgo.Query { return m.createQuery(query, true) } func (m *MongoSearcher) CreateQueryWithoutOptions(query Query) *mgo.Query { return m.createQuery(query, false) } func (m *MongoSearcher) CreateQueryObject(query Query) bson.M { return m.createQueryObject(query) } func (m *MongoSearcher) createQuery(query Query, withOptions bool) *mgo.Query { c := m.db.C(models.PluralizeLowerResourceName(query.Resource)) q := m.createQueryObject(query) mgoQuery := c.Find(q) if withOptions { o := query.Options() removeParallelArraySorts(o) if len(o.Sort) > 0 { fields := make([]string, len(o.Sort)) for i := range o.Sort { field := convertSearchPathToMongoField(o.Sort[i].Parameter.Paths[0].Path) if o.Sort[i].Descending { field = "-" + field } fields[i] = field } mgoQuery = mgoQuery.Sort(fields...) } if o.Offset > 0 { mgoQuery = mgoQuery.Skip(o.Offset) } mgoQuery = mgoQuery.Limit(o.Count) } return mgoQuery } func (m *MongoSearcher) CreatePipeline(query Query) *mgo.Pipe { c := m.db.C(models.PluralizeLowerResourceName(query.Resource)) p := []bson.M{{"$match": m.createQueryObject(query)}} o := query.Options() removeParallelArraySorts(o) if len(o.Sort) > 0 { var sortBSOND bson.D for _, sort := range o.Sort { field := convertSearchPathToMongoField(sort.Parameter.Paths[0].Path) order := 1 if sort.Descending { order = -1 } sortBSOND = append(sortBSOND, bson.DocElem{Name: field, Value: order}) } p = append(p, bson.M{"$sort": sortBSOND}) } if o.Offset > 0 { p = append(p, bson.M{"$skip": o.Offset}) } p = append(p, bson.M{"$limit": o.Count}) if len(o.Include) > 0 { for _, incl := range o.Include { for _, inclPath := range incl.Parameter.Paths { if inclPath.Type != "Reference" { continue } localField := strings.Replace(inclPath.Path, "[]", "", -1) + ".referenceid" for i, inclTarget := range incl.Parameter.Targets { if inclTarget == "Any" { continue } from := models.PluralizeLowerResourceName(inclTarget) as := fmt.Sprintf("_included%sResourcesReferencedBy%s", inclTarget, strings.Title(incl.Parameter.Name)) if len(incl.Parameter.Paths) > 1 { as += fmt.Sprintf("Path%d", i+1) } p = append(p, bson.M{"$lookup": bson.M{ "from": from, "localField": localField, "foreignField": "_id", "as": as, }}) } } } } if len(o.RevInclude) > 0 { for _, incl := range o.RevInclude { targetsSearchResource := false for _, inclTarget := range incl.Parameter.Targets { if inclTarget == query.Resource || inclTarget == "Any" { targetsSearchResource = true break } } if !targetsSearchResource { continue } from := models.PluralizeLowerResourceName(incl.Parameter.Resource) for i, inclPath := range incl.Parameter.Paths { if inclPath.Type != "Reference" { continue } foreignField := strings.Replace(inclPath.Path, "[]", "", -1) + ".referenceid" as := fmt.Sprintf("_revIncluded%sResourcesReferencing%s", incl.Parameter.Resource, strings.Title(incl.Parameter.Name)) if len(incl.Parameter.Paths) > 1 { as += fmt.Sprintf("Path%d", i+1) } p = append(p, bson.M{"$lookup": bson.M{ "from": from, "localField": "_id", "foreignField": foreignField, "as": as, }}) } } } return c.Pipe(p) } func (m *MongoSearcher) createQueryObject(query Query) bson.M { result := bson.M{} for _, p := range m.createParamObjects(query.Params()) { merge(result, p) } return result } func (m *MongoSearcher) createParamObjects(params []SearchParam) []bson.M { results := make([]bson.M, len(params)) for i, p := range params { panicOnUnsupportedFeatures(p) switch p := p.(type) { case *CompositeParam: results[i] = m.createCompositeQueryObject(p) case *DateParam: results[i] = m.createDateQueryObject(p) case *NumberParam: results[i] = m.createNumberQueryObject(p) case *QuantityParam: results[i] = m.createQuantityQueryObject(p) case *ReferenceParam: results[i] = m.createReferenceQueryObject(p) case *StringParam: results[i] = m.createStringQueryObject(p) case *TokenParam: results[i] = m.createTokenQueryObject(p) case *URIParam: results[i] = m.createURIQueryObject(p) case *OrParam: results[i] = m.createOrQueryObject(p) default: builder, err := GlobalMongoRegistry().LookupBSONBuilder(p.getInfo().Type) if err != nil { panic(createInternalServerError("MSG_PARAM_UNKNOWN", fmt.Sprintf("Parameter \"%s\" not understood", p.getInfo().Name))) } result, err := builder(p, m) if err != nil { panic(createInternalServerError("MSG_PARAM_INVALID", fmt.Sprintf("Parameter \"%s\" content is invalid", p.getInfo().Name))) } results[i] = result } } return results } func panicOnUnsupportedFeatures(p SearchParam) { _, isDate := p.(*DateParam) prefix := p.getInfo().Prefix if prefix != "" && prefix != EQ && !isDate { panic(createUnsupportedSearchError("MSG_PARAM_INVALID", fmt.Sprintf("Parameter \"%s\" content is invalid", p.getInfo().Name))) } _, isRef := p.(*ReferenceParam) modifier := p.getInfo().Modifier if modifier != "" { if _, ok := SearchParameterDictionary[modifier]; !isRef || !ok { panic(createUnsupportedSearchError("MSG_PARAM_MODIFIER_INVALID", fmt.Sprintf("Parameter \"%s\" modifier is invalid", p.getInfo().Name))) } } } func (m *MongoSearcher) createCompositeQueryObject(c *CompositeParam) bson.M { panic(createUnsupportedSearchError("MSG_PARAM_UNKNOWN", fmt.Sprintf("Parameter \"%s\" not understood", c.Name))) } func (m *MongoSearcher) createDateQueryObject(d *DateParam) bson.M { single := func(p SearchParamPath) bson.M { switch p.Type { case "date", "dateTime", "instant": return buildBSON(p.Path, dateSelector(d)) case "Period": return buildBSON(p.Path, periodSelector(d)) case "Timing": return buildBSON(p.Path+".event", dateSelector(d)) default: return bson.M{} } } return orPaths(single, d.Paths) } func dateSelector(d *DateParam) bson.M { var timeCriteria bson.M switch d.Prefix { case EQ: timeCriteria = bson.M{ "$gte": d.Date.RangeLowIncl(), "$lt": d.Date.RangeHighExcl(), } case GT, SA: timeCriteria = bson.M{ "$gt": d.Date.RangeLowIncl(), } case LT, EB: timeCriteria = bson.M{ "$lt": d.Date.RangeLowIncl(), } case GE: timeCriteria = bson.M{ "$gte": d.Date.RangeLowIncl(), } case LE: timeCriteria = bson.M{ "$lt": d.Date.RangeHighExcl(), } default: panic(createUnsupportedSearchError("MSG_PARAM_INVALID", fmt.Sprintf("Parameter \"%s\" content is invalid", d.Name))) } return bson.M{"time": timeCriteria} }
Apache License 2.0
lilic/instrumently
vendor/gonum.org/v1/gonum/blas/gonum/level1cmplx64.go
Cscal
go
func (Implementation) Cscal(n int, alpha complex64, x []complex64, incX int) { if incX < 1 { if incX == 0 { panic(zeroIncX) } return } if (n-1)*incX >= len(x) { panic(shortX) } if n < 1 { if n == 0 { return } panic(nLT0) } if alpha == 0 { if incX == 1 { x = x[:n] for i := range x { x[i] = 0 } return } for ix := 0; ix < n*incX; ix += incX { x[ix] = 0 } return } if incX == 1 { c64.ScalUnitary(alpha, x[:n]) return } c64.ScalInc(alpha, x, uintptr(n), uintptr(incX)) }
Cscal scales the vector x by a complex scalar alpha. Cscal has no effect if incX < 0. Complex64 implementations are autogenerated and not directly tested.
https://github.com/lilic/instrumently/blob/8cce3198cf51b110094e9e7b29355d1a3423c23b/vendor/gonum.org/v1/gonum/blas/gonum/level1cmplx64.go#L390-L424
package gonum import ( math "gonum.org/v1/gonum/internal/math32" "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/internal/asm/c64" ) var _ blas.Complex64Level1 = Implementation{} func (Implementation) Scasum(n int, x []complex64, incX int) float32 { if n < 0 { panic(nLT0) } if incX < 1 { if incX == 0 { panic(zeroIncX) } return 0 } var sum float32 if incX == 1 { if len(x) < n { panic(shortX) } for _, v := range x[:n] { sum += scabs1(v) } return sum } if (n-1)*incX >= len(x) { panic(shortX) } for i := 0; i < n; i++ { v := x[i*incX] sum += scabs1(v) } return sum } func (Implementation) Scnrm2(n int, x []complex64, incX int) float32 { if incX < 1 { if incX == 0 { panic(zeroIncX) } return 0 } if n < 1 { if n == 0 { return 0 } panic(nLT0) } if (n-1)*incX >= len(x) { panic(shortX) } var ( scale float32 ssq float32 = 1 ) if incX == 1 { for _, v := range x[:n] { re, im := math.Abs(real(v)), math.Abs(imag(v)) if re != 0 { if re > scale { ssq = 1 + ssq*(scale/re)*(scale/re) scale = re } else { ssq += (re / scale) * (re / scale) } } if im != 0 { if im > scale { ssq = 1 + ssq*(scale/im)*(scale/im) scale = im } else { ssq += (im / scale) * (im / scale) } } } if math.IsInf(scale, 1) { return math.Inf(1) } return scale * math.Sqrt(ssq) } for ix := 0; ix < n*incX; ix += incX { re, im := math.Abs(real(x[ix])), math.Abs(imag(x[ix])) if re != 0 { if re > scale { ssq = 1 + ssq*(scale/re)*(scale/re) scale = re } else { ssq += (re / scale) * (re / scale) } } if im != 0 { if im > scale { ssq = 1 + ssq*(scale/im)*(scale/im) scale = im } else { ssq += (im / scale) * (im / scale) } } } if math.IsInf(scale, 1) { return math.Inf(1) } return scale * math.Sqrt(ssq) } func (Implementation) Icamax(n int, x []complex64, incX int) int { if incX < 1 { if incX == 0 { panic(zeroIncX) } return -1 } if n < 1 { if n == 0 { return -1 } panic(nLT0) } if len(x) <= (n-1)*incX { panic(shortX) } idx := 0 max := scabs1(x[0]) if incX == 1 { for i, v := range x[1:n] { absV := scabs1(v) if absV > max { max = absV idx = i + 1 } } return idx } ix := incX for i := 1; i < n; i++ { absV := scabs1(x[ix]) if absV > max { max = absV idx = i } ix += incX } return idx } func (Implementation) Caxpy(n int, alpha complex64, x []complex64, incX int, y []complex64, incY int) { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n < 1 { if n == 0 { return } panic(nLT0) } if (incX > 0 && (n-1)*incX >= len(x)) || (incX < 0 && (1-n)*incX >= len(x)) { panic(shortX) } if (incY > 0 && (n-1)*incY >= len(y)) || (incY < 0 && (1-n)*incY >= len(y)) { panic(shortY) } if alpha == 0 { return } if incX == 1 && incY == 1 { c64.AxpyUnitary(alpha, x[:n], y[:n]) return } var ix, iy int if incX < 0 { ix = (1 - n) * incX } if incY < 0 { iy = (1 - n) * incY } c64.AxpyInc(alpha, x, y, uintptr(n), uintptr(incX), uintptr(incY), uintptr(ix), uintptr(iy)) } func (Implementation) Ccopy(n int, x []complex64, incX int, y []complex64, incY int) { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n < 1 { if n == 0 { return } panic(nLT0) } if (incX > 0 && (n-1)*incX >= len(x)) || (incX < 0 && (1-n)*incX >= len(x)) { panic(shortX) } if (incY > 0 && (n-1)*incY >= len(y)) || (incY < 0 && (1-n)*incY >= len(y)) { panic(shortY) } if incX == 1 && incY == 1 { copy(y[:n], x[:n]) return } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } for i := 0; i < n; i++ { y[iy] = x[ix] ix += incX iy += incY } } func (Implementation) Cdotc(n int, x []complex64, incX int, y []complex64, incY int) complex64 { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n <= 0 { if n == 0 { return 0 } panic(nLT0) } if incX == 1 && incY == 1 { if len(x) < n { panic(shortX) } if len(y) < n { panic(shortY) } return c64.DotcUnitary(x[:n], y[:n]) } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } if ix >= len(x) || (n-1)*incX >= len(x) { panic(shortX) } if iy >= len(y) || (n-1)*incY >= len(y) { panic(shortY) } return c64.DotcInc(x, y, uintptr(n), uintptr(incX), uintptr(incY), uintptr(ix), uintptr(iy)) } func (Implementation) Cdotu(n int, x []complex64, incX int, y []complex64, incY int) complex64 { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n <= 0 { if n == 0 { return 0 } panic(nLT0) } if incX == 1 && incY == 1 { if len(x) < n { panic(shortX) } if len(y) < n { panic(shortY) } return c64.DotuUnitary(x[:n], y[:n]) } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } if ix >= len(x) || (n-1)*incX >= len(x) { panic(shortX) } if iy >= len(y) || (n-1)*incY >= len(y) { panic(shortY) } return c64.DotuInc(x, y, uintptr(n), uintptr(incX), uintptr(incY), uintptr(ix), uintptr(iy)) } func (Implementation) Csscal(n int, alpha float32, x []complex64, incX int) { if incX < 1 { if incX == 0 { panic(zeroIncX) } return } if (n-1)*incX >= len(x) { panic(shortX) } if n < 1 { if n == 0 { return } panic(nLT0) } if alpha == 0 { if incX == 1 { x = x[:n] for i := range x { x[i] = 0 } return } for ix := 0; ix < n*incX; ix += incX { x[ix] = 0 } return } if incX == 1 { x = x[:n] for i, v := range x { x[i] = complex(alpha*real(v), alpha*imag(v)) } return } for ix := 0; ix < n*incX; ix += incX { v := x[ix] x[ix] = complex(alpha*real(v), alpha*imag(v)) } }
Apache License 2.0
socketplane/socketplane
Godeps/_workspace/src/github.com/hashicorp/yamux/stream.go
processFlags
go
func (s *Stream) processFlags(flags uint16) error { s.stateLock.Lock() defer s.stateLock.Unlock() if flags&flagACK == flagACK { if s.state == streamSYNSent { s.state = streamEstablished } } else if flags&flagFIN == flagFIN { switch s.state { case streamSYNSent: fallthrough case streamSYNReceived: fallthrough case streamEstablished: s.state = streamRemoteClose s.notifyWaiting() case streamLocalClose: s.state = streamClosed s.session.closeStream(s.id) s.notifyWaiting() default: s.session.logger.Printf("[ERR] yamux: unexpected FIN flag in state %d", s.state) return ErrUnexpectedFlag } } else if flags&flagRST == flagRST { s.state = streamReset s.session.closeStream(s.id) s.notifyWaiting() } return nil }
processFlags is used to update the state of the stream based on set flags, if any. Lock must be held
https://github.com/socketplane/socketplane/blob/bc8b7e0e5ddf354c857a77b5cdfb904540026373/Godeps/_workspace/src/github.com/hashicorp/yamux/stream.go#L309-L340
package yamux import ( "bytes" "io" "sync" "sync/atomic" "time" ) type streamState int const ( streamInit streamState = iota streamSYNSent streamSYNReceived streamEstablished streamLocalClose streamRemoteClose streamClosed streamReset ) type Stream struct { recvWindow uint32 sendWindow uint32 id uint32 session *Session state streamState stateLock sync.Mutex recvBuf bytes.Buffer recvLock sync.Mutex controlHdr header controlErr chan error controlHdrLock sync.Mutex sendHdr header sendErr chan error sendLock sync.Mutex recvNotifyCh chan struct{} sendNotifyCh chan struct{} readDeadline time.Time writeDeadline time.Time } func newStream(session *Session, id uint32, state streamState) *Stream { s := &Stream{ id: id, session: session, state: state, controlHdr: header(make([]byte, headerSize)), controlErr: make(chan error, 1), sendHdr: header(make([]byte, headerSize)), sendErr: make(chan error, 1), recvWindow: initialStreamWindow, sendWindow: initialStreamWindow, recvNotifyCh: make(chan struct{}, 1), sendNotifyCh: make(chan struct{}, 1), } return s } func (s *Stream) Session() *Session { return s.session } func (s *Stream) StreamID() uint32 { return s.id } func (s *Stream) Read(b []byte) (n int, err error) { defer asyncNotify(s.recvNotifyCh) START: s.stateLock.Lock() switch s.state { case streamRemoteClose: fallthrough case streamClosed: if s.recvBuf.Len() == 0 { s.stateLock.Unlock() return 0, io.EOF } case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset } s.stateLock.Unlock() s.recvLock.Lock() if s.recvBuf.Len() == 0 { s.recvLock.Unlock() goto WAIT } n, _ = s.recvBuf.Read(b) s.recvLock.Unlock() err = s.sendWindowUpdate() return n, err WAIT: var timeout <-chan time.Time if !s.readDeadline.IsZero() { delay := s.readDeadline.Sub(time.Now()) timeout = time.After(delay) } select { case <-s.recvNotifyCh: goto START case <-timeout: return 0, ErrTimeout } } func (s *Stream) Write(b []byte) (n int, err error) { s.sendLock.Lock() defer s.sendLock.Unlock() total := 0 for total < len(b) { n, err := s.write(b[total:]) total += n if err != nil { return total, err } } return total, nil } func (s *Stream) write(b []byte) (n int, err error) { var flags uint16 var max uint32 var body io.Reader START: s.stateLock.Lock() switch s.state { case streamLocalClose: fallthrough case streamClosed: s.stateLock.Unlock() return 0, ErrStreamClosed case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset } s.stateLock.Unlock() window := atomic.LoadUint32(&s.sendWindow) if window == 0 { goto WAIT } flags = s.sendFlags() max = min(window, uint32(len(b))) body = bytes.NewReader(b[:max]) s.sendHdr.encode(typeData, flags, s.id, max) if err := s.session.waitForSendErr(s.sendHdr, body, s.sendErr); err != nil { return 0, err } atomic.AddUint32(&s.sendWindow, ^uint32(max-1)) return int(max), err WAIT: var timeout <-chan time.Time if !s.writeDeadline.IsZero() { delay := s.writeDeadline.Sub(time.Now()) timeout = time.After(delay) } select { case <-s.sendNotifyCh: goto START case <-timeout: return 0, ErrTimeout } return 0, nil } func (s *Stream) sendFlags() uint16 { s.stateLock.Lock() defer s.stateLock.Unlock() var flags uint16 switch s.state { case streamInit: flags |= flagSYN s.state = streamSYNSent case streamSYNReceived: flags |= flagACK s.state = streamEstablished } return flags } func (s *Stream) sendWindowUpdate() error { s.controlHdrLock.Lock() defer s.controlHdrLock.Unlock() max := s.session.config.MaxStreamWindowSize delta := max - atomic.LoadUint32(&s.recvWindow) flags := s.sendFlags() if delta < (max/2) && flags == 0 { return nil } atomic.AddUint32(&s.recvWindow, delta) s.controlHdr.encode(typeWindowUpdate, flags, s.id, delta) if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { return err } return nil } func (s *Stream) sendClose() error { s.controlHdrLock.Lock() defer s.controlHdrLock.Unlock() flags := s.sendFlags() flags |= flagFIN s.controlHdr.encode(typeWindowUpdate, flags, s.id, 0) if err := s.session.waitForSendErr(s.controlHdr, nil, s.controlErr); err != nil { return err } return nil } func (s *Stream) Close() error { s.stateLock.Lock() switch s.state { case streamSYNSent: fallthrough case streamSYNReceived: fallthrough case streamEstablished: s.state = streamLocalClose goto SEND_CLOSE case streamLocalClose: case streamRemoteClose: s.state = streamClosed s.session.closeStream(s.id) goto SEND_CLOSE case streamClosed: case streamReset: default: panic("unhandled state") } s.stateLock.Unlock() return nil SEND_CLOSE: s.stateLock.Unlock() s.sendClose() s.notifyWaiting() return nil } func (s *Stream) forceClose() { s.stateLock.Lock() s.state = streamClosed s.stateLock.Unlock() s.notifyWaiting() }
Apache License 2.0
tibcosoftware/tgdb-client
api/go/src/tgdb/impl/modelimpl.go
ResetModifiedAttributes
go
func (obj *Graph) ResetModifiedAttributes() { obj.resetModifiedAttributes() }
ResetModifiedAttributes resets the dirty flag on Attributes
https://github.com/tibcosoftware/tgdb-client/blob/90c1b2017c9aafad0a26cebace406744acf48e10/api/go/src/tgdb/impl/modelimpl.go#L821-L823
package impl import ( "bytes" "encoding/gob" "fmt" "strings" "tgdb" ) var logger = DefaultTGLogManager().GetLogger() type GraphMetadata struct { initialized bool descriptors map[string]tgdb.TGAttributeDescriptor descriptorsById map[int64]tgdb.TGAttributeDescriptor edgeTypes map[string]tgdb.TGEdgeType edgeTypesById map[int]tgdb.TGEdgeType nodeTypes map[string]tgdb.TGNodeType nodeTypesById map[int]tgdb.TGNodeType graphObjFactory *GraphObjectFactory } type GraphObjectFactory struct { graphMData *GraphMetadata connection tgdb.TGConnection } func setAttributeViaDescriptor(obj tgdb.TGEntity, attrDesc *AttributeDescriptor, value interface{}) tgdb.TGError { if attrDesc == nil { logger.Error(fmt.Sprint("ERROR: Returning AbstractEntity:setAttributeViaDescriptor as AttrDesc is EMPTY")) errMsg := fmt.Sprintf("Attribute Descriptor cannot be null") return GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } if value == nil { logger.Error(fmt.Sprint("ERROR: Returning AbstractEntity:setAttributeViaDescriptor as value is EMPTY")) errMsg := fmt.Sprintf("Attribute value is required") return GetErrorByType(TGErrorIOException, INTERNAL_SERVER_ERROR, errMsg, "") } attrDescName := attrDesc.GetName() attr := obj.(*AbstractEntity).Attributes[attrDescName] if attr == nil { if attrDesc.GetAttrType() == AttributeTypeInvalid { logger.Error(fmt.Sprint("ERROR: Returning AbstractEntity:setAttributeViaDescriptor as AttrDesc.GetAttrType() == types.AttributeTypeInvalid")) errMsg := fmt.Sprintf("Attribute descriptor is of incorrect type") return GetErrorByType(TGErrorIOException, INTERNAL_SERVER_ERROR, errMsg, "") } newAttr, aErr := CreateAttributeWithDesc(nil, attrDesc, nil) if aErr != nil { logger.Error(fmt.Sprintf("ERROR: Returning AbstractEntity:setAttributeViaDescriptor unable to create attribute '%s' w/ descriptor and value '%+v'", attrDesc, value)) return aErr } newAttr.SetOwner(obj) attr = newAttr } if !attr.GetIsModified() { obj.(*AbstractEntity).ModifiedAttributes = append(obj.(*AbstractEntity).ModifiedAttributes, attr) } err := attr.SetValue(value) if err != nil { logger.Error(fmt.Sprintf("ERROR: Returning AbstractEntity:setAttributeViaDescriptor unable to set attribute value w/ error '%+v'", err.Error())) return err } obj.(*AbstractEntity).Attributes[attrDesc.Name] = attr return nil } func DefaultGraphMetadata() *GraphMetadata { gob.Register(GraphMetadata{}) newGraphMetadata := GraphMetadata{ initialized: false, descriptors: make(map[string]tgdb.TGAttributeDescriptor, 0), descriptorsById: make(map[int64]tgdb.TGAttributeDescriptor, 0), edgeTypes: make(map[string]tgdb.TGEdgeType, 0), edgeTypesById: make(map[int]tgdb.TGEdgeType, 0), nodeTypes: make(map[string]tgdb.TGNodeType, 0), nodeTypesById: make(map[int]tgdb.TGNodeType, 0), } return &newGraphMetadata } func NewGraphMetadata(gof *GraphObjectFactory) *GraphMetadata { newGraphMetadata := DefaultGraphMetadata() newGraphMetadata.graphObjFactory = gof return newGraphMetadata } func (obj *GraphMetadata) GetNewAttributeDescriptors() ([]tgdb.TGAttributeDescriptor, tgdb.TGError) { if obj.descriptors == nil || len(obj.descriptors) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNewAttributeDescriptors as there are NO new AttrDesc`")) return nil, nil } attrDesc := make([]tgdb.TGAttributeDescriptor, 0) for _, desc := range obj.descriptors { if desc.(*AttributeDescriptor).GetAttributeId() < 0 { attrDesc = append(attrDesc, desc) } } return attrDesc, nil } func (obj *GraphMetadata) GetConnection() tgdb.TGConnection { return obj.graphObjFactory.GetConnection() } func (obj *GraphMetadata) GetGraphObjectFactory() *GraphObjectFactory { return obj.graphObjFactory } func (obj *GraphMetadata) GetAttributeDescriptorsById() map[int64]tgdb.TGAttributeDescriptor { return obj.descriptorsById } func (obj *GraphMetadata) GetEdgeTypesById() map[int]tgdb.TGEdgeType { return obj.edgeTypesById } func (obj *GraphMetadata) GetNodeTypesById() map[int]tgdb.TGNodeType { return obj.nodeTypesById } func (obj *GraphMetadata) IsInitialized() bool { return obj.initialized } func (obj *GraphMetadata) SetInitialized(flag bool) { obj.initialized = flag } func (obj *GraphMetadata) SetAttributeDescriptors(attrDesc map[string]tgdb.TGAttributeDescriptor) { obj.descriptors = attrDesc } func (obj *GraphMetadata) SetAttributeDescriptorsById(attrDescId map[int64]tgdb.TGAttributeDescriptor) { obj.descriptorsById = attrDescId } func (obj *GraphMetadata) SetEdgeTypes(edgeTypes map[string]tgdb.TGEdgeType) { obj.edgeTypes = edgeTypes } func (obj *GraphMetadata) SetEdgeTypesById(edgeTypesId map[int]tgdb.TGEdgeType) { obj.edgeTypesById = edgeTypesId } func (obj *GraphMetadata) SetNodeTypes(nodeTypes map[string]tgdb.TGNodeType) { obj.nodeTypes = nodeTypes } func (obj *GraphMetadata) SetNodeTypesById(nodeTypes map[int]tgdb.TGNodeType) { obj.nodeTypesById = nodeTypes } func (obj *GraphMetadata) UpdateMetadata(attrDescList []tgdb.TGAttributeDescriptor, nodeTypeList []tgdb.TGNodeType, edgeTypeList []tgdb.TGEdgeType) tgdb.TGError { if attrDescList != nil { for _, attrDesc := range attrDescList { obj.descriptors[attrDesc.GetName()] = attrDesc.(*AttributeDescriptor) obj.descriptorsById[attrDesc.GetAttributeId()] = attrDesc.(*AttributeDescriptor) } } if nodeTypeList != nil { for _, nodeType := range nodeTypeList { nodeType.(*NodeType).UpdateMetadata(obj) obj.nodeTypes[nodeType.GetName()] = nodeType.(*NodeType) obj.nodeTypesById[nodeType.GetEntityTypeId()] = nodeType.(*NodeType) } } if edgeTypeList != nil { for _, edgeType := range edgeTypeList { edgeType.(*EdgeType).UpdateMetadata(obj) obj.edgeTypes[edgeType.GetName()] = edgeType.(*EdgeType) obj.edgeTypesById[edgeType.GetEntityTypeId()] = edgeType.(*EdgeType) } } obj.initialized = true return nil } func (obj *GraphMetadata) CreateAttributeDescriptor(attrName string, attrType int, isArray bool) tgdb.TGAttributeDescriptor { newAttrDesc := NewAttributeDescriptorAsArray(attrName, attrType, isArray) obj.descriptors[attrName] = newAttrDesc return newAttrDesc } func (obj *GraphMetadata) CreateAttributeDescriptorForDataType(attrName string, dataTypeClassName string) tgdb.TGAttributeDescriptor { attrType := GetAttributeTypeFromName(dataTypeClassName) if logger.IsDebug() { logger.Debug(fmt.Sprintf("GraphMetadata CreateAttributeDescriptorForDataType creating attribute descriptor for '%+v' w/ type '%+v'", attrName, attrType)) } newAttrDesc := NewAttributeDescriptorAsArray(attrName, attrType.GetTypeId(), false) obj.descriptors[attrName] = newAttrDesc return newAttrDesc } func (obj *GraphMetadata) GetAttributeDescriptor(attrName string) (tgdb.TGAttributeDescriptor, tgdb.TGError) { if obj.descriptors == nil || len(obj.descriptors) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetAttributeDescriptor as there are NO AttrDesc`")) return nil, nil } desc := obj.descriptors[attrName] return desc, nil } func (obj *GraphMetadata) GetAttributeDescriptorById(id int64) (tgdb.TGAttributeDescriptor, tgdb.TGError) { if obj.descriptorsById == nil || len(obj.descriptorsById) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetAttributeDescriptorById as there are NO AttrDesc`")) return nil, nil } desc := obj.descriptorsById[id] return desc, nil } func (obj *GraphMetadata) GetAttributeDescriptors() ([]tgdb.TGAttributeDescriptor, tgdb.TGError) { if obj.descriptors == nil || len(obj.descriptors) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetAttributeDescriptors as there are NO AttrDesc`")) return nil, nil } attrDesc := make([]tgdb.TGAttributeDescriptor, 0) for _, desc := range obj.descriptors { attrDesc = append(attrDesc, desc) } return attrDesc, nil } func (obj *GraphMetadata) CreateCompositeKey(nodeTypeName string) tgdb.TGKey { compKey := NewCompositeKey(obj, nodeTypeName) return compKey } func (obj *GraphMetadata) CreateEdgeType(typeName string, parentEdgeType tgdb.TGEdgeType) tgdb.TGEdgeType { newEdgeType := NewEdgeType(typeName, parentEdgeType.GetDirectionType(), parentEdgeType) return newEdgeType } func (obj *GraphMetadata) GetEdgeType(typeName string) (tgdb.TGEdgeType, tgdb.TGError) { if obj.edgeTypes == nil || len(obj.edgeTypes) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetEdgeType as there are NO edges`")) return nil, nil } edge := obj.edgeTypes[typeName] return edge, nil } func (obj *GraphMetadata) GetEdgeTypeById(id int) (tgdb.TGEdgeType, tgdb.TGError) { if obj.edgeTypesById == nil || len(obj.edgeTypesById) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetEdgeTypeById as there are NO edges`")) return nil, nil } edge := obj.edgeTypesById[id] return edge, nil } func (obj *GraphMetadata) GetEdgeTypes() ([]tgdb.TGEdgeType, tgdb.TGError) { if obj.edgeTypes == nil || len(obj.edgeTypes) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetEdgeTypes as there are NO edges`")) return nil, nil } edgeTypes := make([]tgdb.TGEdgeType, 0) for _, edgeType := range obj.edgeTypes { edgeTypes = append(edgeTypes, edgeType) } return edgeTypes, nil } func (obj *GraphMetadata) CreateNodeType(typeName string, parentNodeType tgdb.TGNodeType) tgdb.TGNodeType { newNodeType := NewNodeType(typeName, parentNodeType) return newNodeType } func (obj *GraphMetadata) GetNodeType(typeName string) (tgdb.TGNodeType, tgdb.TGError) { if obj.nodeTypes == nil || len(obj.nodeTypes) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNodeType as there are NO nodes")) return nil, nil } node := obj.nodeTypes[typeName] return node, nil } func (obj *GraphMetadata) GetNodeTypeById(id int) (tgdb.TGNodeType, tgdb.TGError) { if obj.nodeTypesById == nil || len(obj.nodeTypesById) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNodeTypeById as there are NO nodes")) return nil, nil } node := obj.nodeTypesById[id] if logger.IsDebug() { logger.Debug(fmt.Sprintf("Returning GraphMetadata:GetNodeTypeById read node as '%+v'", node)) } return node, nil } func (obj *GraphMetadata) GetNodeTypes() ([]tgdb.TGNodeType, tgdb.TGError) { if obj.nodeTypes == nil || len(obj.nodeTypes) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning GraphMetadata:GetNodeTypes as there are NO nodes")) return nil, nil } nodeTypes := make([]tgdb.TGNodeType, 0) for _, nodeType := range obj.nodeTypes { nodeTypes = append(nodeTypes, nodeType) } return nodeTypes, nil } func (obj *GraphMetadata) ReadExternal(is tgdb.TGInputStream) tgdb.TGError { return nil } func (obj *GraphMetadata) WriteExternal(os tgdb.TGOutputStream) tgdb.TGError { return nil } func (obj *GraphMetadata) MarshalBinary() ([]byte, error) { var b bytes.Buffer _, err := fmt.Fprintln(&b, obj.initialized, obj.descriptors, obj.descriptorsById, obj.edgeTypes, obj.edgeTypesById, obj.nodeTypes, obj.nodeTypesById, obj.graphObjFactory) if err != nil { logger.Error(fmt.Sprintf("ERROR: Returning GraphMetadata:MarshalBinary w/ Error: '%+v'", err.Error())) return nil, err } return b.Bytes(), nil } func (obj *GraphMetadata) UnmarshalBinary(data []byte) error { b := bytes.NewBuffer(data) _, err := fmt.Fscanln(b, &obj.initialized, &obj.descriptors, &obj.descriptorsById, &obj.edgeTypes, &obj.edgeTypesById, &obj.nodeTypes, &obj.nodeTypesById, &obj.graphObjFactory) if err != nil { logger.Error(fmt.Sprintf("ERROR: Returning GraphMetadata:UnmarshalBinary w/ Error: '%+v'", err.Error())) return err } return nil } func DefaultGraphObjectFactory() *GraphObjectFactory { gob.Register(GraphObjectFactory{}) newGraphObjectFactory := GraphObjectFactory{} return &newGraphObjectFactory } func NewGraphObjectFactory(conn tgdb.TGConnection) *GraphObjectFactory { newGraphObjectFactory := DefaultGraphObjectFactory() newGraphObjectFactory.graphMData = NewGraphMetadata(newGraphObjectFactory) newGraphObjectFactory.connection = conn return newGraphObjectFactory } func (obj *GraphObjectFactory) GetConnection() tgdb.TGConnection { return obj.connection } func (obj *GraphObjectFactory) GetGraphMetaData() *GraphMetadata { return obj.graphMData } func (obj *GraphObjectFactory) CreateCompositeKey(nodeTypeName string) (tgdb.TGKey, tgdb.TGError) { _, err := obj.graphMData.GetNodeType(nodeTypeName) if err != nil { logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateCompositeKey as node NOT found")) errMsg := fmt.Sprintf("Node desc with Name %s not found", nodeTypeName) return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } return NewCompositeKey(obj.graphMData, nodeTypeName), nil } func (obj *GraphObjectFactory) CreateEdgeWithEdgeType(fromNode tgdb.TGNode, toNode tgdb.TGNode, edgeType tgdb.TGEdgeType) (tgdb.TGEdge, tgdb.TGError) { newEdge := NewEdgeWithEdgeType(obj.graphMData, fromNode, toNode, edgeType) if newEdge.isInitialized != true { logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateEdgeWithEdgeType as edge in NOT initialized")) errMsg := fmt.Sprintf("Unable to create an edge with type %s", edgeType.(*EdgeType).Name) return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } fromNode.AddEdge(newEdge) toNode.AddEdge(newEdge) return newEdge, nil } func (obj *GraphObjectFactory) CreateEdgeWithDirection(fromNode tgdb.TGNode, toNode tgdb.TGNode, directionType tgdb.TGDirectionType) (tgdb.TGEdge, tgdb.TGError) { newEdge := NewEdgeWithDirection(obj.graphMData, fromNode, toNode, directionType) if newEdge.isInitialized != true { logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateEdgeWithDirection as edge in NOT initialized")) errMsg := fmt.Sprintf("Unable to create an edge with direction %s", directionType) return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } fromNode.AddEdge(newEdge) toNode.AddEdge(newEdge) return newEdge, nil } func (obj *GraphObjectFactory) CreateEntity(entityKind tgdb.TGEntityKind) (tgdb.TGEntity, tgdb.TGError) { switch entityKind { case tgdb.EntityKindNode: return NewNode(obj.graphMData), nil case tgdb.EntityKindEdge: return NewEdge(obj.graphMData), nil case tgdb.EntityKindGraph: return NewGraph(obj.graphMData), nil } logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateEntity as entity kind specified is INVALID")) errMsg := fmt.Sprintf("Invalid entity kind %d specified", entityKind) return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } func (obj *GraphObjectFactory) CreateEntityId(buf []byte) (tgdb.TGEntityId, tgdb.TGError) { return NewByteArrayEntity(buf), nil } func (obj *GraphObjectFactory) CreateGraph(name string) (tgdb.TGGraph, tgdb.TGError) { graph := NewGraphWithName(obj.graphMData, name) if graph.isInitialized != true { logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateGraph as graph in NOT initialized")) errMsg := fmt.Sprint("Unable to create a graph with this Graph Object Factory") return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } return graph, nil } func (obj *GraphObjectFactory) CreateNode() (tgdb.TGNode, tgdb.TGError) { node := NewNode(obj.graphMData) if node.isInitialized != true { logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateNode as node in NOT initialized")) errMsg := fmt.Sprint("Unable to create a node with this Graph Object Factory") return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } return node, nil } func (obj *GraphObjectFactory) CreateNodeInGraph(nodeType tgdb.TGNodeType) (tgdb.TGNode, tgdb.TGError) { node := NewNodeWithType(obj.graphMData, nodeType) if node.isInitialized != true { logger.Error(fmt.Sprint("ERROR: Returning GraphObjectFactory:CreateNodeInGraph as node in NOT initialized")) errMsg := fmt.Sprint("Unable to create a node with this Graph Object Factory") return nil, GetErrorByType(TGErrorGeneralException, INTERNAL_SERVER_ERROR, errMsg, "") } return node, nil } func (obj *GraphObjectFactory) MarshalBinary() ([]byte, error) { var b bytes.Buffer _, err := fmt.Fprintln(&b, obj.graphMData, obj.connection) if err != nil { logger.Error(fmt.Sprintf("ERROR: Returning GraphObjectFactory:MarshalBinary w/ Error: '%+v'", err.Error())) return nil, err } return b.Bytes(), nil } func (obj *GraphObjectFactory) UnmarshalBinary(data []byte) error { b := bytes.NewBuffer(data) _, err := fmt.Fscanln(b, &obj.graphMData, &obj.connection) if err != nil { logger.Error(fmt.Sprintf("ERROR: Returning GraphObjectFactory:UnmarshalBinary w/ Error: '%+v'", err.Error())) return err } return nil } type Graph struct { *Node name string } func DefaultGraph() *Graph { gob.Register(Graph{}) newGraph := Graph{ Node: DefaultNode(), } newGraph.EntityKind = tgdb.EntityKindGraph return &newGraph } func NewGraph(gmd *GraphMetadata) *Graph { newGraph := DefaultGraph() newGraph.graphMetadata = gmd return newGraph } func NewGraphWithName(gmd *GraphMetadata, name string) *Graph { newGraph := NewGraph(gmd) newGraph.name = name return newGraph } func (obj *Graph) GetModifiedAttributes() []tgdb.TGAttribute { return obj.getModifiedAttributes() } func (obj *Graph) GetName() string { return obj.name } func (obj *Graph) SetName(name string) { obj.name = name } func (obj *Graph) AddNode(node tgdb.TGNode) (tgdb.TGGraph, tgdb.TGError) { return obj, nil } func (obj *Graph) AddEdges(edges []tgdb.TGEdge) (tgdb.TGGraph, tgdb.TGError) { return obj, nil } func (obj *Graph) GetNode(filter tgdb.TGFilter) (tgdb.TGNode, tgdb.TGError) { return nil, nil } func (obj *Graph) ListNodes(filter tgdb.TGFilter, recurseAllSubGraphs bool) (tgdb.TGNode, tgdb.TGError) { return nil, nil } func (obj *Graph) CreateGraph(name string) (tgdb.TGGraph, tgdb.TGError) { return nil, nil } func (obj *Graph) RemoveGraph(name string) (tgdb.TGGraph, tgdb.TGError) { return nil, nil } func (obj *Graph) RemoveNode(node tgdb.TGNode) (tgdb.TGGraph, tgdb.TGError) { return nil, nil } func (obj *Graph) RemoveNodes(filter tgdb.TGFilter) int { return 0 } func (obj *Graph) AddEdge(edge tgdb.TGEdge) { obj.Edges = append(obj.Edges, edge) } func (obj *Graph) AddEdgeWithDirectionType(node tgdb.TGNode, edgeType tgdb.TGEdgeType, directionType tgdb.TGDirectionType) tgdb.TGEdge { newEdge := NewEdgeWithDirection(obj.graphMetadata, obj, node, directionType) obj.AddEdge(newEdge) return newEdge } func (obj *Graph) GetEdges() []tgdb.TGEdge { return obj.Edges } func (obj *Graph) GetEdgesForDirectionType(directionType tgdb.TGDirectionType) []tgdb.TGEdge { edgesWithDirections := make([]tgdb.TGEdge, 0) if len(obj.Edges) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning Graph:GetEdgesForDirectionType as there are NO edges")) return edgesWithDirections } for _, edge := range obj.Edges { if edge.(*Edge).directionType == directionType { edgesWithDirections = append(edgesWithDirections, edge) } } return edgesWithDirections } func (obj *Graph) GetEdgesForEdgeType(edgeType tgdb.TGEdgeType, direction tgdb.TGDirection) []tgdb.TGEdge { edgesWithDirections := make([]tgdb.TGEdge, 0) if len(obj.Edges) == 0 { logger.Warning(fmt.Sprint("WARNING: Returning Graph:GetEdgesForEdgeType as there are NO edges")) return edgesWithDirections } if edgeType == nil && direction == tgdb.DirectionAny { for _, edge := range obj.Edges { if edge.(*Edge).GetIsInitialized() { edgesWithDirections = append(edgesWithDirections, edge) } } if logger.IsDebug() { logger.Debug(fmt.Sprint("Returning Graph:GetEdgesForEdgeType w/ all edges of ANY directions")) } return obj.Edges } for _, edge := range obj.Edges { if !edge.(*Edge).GetIsInitialized() { logger.Warning(fmt.Sprintf("WARNING: Returning Graph:GetEdgesForEdgeType - skipping uninitialized edge '%+v'", edge)) continue } eType := edge.GetEntityType() if edgeType != nil && eType != nil && eType.GetName() != edgeType.GetName() { logger.Warning(fmt.Sprintf("WARNING: Returning Graph:GetEdgesForEdgeType - skipping (entity type NOT matching) edge '%+v'", edge)) continue } if direction == tgdb.DirectionAny { edgesWithDirections = append(edgesWithDirections, edge) } else if direction == tgdb.DirectionOutbound { edgesForThisNode := edge.GetVertices() if obj.GetVirtualId() == edgesForThisNode[0].GetVirtualId() { edgesWithDirections = append(edgesWithDirections, edge) } } else { edgesForThisNode := edge.GetVertices() if obj.GetVirtualId() == edgesForThisNode[1].GetVirtualId() { edgesWithDirections = append(edgesWithDirections, edge) } } } return edgesWithDirections } func (obj *Graph) GetAttribute(attrName string) tgdb.TGAttribute { return obj.getAttribute(attrName) } func (obj *Graph) GetAttributes() ([]tgdb.TGAttribute, tgdb.TGError) { return obj.getAttributes() } func (obj *Graph) GetEntityKind() tgdb.TGEntityKind { return obj.getEntityKind() } func (obj *Graph) GetEntityType() tgdb.TGEntityType { return obj.getEntityType() } func (obj *Graph) GetGraphMetadata() tgdb.TGGraphMetadata { return obj.getGraphMetadata() } func (obj *Graph) GetIsDeleted() bool { return obj.getIsDeleted() } func (obj *Graph) GetIsNew() bool { return obj.getIsNew() } func (obj *Graph) GetVersion() int { return obj.getVersion() } func (obj *Graph) GetVirtualId() int64 { return obj.getVirtualId() } func (obj *Graph) IsAttributeSet(attrName string) bool { return obj.isAttributeSet(attrName) }
Apache License 2.0
dolthub/go-mysql-server
sql/plan/process.go
PartitionRows
go
func (t *ProcessIndexableTable) PartitionRows(ctx *sql.Context, p sql.Partition) (sql.RowIter, error) { iter, err := t.DriverIndexableTable.PartitionRows(ctx, p) if err != nil { return nil, err } partitionName := partitionName(p) if t.OnPartitionStart != nil { t.OnPartitionStart(partitionName) } var onDone NotifyFunc if t.OnPartitionDone != nil { onDone = func() { t.OnPartitionDone(partitionName) } } var onNext NotifyFunc if t.OnRowNext != nil { onNext = func() { t.OnRowNext(partitionName) } } return &trackedRowIter{iter: iter, onNext: onNext, onDone: onDone}, nil }
PartitionRows implements the sql.Table interface.
https://github.com/dolthub/go-mysql-server/blob/057afd4733540f3ad2eb15968d16ce9bae082063/sql/plan/process.go#L166-L192
package plan import ( "fmt" "github.com/dolthub/go-mysql-server/sql" ) type QueryProcess struct { UnaryNode Notify NotifyFunc } type NotifyFunc func() func NewQueryProcess(node sql.Node, notify NotifyFunc) *QueryProcess { return &QueryProcess{UnaryNode{Child: node}, notify} } func (p *QueryProcess) WithChildren(children ...sql.Node) (sql.Node, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(p, len(children), 1) } return NewQueryProcess(children[0], p.Notify), nil } func (p *QueryProcess) RowIter(ctx *sql.Context, row sql.Row) (sql.RowIter, error) { iter, err := p.Child.RowIter(ctx, row) if err != nil { return nil, err } qType := getQueryType(p.Child) return &trackedRowIter{ node: p.Child, iter: iter, onDone: p.Notify, queryType: qType, shouldSetFoundRows: qType == queryTypeSelect && p.shouldSetFoundRows(), }, nil } func getQueryType(child sql.Node) queryType { var queryType queryType = queryTypeSelect Inspect(child, func(node sql.Node) bool { if IsNoRowNode(node) { queryType = queryTypeDdl return false } switch node.(type) { case *Signal: queryType = queryTypeDdl return false case nil: return false case *TriggerExecutor, *InsertInto, *Update, *DeleteFrom, *LoadData: queryType = queryTypeUpdate return false } return true }) return queryType } func (p *QueryProcess) String() string { return p.Child.String() } func (p *QueryProcess) DebugString() string { tp := sql.NewTreePrinter() _ = tp.WriteNode("QueryProcess") _ = tp.WriteChildren(sql.DebugString(p.Child)) return tp.String() } func (p *QueryProcess) shouldSetFoundRows() bool { var limit *Limit Inspect(p.Child, func(n sql.Node) bool { switch n := n.(type) { case *StartTransaction: return true case *Limit: limit = n return false default: return false } }) if limit == nil { return true } return !limit.CalcFoundRows } type ProcessIndexableTable struct { sql.DriverIndexableTable OnPartitionDone NamedNotifyFunc OnPartitionStart NamedNotifyFunc OnRowNext NamedNotifyFunc } func (t *ProcessIndexableTable) DebugString() string { tp := sql.NewTreePrinter() _ = tp.WriteNode("ProcessIndexableTable") _ = tp.WriteChildren(sql.DebugString(t.Underlying())) return tp.String() } func NewProcessIndexableTable(t sql.DriverIndexableTable, onPartitionDone, onPartitionStart, OnRowNext NamedNotifyFunc) *ProcessIndexableTable { return &ProcessIndexableTable{t, onPartitionDone, onPartitionStart, OnRowNext} } func (t *ProcessIndexableTable) Underlying() sql.Table { return t.DriverIndexableTable } func (t *ProcessIndexableTable) IndexKeyValues( ctx *sql.Context, columns []string, ) (sql.PartitionIndexKeyValueIter, error) { iter, err := t.DriverIndexableTable.IndexKeyValues(ctx, columns) if err != nil { return nil, err } return &trackedPartitionIndexKeyValueIter{iter, t.OnPartitionDone, t.OnPartitionStart, t.OnRowNext}, nil }
Apache License 2.0
baetyl/baetyl-cloud
mock/plugin/resource.go
GetApplication
go
func (mr *MockResourceMockRecorder) GetApplication(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetApplication", reflect.TypeOf((*MockResource)(nil).GetApplication), arg0, arg1, arg2) }
GetApplication indicates an expected call of GetApplication
https://github.com/baetyl/baetyl-cloud/blob/cd33101ae4b1c43b5d5db2c86857972bc03174d0/mock/plugin/resource.go#L221-L224
package plugin import ( models "github.com/baetyl/baetyl-cloud/v2/models" v1 "github.com/baetyl/baetyl-go/v2/spec/v1" gomock "github.com/golang/mock/gomock" reflect "reflect" ) type MockResource struct { ctrl *gomock.Controller recorder *MockResourceMockRecorder } type MockResourceMockRecorder struct { mock *MockResource } func NewMockResource(ctrl *gomock.Controller) *MockResource { mock := &MockResource{ctrl: ctrl} mock.recorder = &MockResourceMockRecorder{mock} return mock } func (m *MockResource) EXPECT() *MockResourceMockRecorder { return m.recorder } func (m *MockResource) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) return ret0 } func (mr *MockResourceMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockResource)(nil).Close)) } func (m *MockResource) CountAllNode(arg0 interface{}) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CountAllNode", arg0) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockResourceMockRecorder) CountAllNode(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountAllNode", reflect.TypeOf((*MockResource)(nil).CountAllNode), arg0) } func (m *MockResource) CreateApplication(arg0 interface{}, arg1 string, arg2 *v1.Application) (*v1.Application, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateApplication", arg0, arg1, arg2) ret0, _ := ret[0].(*v1.Application) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockResourceMockRecorder) CreateApplication(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateApplication", reflect.TypeOf((*MockResource)(nil).CreateApplication), arg0, arg1, arg2) } func (m *MockResource) CreateConfig(arg0 interface{}, arg1 string, arg2 *v1.Configuration) (*v1.Configuration, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateConfig", arg0, arg1, arg2) ret0, _ := ret[0].(*v1.Configuration) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockResourceMockRecorder) CreateConfig(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfig", reflect.TypeOf((*MockResource)(nil).CreateConfig), arg0, arg1, arg2) } func (m *MockResource) CreateNamespace(arg0 *models.Namespace) (*models.Namespace, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateNamespace", arg0) ret0, _ := ret[0].(*models.Namespace) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockResourceMockRecorder) CreateNamespace(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNamespace", reflect.TypeOf((*MockResource)(nil).CreateNamespace), arg0) } func (m *MockResource) CreateNode(arg0 interface{}, arg1 string, arg2 *v1.Node) (*v1.Node, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateNode", arg0, arg1, arg2) ret0, _ := ret[0].(*v1.Node) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockResourceMockRecorder) CreateNode(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNode", reflect.TypeOf((*MockResource)(nil).CreateNode), arg0, arg1, arg2) } func (m *MockResource) CreateSecret(arg0 interface{}, arg1 string, arg2 *v1.Secret) (*v1.Secret, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateSecret", arg0, arg1, arg2) ret0, _ := ret[0].(*v1.Secret) ret1, _ := ret[1].(error) return ret0, ret1 } func (mr *MockResourceMockRecorder) CreateSecret(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSecret", reflect.TypeOf((*MockResource)(nil).CreateSecret), arg0, arg1, arg2) } func (m *MockResource) DeleteApplication(arg0 interface{}, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteApplication", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } func (mr *MockResourceMockRecorder) DeleteApplication(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteApplication", reflect.TypeOf((*MockResource)(nil).DeleteApplication), arg0, arg1, arg2) } func (m *MockResource) DeleteConfig(arg0 interface{}, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteConfig", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } func (mr *MockResourceMockRecorder) DeleteConfig(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfig", reflect.TypeOf((*MockResource)(nil).DeleteConfig), arg0, arg1, arg2) } func (m *MockResource) DeleteNamespace(arg0 *models.Namespace) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteNamespace", arg0) ret0, _ := ret[0].(error) return ret0 } func (mr *MockResourceMockRecorder) DeleteNamespace(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteNamespace", reflect.TypeOf((*MockResource)(nil).DeleteNamespace), arg0) } func (m *MockResource) DeleteNode(arg0 interface{}, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteNode", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } func (mr *MockResourceMockRecorder) DeleteNode(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteNode", reflect.TypeOf((*MockResource)(nil).DeleteNode), arg0, arg1, arg2) } func (m *MockResource) DeleteSecret(arg0, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteSecret", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } func (mr *MockResourceMockRecorder) DeleteSecret(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSecret", reflect.TypeOf((*MockResource)(nil).DeleteSecret), arg0, arg1) } func (m *MockResource) GetApplication(arg0, arg1, arg2 string) (*v1.Application, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetApplication", arg0, arg1, arg2) ret0, _ := ret[0].(*v1.Application) ret1, _ := ret[1].(error) return ret0, ret1 }
Apache License 2.0
riking/autodelete
vendor/github.com/bwmarrin/discordgo/eventhandlers.go
Handle
go
func (eh connectEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*Connect); ok { eh(s, t) } }
Handle is the handler for Connect events.
https://github.com/riking/autodelete/blob/fc0885ae8208bd55f84cd695966a92af4ed0d76f/vendor/github.com/bwmarrin/discordgo/eventhandlers.go#L145-L149
package discordgo const ( channelCreateEventType = "CHANNEL_CREATE" channelDeleteEventType = "CHANNEL_DELETE" channelPinsUpdateEventType = "CHANNEL_PINS_UPDATE" channelUpdateEventType = "CHANNEL_UPDATE" connectEventType = "__CONNECT__" disconnectEventType = "__DISCONNECT__" eventEventType = "__EVENT__" guildBanAddEventType = "GUILD_BAN_ADD" guildBanRemoveEventType = "GUILD_BAN_REMOVE" guildCreateEventType = "GUILD_CREATE" guildDeleteEventType = "GUILD_DELETE" guildEmojisUpdateEventType = "GUILD_EMOJIS_UPDATE" guildIntegrationsUpdateEventType = "GUILD_INTEGRATIONS_UPDATE" guildMemberAddEventType = "GUILD_MEMBER_ADD" guildMemberRemoveEventType = "GUILD_MEMBER_REMOVE" guildMemberUpdateEventType = "GUILD_MEMBER_UPDATE" guildMembersChunkEventType = "GUILD_MEMBERS_CHUNK" guildRoleCreateEventType = "GUILD_ROLE_CREATE" guildRoleDeleteEventType = "GUILD_ROLE_DELETE" guildRoleUpdateEventType = "GUILD_ROLE_UPDATE" guildUpdateEventType = "GUILD_UPDATE" messageAckEventType = "MESSAGE_ACK" messageCreateEventType = "MESSAGE_CREATE" messageDeleteEventType = "MESSAGE_DELETE" messageDeleteBulkEventType = "MESSAGE_DELETE_BULK" messageReactionAddEventType = "MESSAGE_REACTION_ADD" messageReactionRemoveEventType = "MESSAGE_REACTION_REMOVE" messageReactionRemoveAllEventType = "MESSAGE_REACTION_REMOVE_ALL" messageUpdateEventType = "MESSAGE_UPDATE" presenceUpdateEventType = "PRESENCE_UPDATE" presencesReplaceEventType = "PRESENCES_REPLACE" rateLimitEventType = "__RATE_LIMIT__" readyEventType = "READY" relationshipAddEventType = "RELATIONSHIP_ADD" relationshipRemoveEventType = "RELATIONSHIP_REMOVE" resumedEventType = "RESUMED" typingStartEventType = "TYPING_START" userGuildSettingsUpdateEventType = "USER_GUILD_SETTINGS_UPDATE" userNoteUpdateEventType = "USER_NOTE_UPDATE" userSettingsUpdateEventType = "USER_SETTINGS_UPDATE" userUpdateEventType = "USER_UPDATE" voiceServerUpdateEventType = "VOICE_SERVER_UPDATE" voiceStateUpdateEventType = "VOICE_STATE_UPDATE" webhooksUpdateEventType = "WEBHOOKS_UPDATE" ) type channelCreateEventHandler func(*Session, *ChannelCreate) func (eh channelCreateEventHandler) Type() string { return channelCreateEventType } func (eh channelCreateEventHandler) New() interface{} { return &ChannelCreate{} } func (eh channelCreateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelCreate); ok { eh(s, t) } } type channelDeleteEventHandler func(*Session, *ChannelDelete) func (eh channelDeleteEventHandler) Type() string { return channelDeleteEventType } func (eh channelDeleteEventHandler) New() interface{} { return &ChannelDelete{} } func (eh channelDeleteEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelDelete); ok { eh(s, t) } } type channelPinsUpdateEventHandler func(*Session, *ChannelPinsUpdate) func (eh channelPinsUpdateEventHandler) Type() string { return channelPinsUpdateEventType } func (eh channelPinsUpdateEventHandler) New() interface{} { return &ChannelPinsUpdate{} } func (eh channelPinsUpdateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelPinsUpdate); ok { eh(s, t) } } type channelUpdateEventHandler func(*Session, *ChannelUpdate) func (eh channelUpdateEventHandler) Type() string { return channelUpdateEventType } func (eh channelUpdateEventHandler) New() interface{} { return &ChannelUpdate{} } func (eh channelUpdateEventHandler) Handle(s *Session, i interface{}) { if t, ok := i.(*ChannelUpdate); ok { eh(s, t) } } type connectEventHandler func(*Session, *Connect) func (eh connectEventHandler) Type() string { return connectEventType }
Apache License 2.0
luksa/statefulset-scaledown-controller
vendor/k8s.io/client-go/kubernetes/typed/apps/v1/fake/fake_replicaset.go
Get
go
func (c *FakeReplicaSets) Get(name string, options v1.GetOptions) (result *apps_v1.ReplicaSet, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(replicasetsResource, c.ns, name), &apps_v1.ReplicaSet{}) if obj == nil { return nil, err } return obj.(*apps_v1.ReplicaSet), err }
Get takes name of the replicaSet, and returns the corresponding replicaSet object, and an error if there is any.
https://github.com/luksa/statefulset-scaledown-controller/blob/22d2e550e4c8272bab437fa0532394c4fb14fbd7/vendor/k8s.io/client-go/kubernetes/typed/apps/v1/fake/fake_replicaset.go#L42-L50
package fake import ( apps_v1 "k8s.io/api/apps/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" ) type FakeReplicaSets struct { Fake *FakeAppsV1 ns string } var replicasetsResource = schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "replicasets"} var replicasetsKind = schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "ReplicaSet"}
Apache License 2.0
monzo/phosphor
phosphor/marshaling.go
protoToAnnotationType
go
func protoToAnnotationType(p traceproto.AnnotationType) AnnotationType { at := int32(p) if at > 6 || at < 1 { at = 0 } return AnnotationType(at) }
protoToAnnotationType converts a annotation type in our proto to our domain
https://github.com/monzo/phosphor/blob/ee1fad17320ae707e9a72ab037f17514e0d53fb9/phosphor/marshaling.go#L86-L94
package phosphor import ( "sort" "time" "github.com/mondough/phosphor/proto" ) func prettyFormatTrace(t *Trace) interface{} { return map[string]interface{}{ "annotations": formatAnnotations(t.Annotation), } } func formatAnnotations(ans []*Annotation) interface{} { sort.Sort(ByTime(ans)) pa := AnnotationsToProto(ans) m := make([]interface{}, 0, len(pa)) for _, a := range pa { m = append(m, formatAnnotation(a)) } return m } func formatAnnotation(a *traceproto.Annotation) interface{} { return map[string]interface{}{ "trace_id": a.TraceId, "span_id": a.SpanId, "parent_id": a.ParentId, "type": a.Type.String(), "async": a.Async, "timestamp": a.Timestamp, "duration": a.Duration, "hostname": a.Hostname, "origin": a.Origin, "destination": a.Destination, "payload": a.Payload, "key_value": a.KeyValue, } } type ByTime []*Annotation func (s ByTime) Len() int { return len(s) } func (s ByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s ByTime) Less(i, j int) bool { return s[i].Timestamp.Before(s[j].Timestamp) } func ProtoToAnnotation(p *traceproto.Annotation) *Annotation { if p == nil { return &Annotation{} } return &Annotation{ TraceId: p.TraceId, SpanId: p.SpanId, ParentSpanId: p.ParentId, Timestamp: microsecondInt64ToTime(p.Timestamp), Duration: microsecondInt64ToDuration(p.Duration), Hostname: p.Hostname, Origin: p.Origin, Destination: p.Destination, AnnotationType: protoToAnnotationType(p.Type), Async: p.Async, Payload: p.Payload, PayloadSize: int32(len(p.Payload)), KeyValue: protoToKeyValue(p.KeyValue), } }
Apache License 2.0
crossplane/crossplane-runtime
apis/common/v1/zz_generated.deepcopy.go
DeepCopy
go
func (in *Selector) DeepCopy() *Selector { if in == nil { return nil } out := new(Selector) in.DeepCopyInto(out) return out }
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Selector.
https://github.com/crossplane/crossplane-runtime/blob/bf5d5512c2f236535c7758f3eaf59c5414c6cf78/apis/common/v1/zz_generated.deepcopy.go#L308-L315
package v1 import ( corev1 "k8s.io/api/core/v1" ) func (in *CommonCredentialSelectors) DeepCopyInto(out *CommonCredentialSelectors) { *out = *in if in.Fs != nil { in, out := &in.Fs, &out.Fs *out = new(FsSelector) **out = **in } if in.Env != nil { in, out := &in.Env, &out.Env *out = new(EnvSelector) **out = **in } if in.SecretRef != nil { in, out := &in.SecretRef, &out.SecretRef *out = new(SecretKeySelector) **out = **in } } func (in *CommonCredentialSelectors) DeepCopy() *CommonCredentialSelectors { if in == nil { return nil } out := new(CommonCredentialSelectors) in.DeepCopyInto(out) return out } func (in *Condition) DeepCopyInto(out *Condition) { *out = *in in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) } func (in *Condition) DeepCopy() *Condition { if in == nil { return nil } out := new(Condition) in.DeepCopyInto(out) return out } func (in *ConditionedStatus) DeepCopyInto(out *ConditionedStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } func (in *ConditionedStatus) DeepCopy() *ConditionedStatus { if in == nil { return nil } out := new(ConditionedStatus) in.DeepCopyInto(out) return out } func (in *EnvSelector) DeepCopyInto(out *EnvSelector) { *out = *in } func (in *EnvSelector) DeepCopy() *EnvSelector { if in == nil { return nil } out := new(EnvSelector) in.DeepCopyInto(out) return out } func (in *FsSelector) DeepCopyInto(out *FsSelector) { *out = *in } func (in *FsSelector) DeepCopy() *FsSelector { if in == nil { return nil } out := new(FsSelector) in.DeepCopyInto(out) return out } func (in *LocalSecretReference) DeepCopyInto(out *LocalSecretReference) { *out = *in } func (in *LocalSecretReference) DeepCopy() *LocalSecretReference { if in == nil { return nil } out := new(LocalSecretReference) in.DeepCopyInto(out) return out } func (in *MergeOptions) DeepCopyInto(out *MergeOptions) { *out = *in if in.KeepMapValues != nil { in, out := &in.KeepMapValues, &out.KeepMapValues *out = new(bool) **out = **in } if in.AppendSlice != nil { in, out := &in.AppendSlice, &out.AppendSlice *out = new(bool) **out = **in } } func (in *MergeOptions) DeepCopy() *MergeOptions { if in == nil { return nil } out := new(MergeOptions) in.DeepCopyInto(out) return out } func (in *ProviderConfigStatus) DeepCopyInto(out *ProviderConfigStatus) { *out = *in in.ConditionedStatus.DeepCopyInto(&out.ConditionedStatus) } func (in *ProviderConfigStatus) DeepCopy() *ProviderConfigStatus { if in == nil { return nil } out := new(ProviderConfigStatus) in.DeepCopyInto(out) return out } func (in *ProviderConfigUsage) DeepCopyInto(out *ProviderConfigUsage) { *out = *in out.ProviderConfigReference = in.ProviderConfigReference out.ResourceReference = in.ResourceReference } func (in *ProviderConfigUsage) DeepCopy() *ProviderConfigUsage { if in == nil { return nil } out := new(ProviderConfigUsage) in.DeepCopyInto(out) return out } func (in *Reference) DeepCopyInto(out *Reference) { *out = *in } func (in *Reference) DeepCopy() *Reference { if in == nil { return nil } out := new(Reference) in.DeepCopyInto(out) return out } func (in *ResourceSpec) DeepCopyInto(out *ResourceSpec) { *out = *in if in.WriteConnectionSecretToReference != nil { in, out := &in.WriteConnectionSecretToReference, &out.WriteConnectionSecretToReference *out = new(SecretReference) **out = **in } if in.ProviderConfigReference != nil { in, out := &in.ProviderConfigReference, &out.ProviderConfigReference *out = new(Reference) **out = **in } if in.ProviderReference != nil { in, out := &in.ProviderReference, &out.ProviderReference *out = new(Reference) **out = **in } } func (in *ResourceSpec) DeepCopy() *ResourceSpec { if in == nil { return nil } out := new(ResourceSpec) in.DeepCopyInto(out) return out } func (in *ResourceStatus) DeepCopyInto(out *ResourceStatus) { *out = *in in.ConditionedStatus.DeepCopyInto(&out.ConditionedStatus) } func (in *ResourceStatus) DeepCopy() *ResourceStatus { if in == nil { return nil } out := new(ResourceStatus) in.DeepCopyInto(out) return out } func (in *SecretKeySelector) DeepCopyInto(out *SecretKeySelector) { *out = *in out.SecretReference = in.SecretReference } func (in *SecretKeySelector) DeepCopy() *SecretKeySelector { if in == nil { return nil } out := new(SecretKeySelector) in.DeepCopyInto(out) return out } func (in *SecretReference) DeepCopyInto(out *SecretReference) { *out = *in } func (in *SecretReference) DeepCopy() *SecretReference { if in == nil { return nil } out := new(SecretReference) in.DeepCopyInto(out) return out } func (in *Selector) DeepCopyInto(out *Selector) { *out = *in if in.MatchLabels != nil { in, out := &in.MatchLabels, &out.MatchLabels *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.MatchControllerRef != nil { in, out := &in.MatchControllerRef, &out.MatchControllerRef *out = new(bool) **out = **in } }
Apache License 2.0
chris-wood/odoh-server
vendor/github.com/elastic/go-elasticsearch/v8/esapi/api.xpack.monitoring.bulk.go
WithErrorTrace
go
func (f MonitoringBulk) WithErrorTrace() func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.ErrorTrace = true } }
WithErrorTrace includes the stack trace for errors in the response body.
https://github.com/chris-wood/odoh-server/blob/0e65d7b6ffd1e3261e713344771fa9df2b17725b/vendor/github.com/elastic/go-elasticsearch/v8/esapi/api.xpack.monitoring.bulk.go#L213-L217
package esapi import ( "context" "io" "net/http" "strings" ) func newMonitoringBulkFunc(t Transport) MonitoringBulk { return func(body io.Reader, o ...func(*MonitoringBulkRequest)) (*Response, error) { var r = MonitoringBulkRequest{Body: body} for _, f := range o { f(&r) } return r.Do(r.ctx, t) } } type MonitoringBulk func(body io.Reader, o ...func(*MonitoringBulkRequest)) (*Response, error) type MonitoringBulkRequest struct { Body io.Reader DocumentType string Interval string SystemAPIVersion string SystemID string Pretty bool Human bool ErrorTrace bool FilterPath []string Header http.Header ctx context.Context } func (r MonitoringBulkRequest) Do(ctx context.Context, transport Transport) (*Response, error) { var ( method string path strings.Builder params map[string]string ) method = "POST" path.Grow(1 + len("_monitoring") + 1 + len(r.DocumentType) + 1 + len("bulk")) path.WriteString("/") path.WriteString("_monitoring") if r.DocumentType != "" { path.WriteString("/") path.WriteString(r.DocumentType) } path.WriteString("/") path.WriteString("bulk") params = make(map[string]string) if r.Interval != "" { params["interval"] = r.Interval } if r.SystemAPIVersion != "" { params["system_api_version"] = r.SystemAPIVersion } if r.SystemID != "" { params["system_id"] = r.SystemID } if r.Pretty { params["pretty"] = "true" } if r.Human { params["human"] = "true" } if r.ErrorTrace { params["error_trace"] = "true" } if len(r.FilterPath) > 0 { params["filter_path"] = strings.Join(r.FilterPath, ",") } req, err := newRequest(method, path.String(), r.Body) if err != nil { return nil, err } if len(params) > 0 { q := req.URL.Query() for k, v := range params { q.Set(k, v) } req.URL.RawQuery = q.Encode() } if r.Body != nil { req.Header[headerContentType] = headerContentTypeJSON } if len(r.Header) > 0 { if len(req.Header) == 0 { req.Header = r.Header } else { for k, vv := range r.Header { for _, v := range vv { req.Header.Add(k, v) } } } } if ctx != nil { req = req.WithContext(ctx) } res, err := transport.Perform(req) if err != nil { return nil, err } response := Response{ StatusCode: res.StatusCode, Body: res.Body, Header: res.Header, } return &response, nil } func (f MonitoringBulk) WithContext(v context.Context) func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.ctx = v } } func (f MonitoringBulk) WithDocumentType(v string) func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.DocumentType = v } } func (f MonitoringBulk) WithInterval(v string) func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.Interval = v } } func (f MonitoringBulk) WithSystemAPIVersion(v string) func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.SystemAPIVersion = v } } func (f MonitoringBulk) WithSystemID(v string) func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.SystemID = v } } func (f MonitoringBulk) WithPretty() func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.Pretty = true } } func (f MonitoringBulk) WithHuman() func(*MonitoringBulkRequest) { return func(r *MonitoringBulkRequest) { r.Human = true } }
MIT License
peak/s5cmd
vendor/github.com/johannesboyne/gofakes3/internal/goskipiter/iter.go
Close
go
func (iter *Iterator) Close() { iter.inner.Close() }
Close this iterator to reap resources associated with it. While not strictly required, it will provide extra hints for the garbage collector.
https://github.com/peak/s5cmd/blob/fd03f6e870d09e9ecc2565f7751fefe366297134/vendor/github.com/johannesboyne/gofakes3/internal/goskipiter/iter.go#L64-L66
package goskipiter import "github.com/ryszard/goskiplist/skiplist" type Iterator struct { inner skiplist.Iterator didSeek bool seekWasOK bool } func New(inner skiplist.Iterator) *Iterator { return &Iterator{inner: inner} } func (iter *Iterator) Next() (ok bool) { if iter.didSeek { iter.didSeek = false return iter.seekWasOK } else { return iter.inner.Next() } } func (iter *Iterator) Previous() (ok bool) { if iter.didSeek { panic("not implemented") } return iter.inner.Previous() } func (iter *Iterator) Key() interface{} { return iter.inner.Key() } func (iter *Iterator) Value() interface{} { return iter.inner.Value() } func (iter *Iterator) Seek(key interface{}) (ok bool) { iter.didSeek = true ok = iter.inner.Seek(key) iter.seekWasOK = ok return ok }
MIT License
istio/old_pilot_repo
proxy/agent_test.go
TestExceedBudget
go
func TestExceedBudget(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) retry := 0 start := func(config interface{}, epoch int, _ <-chan error) error { if epoch == 0 && retry == 0 { retry++ return fmt.Errorf("error on try %d", retry) } else if epoch == 0 && retry == 1 { retry++ return fmt.Errorf("error on try %d", retry) } else { t.Errorf("Unexpected epoch %d and retry %d", epoch, retry) cancel() } return nil } cleanup := func(epoch int) { if epoch == 0 && (retry == 0 || retry == 1 || retry == 2) { } else { t.Errorf("Unexpected epoch %d and retry %d", epoch, retry) cancel() } } retryDelay := testRetry retryDelay.MaxRetries = 1 a := NewAgent(TestProxy{start, cleanup, func(_ interface{}) { cancel() }}, retryDelay) go a.Run(ctx) a.ScheduleConfigUpdate("test") <-ctx.Done() }
TestExceedBudget drives to permanent failure
https://github.com/istio/old_pilot_repo/blob/328700a0b55e097df7490e1fa7a0afdc24d80828/proxy/agent_test.go#L221-L250
package proxy import ( "context" "errors" "fmt" "testing" "time" ) var ( testRetry = Retry{ InitialInterval: time.Millisecond, MaxRetries: 10, } ) type TestProxy struct { run func(interface{}, int, <-chan error) error cleanup func(int) panic func(interface{}) } func (tp TestProxy) Run(config interface{}, epoch int, stop <-chan error) error { return tp.run(config, epoch, stop) } func (tp TestProxy) Cleanup(epoch int) { if tp.cleanup != nil { tp.cleanup(epoch) } } func (tp TestProxy) Panic(config interface{}) { if tp.panic != nil { tp.panic(config) } } func TestStartStop(t *testing.T) { current := -1 ctx, cancel := context.WithCancel(context.Background()) desired := "config" start := func(config interface{}, epoch int, _ <-chan error) error { if current != -1 { t.Error("Expected epoch not to be set") } if epoch != 0 { t.Error("Expected initial epoch to be 0") } if config != desired { t.Errorf("Start got config %v, want %v", config, desired) } current = epoch return nil } cleanup := func(epoch int) { if current != 0 { t.Error("Expected epoch to be set") } if epoch != 0 { t.Error("Expected initial epoch in cleanup to be 0") } cancel() } a := NewAgent(TestProxy{start, cleanup, nil}, testRetry) go a.Run(ctx) a.ScheduleConfigUpdate(desired) <-ctx.Done() } func TestApplyTwice(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) desired := "config" start := func(config interface{}, epoch int, _ <-chan error) error { if epoch == 1 { t.Error("Should start only once for same config") } <-ctx.Done() return nil } cleanup := func(epoch int) {} a := NewAgent(TestProxy{start, cleanup, nil}, testRetry) go a.Run(ctx) a.ScheduleConfigUpdate(desired) a.ScheduleConfigUpdate(desired) cancel() } func TestApplyThrice(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) good := "good" bad := "bad" applied := false var a Agent start := func(config interface{}, epoch int, _ <-chan error) error { if config == bad { return nil } if config == good && applied { t.Errorf("Config has already been applied") } applied = true <-ctx.Done() return nil } cleanup := func(epoch int) { if epoch == 1 { go func() { a.ScheduleConfigUpdate(good) cancel() }() } else if epoch != 0 { t.Errorf("Unexpected epoch %d", epoch) } } retry := testRetry retry.MaxRetries = 0 a = NewAgent(TestProxy{start, cleanup, nil}, retry) go a.Run(ctx) a.ScheduleConfigUpdate(good) a.ScheduleConfigUpdate(bad) <-ctx.Done() } func TestAbort(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) good1 := "good1" aborted1 := false good2 := "good2" aborted2 := false bad := "bad" active := 3 start := func(config interface{}, epoch int, abort <-chan error) error { if config == bad { return errors.New(bad) } select { case err := <-abort: if config == good1 { aborted1 = true } else if config == good2 { aborted2 = true } return err case <-ctx.Done(): } return nil } cleanup := func(epoch int) { active = active - 1 if active == 0 { if !aborted1 { t.Error("Expected first epoch to be aborted") } if !aborted2 { t.Error("Expected second epoch to be aborted") } cancel() } } retry := testRetry retry.InitialInterval = 10 * time.Second a := NewAgent(TestProxy{start, cleanup, nil}, retry) go a.Run(ctx) a.ScheduleConfigUpdate(good1) a.ScheduleConfigUpdate(good2) a.ScheduleConfigUpdate(bad) <-ctx.Done() } func TestStartFail(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) retry := 0 start := func(config interface{}, epoch int, _ <-chan error) error { if epoch == 0 && retry == 0 { retry++ return fmt.Errorf("error on try %d", retry) } else if epoch == 0 && retry == 1 { retry++ return fmt.Errorf("error on try %d", retry) } else if epoch == 0 && retry == 2 { retry++ cancel() } else { t.Errorf("Unexpected epoch %d and retry %d", epoch, retry) cancel() } return nil } cleanup := func(epoch int) {} a := NewAgent(TestProxy{start, cleanup, nil}, testRetry) go a.Run(ctx) a.ScheduleConfigUpdate("test") <-ctx.Done() }
Apache License 2.0
commerceblock/mainstay
cmd/clientsignuptool/clientsignuptool.go
clientPosition
go
func clientPosition() int32 { details, errDb := dbMongo.GetClientDetails() if errDb != nil { log.Error(errDb) } var maxClientPosition int32 if len(details) == 0 { return 0 } for _, client := range details { if client.ClientPosition > maxClientPosition { maxClientPosition = client.ClientPosition } } return maxClientPosition + 1 }
read client details and get client position
https://github.com/commerceblock/mainstay/blob/a4cbd580318198984185be1f98ed16d68299c514/cmd/clientsignuptool/clientsignuptool.go#L65-L81
package main import ( "bufio" "context" "encoding/hex" "fmt" "os" "mainstay/config" "mainstay/db" "mainstay/log" "mainstay/models" "github.com/btcsuite/btcd/btcec" "github.com/satori/go.uuid" ) const ConfPath = "/src/mainstay/cmd/clientsignuptool/conf.json" var ( mainConfig *config.Config dbMongo *db.DbMongo ) func init() { confFile, confErr := config.GetConfFile(os.Getenv("GOPATH") + ConfPath) if confErr != nil { log.Error(confErr) } var mainConfigErr error mainConfig, mainConfigErr = config.NewConfig(confFile) if mainConfigErr != nil { log.Error(mainConfigErr) } } func printClientDetails() { log.Infoln("existing clients") details, errDb := dbMongo.GetClientDetails() if errDb != nil { log.Error(errDb) } if len(details) == 0 { log.Infoln("no existing client positions") return } for _, client := range details { log.Infof("client_position: %d pubkey: %s name: %s\n", client.ClientPosition, client.Pubkey, client.ClientName) } log.Infoln() }
MIT License
nange/gospider
web/model/autogenerated_task.go
OptMaxBodySizeIn
go
func (qs TaskQuerySet) OptMaxBodySizeIn(optMaxBodySize ...int) TaskQuerySet { if len(optMaxBodySize) == 0 { qs.db.AddError(errors.New("must at least pass one optMaxBodySize in OptMaxBodySizeIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("opt_max_body_size IN (?)", optMaxBodySize)) }
OptMaxBodySizeIn is an autogenerated method nolint: dupl
https://github.com/nange/gospider/blob/58e3b2708dd55ee0c0b7e6bfae7e85b66ae5c4c4/web/model/autogenerated_task.go#L631-L637
package model import ( "errors" "fmt" "time" "github.com/jinzhu/gorm" "github.com/nange/gospider/common" ) type TaskQuerySet struct { db *gorm.DB } func NewTaskQuerySet(db *gorm.DB) TaskQuerySet { return TaskQuerySet{ db: db.Model(&Task{}), } } func (qs TaskQuerySet) w(db *gorm.DB) TaskQuerySet { return NewTaskQuerySet(db) } func (qs TaskQuerySet) All(ret *[]Task) error { return qs.db.Find(ret).Error } func (qs TaskQuerySet) AutoMigrateEq(autoMigrate bool) TaskQuerySet { return qs.w(qs.db.Where("auto_migrate = ?", autoMigrate)) } func (qs TaskQuerySet) AutoMigrateIn(autoMigrate ...bool) TaskQuerySet { if len(autoMigrate) == 0 { qs.db.AddError(errors.New("must at least pass one autoMigrate in AutoMigrateIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("auto_migrate IN (?)", autoMigrate)) } func (qs TaskQuerySet) AutoMigrateNe(autoMigrate bool) TaskQuerySet { return qs.w(qs.db.Where("auto_migrate != ?", autoMigrate)) } func (qs TaskQuerySet) AutoMigrateNotIn(autoMigrate ...bool) TaskQuerySet { if len(autoMigrate) == 0 { qs.db.AddError(errors.New("must at least pass one autoMigrate in AutoMigrateNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("auto_migrate NOT IN (?)", autoMigrate)) } func (qs TaskQuerySet) Count() (int, error) { var count int err := qs.db.Count(&count).Error return count, err } func (qs TaskQuerySet) CountsEq(counts int) TaskQuerySet { return qs.w(qs.db.Where("counts = ?", counts)) } func (qs TaskQuerySet) CountsGt(counts int) TaskQuerySet { return qs.w(qs.db.Where("counts > ?", counts)) } func (qs TaskQuerySet) CountsGte(counts int) TaskQuerySet { return qs.w(qs.db.Where("counts >= ?", counts)) } func (qs TaskQuerySet) CountsIn(counts ...int) TaskQuerySet { if len(counts) == 0 { qs.db.AddError(errors.New("must at least pass one counts in CountsIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("counts IN (?)", counts)) } func (qs TaskQuerySet) CountsLt(counts int) TaskQuerySet { return qs.w(qs.db.Where("counts < ?", counts)) } func (qs TaskQuerySet) CountsLte(counts int) TaskQuerySet { return qs.w(qs.db.Where("counts <= ?", counts)) } func (qs TaskQuerySet) CountsNe(counts int) TaskQuerySet { return qs.w(qs.db.Where("counts != ?", counts)) } func (qs TaskQuerySet) CountsNotIn(counts ...int) TaskQuerySet { if len(counts) == 0 { qs.db.AddError(errors.New("must at least pass one counts in CountsNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("counts NOT IN (?)", counts)) } func (o *Task) Create(db *gorm.DB) error { return db.Create(o).Error } func (qs TaskQuerySet) CreatedAtEq(createdAt time.Time) TaskQuerySet { return qs.w(qs.db.Where("created_at = ?", createdAt)) } func (qs TaskQuerySet) CreatedAtGt(createdAt time.Time) TaskQuerySet { return qs.w(qs.db.Where("created_at > ?", createdAt)) } func (qs TaskQuerySet) CreatedAtGte(createdAt time.Time) TaskQuerySet { return qs.w(qs.db.Where("created_at >= ?", createdAt)) } func (qs TaskQuerySet) CreatedAtLt(createdAt time.Time) TaskQuerySet { return qs.w(qs.db.Where("created_at < ?", createdAt)) } func (qs TaskQuerySet) CreatedAtLte(createdAt time.Time) TaskQuerySet { return qs.w(qs.db.Where("created_at <= ?", createdAt)) } func (qs TaskQuerySet) CreatedAtNe(createdAt time.Time) TaskQuerySet { return qs.w(qs.db.Where("created_at != ?", createdAt)) } func (qs TaskQuerySet) CronSpecEq(cronSpec string) TaskQuerySet { return qs.w(qs.db.Where("cron_spec = ?", cronSpec)) } func (qs TaskQuerySet) CronSpecIn(cronSpec ...string) TaskQuerySet { if len(cronSpec) == 0 { qs.db.AddError(errors.New("must at least pass one cronSpec in CronSpecIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("cron_spec IN (?)", cronSpec)) } func (qs TaskQuerySet) CronSpecNe(cronSpec string) TaskQuerySet { return qs.w(qs.db.Where("cron_spec != ?", cronSpec)) } func (qs TaskQuerySet) CronSpecNotIn(cronSpec ...string) TaskQuerySet { if len(cronSpec) == 0 { qs.db.AddError(errors.New("must at least pass one cronSpec in CronSpecNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("cron_spec NOT IN (?)", cronSpec)) } func (qs TaskQuerySet) Delete() error { return qs.db.Delete(Task{}).Error } func (o *Task) Delete(db *gorm.DB) error { return db.Delete(o).Error } func (qs TaskQuerySet) DeleteNum() (int64, error) { db := qs.db.Delete(Task{}) return db.RowsAffected, db.Error } func (qs TaskQuerySet) DeleteNumUnscoped() (int64, error) { db := qs.db.Unscoped().Delete(Task{}) return db.RowsAffected, db.Error } func (qs TaskQuerySet) GetUpdater() TaskUpdater { return NewTaskUpdater(qs.db) } func (qs TaskQuerySet) IDEq(ID uint64) TaskQuerySet { return qs.w(qs.db.Where("id = ?", ID)) } func (qs TaskQuerySet) IDGt(ID uint64) TaskQuerySet { return qs.w(qs.db.Where("id > ?", ID)) } func (qs TaskQuerySet) IDGte(ID uint64) TaskQuerySet { return qs.w(qs.db.Where("id >= ?", ID)) } func (qs TaskQuerySet) IDIn(ID ...uint64) TaskQuerySet { if len(ID) == 0 { qs.db.AddError(errors.New("must at least pass one ID in IDIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("id IN (?)", ID)) } func (qs TaskQuerySet) IDLt(ID uint64) TaskQuerySet { return qs.w(qs.db.Where("id < ?", ID)) } func (qs TaskQuerySet) IDLte(ID uint64) TaskQuerySet { return qs.w(qs.db.Where("id <= ?", ID)) } func (qs TaskQuerySet) IDNe(ID uint64) TaskQuerySet { return qs.w(qs.db.Where("id != ?", ID)) } func (qs TaskQuerySet) IDNotIn(ID ...uint64) TaskQuerySet { if len(ID) == 0 { qs.db.AddError(errors.New("must at least pass one ID in IDNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("id NOT IN (?)", ID)) } func (qs TaskQuerySet) Limit(limit int) TaskQuerySet { return qs.w(qs.db.Limit(limit)) } func (qs TaskQuerySet) LimitDelayEq(limitDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_delay = ?", limitDelay)) } func (qs TaskQuerySet) LimitDelayGt(limitDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_delay > ?", limitDelay)) } func (qs TaskQuerySet) LimitDelayGte(limitDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_delay >= ?", limitDelay)) } func (qs TaskQuerySet) LimitDelayIn(limitDelay ...int) TaskQuerySet { if len(limitDelay) == 0 { qs.db.AddError(errors.New("must at least pass one limitDelay in LimitDelayIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_delay IN (?)", limitDelay)) } func (qs TaskQuerySet) LimitDelayLt(limitDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_delay < ?", limitDelay)) } func (qs TaskQuerySet) LimitDelayLte(limitDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_delay <= ?", limitDelay)) } func (qs TaskQuerySet) LimitDelayNe(limitDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_delay != ?", limitDelay)) } func (qs TaskQuerySet) LimitDelayNotIn(limitDelay ...int) TaskQuerySet { if len(limitDelay) == 0 { qs.db.AddError(errors.New("must at least pass one limitDelay in LimitDelayNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_delay NOT IN (?)", limitDelay)) } func (qs TaskQuerySet) LimitDomainGlobEq(limitDomainGlob string) TaskQuerySet { return qs.w(qs.db.Where("limit_domain_glob = ?", limitDomainGlob)) } func (qs TaskQuerySet) LimitDomainGlobIn(limitDomainGlob ...string) TaskQuerySet { if len(limitDomainGlob) == 0 { qs.db.AddError(errors.New("must at least pass one limitDomainGlob in LimitDomainGlobIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_domain_glob IN (?)", limitDomainGlob)) } func (qs TaskQuerySet) LimitDomainGlobNe(limitDomainGlob string) TaskQuerySet { return qs.w(qs.db.Where("limit_domain_glob != ?", limitDomainGlob)) } func (qs TaskQuerySet) LimitDomainGlobNotIn(limitDomainGlob ...string) TaskQuerySet { if len(limitDomainGlob) == 0 { qs.db.AddError(errors.New("must at least pass one limitDomainGlob in LimitDomainGlobNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_domain_glob NOT IN (?)", limitDomainGlob)) } func (qs TaskQuerySet) LimitDomainRegexpEq(limitDomainRegexp string) TaskQuerySet { return qs.w(qs.db.Where("limit_domain_regexp = ?", limitDomainRegexp)) } func (qs TaskQuerySet) LimitDomainRegexpIn(limitDomainRegexp ...string) TaskQuerySet { if len(limitDomainRegexp) == 0 { qs.db.AddError(errors.New("must at least pass one limitDomainRegexp in LimitDomainRegexpIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_domain_regexp IN (?)", limitDomainRegexp)) } func (qs TaskQuerySet) LimitDomainRegexpNe(limitDomainRegexp string) TaskQuerySet { return qs.w(qs.db.Where("limit_domain_regexp != ?", limitDomainRegexp)) } func (qs TaskQuerySet) LimitDomainRegexpNotIn(limitDomainRegexp ...string) TaskQuerySet { if len(limitDomainRegexp) == 0 { qs.db.AddError(errors.New("must at least pass one limitDomainRegexp in LimitDomainRegexpNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_domain_regexp NOT IN (?)", limitDomainRegexp)) } func (qs TaskQuerySet) LimitEnableEq(limitEnable bool) TaskQuerySet { return qs.w(qs.db.Where("limit_enable = ?", limitEnable)) } func (qs TaskQuerySet) LimitEnableIn(limitEnable ...bool) TaskQuerySet { if len(limitEnable) == 0 { qs.db.AddError(errors.New("must at least pass one limitEnable in LimitEnableIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_enable IN (?)", limitEnable)) } func (qs TaskQuerySet) LimitEnableNe(limitEnable bool) TaskQuerySet { return qs.w(qs.db.Where("limit_enable != ?", limitEnable)) } func (qs TaskQuerySet) LimitEnableNotIn(limitEnable ...bool) TaskQuerySet { if len(limitEnable) == 0 { qs.db.AddError(errors.New("must at least pass one limitEnable in LimitEnableNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_enable NOT IN (?)", limitEnable)) } func (qs TaskQuerySet) LimitParallelismEq(limitParallelism int) TaskQuerySet { return qs.w(qs.db.Where("limit_parallelism = ?", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismGt(limitParallelism int) TaskQuerySet { return qs.w(qs.db.Where("limit_parallelism > ?", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismGte(limitParallelism int) TaskQuerySet { return qs.w(qs.db.Where("limit_parallelism >= ?", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismIn(limitParallelism ...int) TaskQuerySet { if len(limitParallelism) == 0 { qs.db.AddError(errors.New("must at least pass one limitParallelism in LimitParallelismIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_parallelism IN (?)", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismLt(limitParallelism int) TaskQuerySet { return qs.w(qs.db.Where("limit_parallelism < ?", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismLte(limitParallelism int) TaskQuerySet { return qs.w(qs.db.Where("limit_parallelism <= ?", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismNe(limitParallelism int) TaskQuerySet { return qs.w(qs.db.Where("limit_parallelism != ?", limitParallelism)) } func (qs TaskQuerySet) LimitParallelismNotIn(limitParallelism ...int) TaskQuerySet { if len(limitParallelism) == 0 { qs.db.AddError(errors.New("must at least pass one limitParallelism in LimitParallelismNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_parallelism NOT IN (?)", limitParallelism)) } func (qs TaskQuerySet) LimitRandomDelayEq(limitRandomDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_random_delay = ?", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayGt(limitRandomDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_random_delay > ?", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayGte(limitRandomDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_random_delay >= ?", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayIn(limitRandomDelay ...int) TaskQuerySet { if len(limitRandomDelay) == 0 { qs.db.AddError(errors.New("must at least pass one limitRandomDelay in LimitRandomDelayIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_random_delay IN (?)", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayLt(limitRandomDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_random_delay < ?", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayLte(limitRandomDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_random_delay <= ?", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayNe(limitRandomDelay int) TaskQuerySet { return qs.w(qs.db.Where("limit_random_delay != ?", limitRandomDelay)) } func (qs TaskQuerySet) LimitRandomDelayNotIn(limitRandomDelay ...int) TaskQuerySet { if len(limitRandomDelay) == 0 { qs.db.AddError(errors.New("must at least pass one limitRandomDelay in LimitRandomDelayNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("limit_random_delay NOT IN (?)", limitRandomDelay)) } func (qs TaskQuerySet) Offset(offset int) TaskQuerySet { return qs.w(qs.db.Offset(offset)) } func (qs TaskQuerySet) One(ret *Task) error { return qs.db.First(ret).Error } func (qs TaskQuerySet) OptAllowedDomainsEq(optAllowedDomains string) TaskQuerySet { return qs.w(qs.db.Where("opt_allowed_domains = ?", optAllowedDomains)) } func (qs TaskQuerySet) OptAllowedDomainsIn(optAllowedDomains ...string) TaskQuerySet { if len(optAllowedDomains) == 0 { qs.db.AddError(errors.New("must at least pass one optAllowedDomains in OptAllowedDomainsIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("opt_allowed_domains IN (?)", optAllowedDomains)) } func (qs TaskQuerySet) OptAllowedDomainsNe(optAllowedDomains string) TaskQuerySet { return qs.w(qs.db.Where("opt_allowed_domains != ?", optAllowedDomains)) } func (qs TaskQuerySet) OptAllowedDomainsNotIn(optAllowedDomains ...string) TaskQuerySet { if len(optAllowedDomains) == 0 { qs.db.AddError(errors.New("must at least pass one optAllowedDomains in OptAllowedDomainsNotIn")) return qs.w(qs.db) } return qs.w(qs.db.Where("opt_allowed_domains NOT IN (?)", optAllowedDomains)) } func (qs TaskQuerySet) OptMaxBodySizeEq(optMaxBodySize int) TaskQuerySet { return qs.w(qs.db.Where("opt_max_body_size = ?", optMaxBodySize)) } func (qs TaskQuerySet) OptMaxBodySizeGt(optMaxBodySize int) TaskQuerySet { return qs.w(qs.db.Where("opt_max_body_size > ?", optMaxBodySize)) } func (qs TaskQuerySet) OptMaxBodySizeGte(optMaxBodySize int) TaskQuerySet { return qs.w(qs.db.Where("opt_max_body_size >= ?", optMaxBodySize)) }
MIT License
goharbor/harbor-cluster-operator
lcm/property.go
ToInt
go
func (p *Property) ToInt() int { if p.Value != nil { if v, ok := p.Value.(int); ok { return v } } return 0 }
ToInt parse properties value to int type
https://github.com/goharbor/harbor-cluster-operator/blob/a258703dccb23ed9a0efb54dd6fb310ffab0a9fa/lcm/property.go#L82-L90
package lcm const ( ProperConn = "Connection" ProperPort = "Port" ProperUser = "Username" ProperPass = "Password" ProperNodes = "AvailableNodes" ) const ( CoreURLSecretForCache string = "coreURLSecret" RegisterSecretForCache string = "registrySecret" ClairSecretForCache string = "clairSecret" ChartMuseumSecretForCache string = "chartMuseumSecret" JobServiceSecretForCache string = "jobServiceSecret" ) const ( CoreSecretForDatabase string = "coreSecret" ClairSecretForDatabase string = "clairSecret" NotaryServerSecretForDatabase string = "notaryServerSecret" NotarySignerSecretForDatabase string = "notarySignerSecret" ) const ( InClusterSecretForStorage string = "inClusterSecret" AzureSecretForStorage string = "azureSecret" GcsSecretForStorage string = "gcsSecret" SwiftSecretForStorage string = "swiftSecret" S3SecretForStorage string = "s3Secret" OssSecretForStorage string = "ossSecret" ChartMuseumSecretForStorage string = "chartMuseumSecret" ) type Property struct { Name string Value interface{} } type Properties []*Property func (ps *Properties) Add(Name string, Value interface{}) { p := &Property{ Name: Name, Value: Value, } *ps = append(*ps, p) } func (ps *Properties) Update(Name string, Value interface{}) { for _, p := range *ps { if p.Name == Name { p.Value = Value return } } } func (ps *Properties) Get(Name string) *Property { for _, p := range *ps { if p.Name == Name { return p } } return nil }
Apache License 2.0
google/simhospital
pkg/hl7/sender.go
Close
go
func (s *stdoutSender) Close() error { log.Infof("Messages successfully sent by the stdoutSender: %d", s.count) return nil }
Close prints the number of messages that have been sent.
https://github.com/google/simhospital/blob/db2c1db3fe37718f8e12426e2ac4d2df803efc16/pkg/hl7/sender.go#L53-L56
package hl7 import ( "bytes" "fmt" "net" "os" "syscall" "time" "github.com/pkg/errors" ) type Sender interface { Send([]byte) error Close() error } type stdoutSender struct { count int } func NewStdoutSender() Sender { return &stdoutSender{} } func (s *stdoutSender) Send(message []byte) error { fmt.Print(string(bytes.Replace(message, []byte(SegmentTerminatorStr), []byte("\n"), -1))) fmt.Print("\n") s.count++ return nil }
Apache License 2.0
pires/consul-lb-gce
vendor/src/github.com/hashicorp/consul/watch/funcs.go
keyWatch
go
func keyWatch(params map[string]interface{}) (WatchFunc, error) { var key string if err := assignValue(params, "key", &key); err != nil { return nil, err } if key == "" { return nil, fmt.Errorf("Must specify a single key to watch") } fn := func(p *WatchPlan) (uint64, interface{}, error) { kv := p.client.KV() opts := consulapi.QueryOptions{WaitIndex: p.lastIndex} pair, meta, err := kv.Get(key, &opts) if err != nil { return 0, nil, err } if pair == nil { return meta.LastIndex, nil, err } return meta.LastIndex, pair, err } return fn, nil }
keyWatch is used to return a key watching function
https://github.com/pires/consul-lb-gce/blob/d034e7fc88b642f3686fc88958d2ae8225f1699c/vendor/src/github.com/hashicorp/consul/watch/funcs.go#L29-L51
package watch import ( "fmt" consulapi "github.com/hashicorp/consul/api" ) type watchFactory func(params map[string]interface{}) (WatchFunc, error) var watchFuncFactory map[string]watchFactory func init() { watchFuncFactory = map[string]watchFactory{ "key": keyWatch, "keyprefix": keyPrefixWatch, "services": servicesWatch, "nodes": nodesWatch, "service": serviceWatch, "checks": checksWatch, "event": eventWatch, } }
Apache License 2.0
opensuse/helm-mirror
vendor/golang.org/x/crypto/openpgp/packet/packet.go
readFull
go
func readFull(r io.Reader, buf []byte) (n int, err error) { n, err = io.ReadFull(r, buf) if err == io.EOF { err = io.ErrUnexpectedEOF } return }
readFull is the same as io.ReadFull except that reading zero bytes returns ErrUnexpectedEOF rather than EOF.
https://github.com/opensuse/helm-mirror/blob/0c1de6d84af02ce36e676f552d5d24d5179175f7/vendor/golang.org/x/crypto/openpgp/packet/packet.go#L24-L30
package packet import ( "bufio" "crypto/aes" "crypto/cipher" "crypto/des" "crypto/rsa" "io" "math/big" "golang.org/x/crypto/cast5" "golang.org/x/crypto/openpgp/errors" )
Apache License 2.0
timebye/go-harbor
repositories.go
GetImageDetails
go
func (s *RepositoriesService) GetImageDetails(repoName, tag string) ([]VulnerabilityItem, *gorequest.Response, []error) { var v []VulnerabilityItem resp, _, errs := s.client. NewRequest(gorequest.GET, fmt.Sprintf("repositories/%s/tags/%s/vulnerability/details", repoName, tag)). EndStruct(&v) return v, &resp, errs }
Get vulnerability details of the image. Call Clair API to get the vulnerability based on the previous successful scan. Harbor API docs: https://github.com/vmware/harbor/blob/release-1.4.0/docs/swagger.yaml#L1177
https://github.com/timebye/go-harbor/blob/7a6811422e3c591cc2cc2ce0b87a61a54b1d7a36/repositories.go#L237-L243
package harbor import ( "fmt" "github.com/goharbor/harbor/src/common/models" "github.com/parnurzeal/gorequest" "time" ) type VulnerabilityItem struct { ID string `json:"id"` Severity int64 `json:"severity"` Pkg string `json:"package"` Version string `json:"version"` Description string `json:"description"` Link string `json:"link"` Fixed string `json:"fixedVersion,omitempty"` } type RepoResp struct { ID int64 `json:"id"` Name string `json:"name"` ProjectID int64 `json:"project_id"` Description string `json:"description"` PullCount int64 `json:"pull_count"` StarCount int64 `json:"star_count"` TagsCount int64 `json:"tags_count"` CreationTime time.Time `json:"creation_time"` UpdateTime time.Time `json:"update_time"` } type RepoRecord struct { *models.RepoRecord } type cfg struct { Labels map[string]string `json:"labels"` } type ComponentsOverview struct { Total int `json:"total"` Summary []*ComponentsOverviewEntry `json:"summary"` } type ComponentsOverviewEntry struct { Sev int `json:"severity"` Count int `json:"count"` } type ImgScanOverview struct { ID int64 `json:"-"` Digest string `json:"image_digest"` Status string `json:"scan_status"` JobID int64 `json:"job_id"` Sev int `json:"severity"` CompOverviewStr string `json:"-"` CompOverview *ComponentsOverview `json:"components,omitempty"` DetailsKey string `json:"details_key"` CreationTime time.Time `json:"creation_time,omitempty"` UpdateTime time.Time `json:"update_time,omitempty"` } type tagDetail struct { Digest string `json:"digest"` Name string `json:"name"` Size int64 `json:"size"` Architecture string `json:"architecture"` OS string `json:"os"` DockerVersion string `json:"docker_version"` Author string `json:"author"` Created time.Time `json:"created"` Config *cfg `json:"config"` } type Signature struct { Tag string `json:"tag"` Hashes map[string][]byte `json:"hashes"` } type TagResp struct { tagDetail Signature *Signature `json:"signature"` ScanOverview *ImgScanOverview `json:"scan_overview,omitempty"` } type RepositoriesService struct { client *Client } type ListRepositoriesOption struct { ListOptions ProjectId int64 `url:"project_id,omitempty" json:"project_id,omitempty"` ProjectName string `url:"project_name,omitempty" json:"project_name,omitempty"` Q string `url:"q,omitempty" json:"q,omitempty"` Sort string `url:"sort,omitempty" json:"sort,omitempty"` } type ManifestResp struct { Manifest interface{} `json:"manifest"` Config interface{} `json:"config,omitempty" ` } func (s *RepositoriesService) ListRepository(opt *ListRepositoriesOption) ([]RepoRecord, *gorequest.Response, []error) { var v []RepoRecord resp, _, errs := s.client. NewRequest(gorequest.GET, fmt.Sprintf("/projects/%s/repositories", opt.ProjectName)). Query(*opt). EndStruct(&v) return v, &resp, errs } func (s *RepositoriesService) DeleteRepository(repoName string) (*gorequest.Response, []error) { resp, _, errs := s.client. NewRequest(gorequest.DELETE, fmt.Sprintf("repositories/%s", repoName)). End() return &resp, errs } type RepositoryDescription struct { Description string `url:"description,omitempty" json:"description,omitempty"` } func (s *RepositoriesService) UpdateRepository(repoName string, d RepositoryDescription) (*gorequest.Response, []error) { resp, _, errs := s.client. NewRequest(gorequest.PUT, fmt.Sprintf("repositories/%s", repoName)). Send(d). End() return &resp, errs } func (s *RepositoriesService) GetRepositoryTag(repoName, tag string) (TagResp, *gorequest.Response, []error) { var v TagResp resp, _, errs := s.client. NewRequest(gorequest.GET, fmt.Sprintf("repositories/%s/tags/%s", repoName, tag)). EndStruct(&v) return v, &resp, errs } func (s *RepositoriesService) DeleteRepositoryTag(repoName, tag string) (*gorequest.Response, []error) { resp, _, errs := s.client. NewRequest(gorequest.DELETE, fmt.Sprintf("repositories/%s/tags/%s", repoName, tag)). End() return &resp, errs } func (s *RepositoriesService) ListRepositoryTags(repoName string) ([]TagResp, *gorequest.Response, []error) { var v []TagResp resp, _, errs := s.client. NewRequest(gorequest.GET, fmt.Sprintf("repositories/%s/tags", repoName)). EndStruct(&v) return v, &resp, errs } func (s *RepositoriesService) GetRepositoryTagManifests(repoName, tag string, version string) (ManifestResp, *gorequest.Response, []error) { var v ManifestResp resp, _, errs := s.client. NewRequest(gorequest.GET, func() string { if version == "" { return fmt.Sprintf("repositories/%s/tags/%s/manifest", repoName, tag) } return fmt.Sprintf("repositories/%s/tags/%s/manifest?version=%s", repoName, tag, version) }()). EndStruct(&v) return v, &resp, errs } func (s *RepositoriesService) ScanImage(repoName, tag string) (*gorequest.Response, []error) { resp, _, errs := s.client. NewRequest(gorequest.POST, fmt.Sprintf("repositories/%s/tags/%s/scan", repoName, tag)). End() return &resp, errs }
MIT License
netauth/netauth
internal/plugin/tree/common/rpc.go
Server
go
func (p *GoPluginRPC) Server(*plugin.MuxBroker) (interface{}, error) { return &GoPluginServer{Mux: p.Mux}, nil }
Server returns a go-plugin compliant interface that handles the provider side of the interface.
https://github.com/netauth/netauth/blob/d6c52237bcbcbfadeee5662d54435dda4b9937ac/internal/plugin/tree/common/rpc.go#L11-L13
package common import ( "net/rpc" "github.com/hashicorp/go-plugin" )
MIT License
fluxcd/flux2
cmd/flux/create_source_git_test.go
run
go
func (r *reconciler) run(t *testing.T) { result := make(chan error) go func() { defer close(result) err := wait.PollImmediate( pollInterval, testTimeout, r.conditionFunc) result <- err }() t.Cleanup(func() { if err := <-result; err != nil { t.Errorf("Failure from test reconciler: '%v':", err.Error()) } }) }
Start the background task that waits for the object to exist then applies the update function.
https://github.com/fluxcd/flux2/blob/ca496d393d993ac5119ed84f83e010b8fe918c53/cmd/flux/create_source_git_test.go#L53-L68
package main import ( "context" "github.com/fluxcd/pkg/apis/meta" sourcev1 "github.com/fluxcd/source-controller/api/v1beta1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" "sigs.k8s.io/controller-runtime/pkg/client" "testing" "time" ) var pollInterval = 50 * time.Millisecond var testTimeout = 10 * time.Second type reconcileFunc func(repo *sourcev1.GitRepository) type reconciler struct { client client.Client name types.NamespacedName reconcile reconcileFunc }
Apache License 2.0
grafana/synthetic-monitoring-agent
pkg/accounting/accounting_test.go
TestGetActiveSeriesForCheck
go
func TestGetActiveSeriesForCheck(t *testing.T) { testcases := getTestCases() for checkType := range activeSeriesByCheckType { _, found := testcases[checkType] require.True(t, found, "every element in activeSeriesByCheckType must be tested") } for name, tc := range testcases { t.Run(name, func(t *testing.T) { actual, err := GetActiveSeriesForCheck(tc.input) require.NoError(t, err) require.Equal(t, activeSeriesByCheckType[tc.class], actual) }) } }
TestGetActiveSeriesForCheck verifies that GetActiveSeriesForCheck returns the data in activeSeriesByCheckType. This makes sure that the function is applying the correct criteria to select the entry from the map. It also verifies that all the entries in that map are covered.
https://github.com/grafana/synthetic-monitoring-agent/blob/62ce3cbdea7059a4d024327217f697cf11a8d21f/pkg/accounting/accounting_test.go#L176-L198
package accounting import ( "path" "path/filepath" "strings" "testing" "github.com/grafana/synthetic-monitoring-agent/pkg/pb/synthetic_monitoring" "github.com/stretchr/testify/require" ) func getTestCases() map[string]struct { input synthetic_monitoring.Check class string } { return map[string]struct { input synthetic_monitoring.Check class string }{ "dns": { input: synthetic_monitoring.Check{ Target: "127.0.0.1", Settings: synthetic_monitoring.CheckSettings{ Dns: &synthetic_monitoring.DnsSettings{}, }, }, class: "dns", }, "dns_basic": { input: synthetic_monitoring.Check{ Target: "127.0.0.1", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Dns: &synthetic_monitoring.DnsSettings{}, }, }, class: "dns_basic", }, "http": { input: synthetic_monitoring.Check{ Target: "http://127.0.0.1/", Settings: synthetic_monitoring.CheckSettings{ Http: &synthetic_monitoring.HttpSettings{}, }, }, class: "http", }, "http_ssl": { input: synthetic_monitoring.Check{ Target: "https://127.0.0.1/", Settings: synthetic_monitoring.CheckSettings{ Http: &synthetic_monitoring.HttpSettings{}, }, }, class: "http_ssl", }, "http_basic": { input: synthetic_monitoring.Check{ Target: "http://127.0.0.1/", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Http: &synthetic_monitoring.HttpSettings{}, }, }, class: "http_basic", }, "http_ssl_basic": { input: synthetic_monitoring.Check{ Target: "https://127.0.0.1/", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Http: &synthetic_monitoring.HttpSettings{}, }, }, class: "http_ssl_basic", }, "ping": { input: synthetic_monitoring.Check{ Target: "127.0.0.1", Settings: synthetic_monitoring.CheckSettings{ Ping: &synthetic_monitoring.PingSettings{}, }, }, class: "ping", }, "ping_basic": { input: synthetic_monitoring.Check{ Target: "127.0.0.1", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Ping: &synthetic_monitoring.PingSettings{}, }, }, class: "ping_basic", }, "tcp": { input: synthetic_monitoring.Check{ Target: "127.0.0.1:8080", Settings: synthetic_monitoring.CheckSettings{ Tcp: &synthetic_monitoring.TcpSettings{}, }, }, class: "tcp", }, "tcp_ssl": { input: synthetic_monitoring.Check{ Target: "127.0.0.1:8080", Settings: synthetic_monitoring.CheckSettings{ Tcp: &synthetic_monitoring.TcpSettings{ Tls: true, }, }, }, class: "tcp_ssl", }, "tcp_basic": { input: synthetic_monitoring.Check{ Target: "127.0.0.1:8080", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Tcp: &synthetic_monitoring.TcpSettings{}, }, }, class: "tcp_basic", }, "tcp_ssl_basic": { input: synthetic_monitoring.Check{ Target: "127.0.0.1:8080", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Tcp: &synthetic_monitoring.TcpSettings{ Tls: true, }, }, }, class: "tcp_ssl_basic", }, "traceroute": { input: synthetic_monitoring.Check{ Target: "127.0.0.1", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Traceroute: &synthetic_monitoring.TracerouteSettings{ MaxHops: 64, HopTimeout: 100, }, }, }, class: "traceroute_basic", }, "traceroute_basic": { input: synthetic_monitoring.Check{ Target: "127.0.0.1", BasicMetricsOnly: true, Settings: synthetic_monitoring.CheckSettings{ Traceroute: &synthetic_monitoring.TracerouteSettings{ MaxHops: 64, HopTimeout: 100, }, }, }, class: "traceroute_basic", }, } }
Apache License 2.0
alienvault-otx/otx-go-sdk
src/otxapi/otxapi.go
Do
go
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) { resp, err := c.client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() response := newResponse(resp) err = CheckResponse(resp) if err != nil { return response, err } content, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("%s", err) os.Exit(1) } response.RawContent = content return response, err }
Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.
https://github.com/alienvault-otx/otx-go-sdk/blob/ac284b7807742c1af88edd962a3980f0298aa2b2/src/otxapi/otxapi.go#L174-L199
package otxapi import ( "bytes" "encoding/json" "fmt" "github.com/google/go-querystring/query" "io" "io/ioutil" "net/http" "net/url" "os" "reflect" ) const ( get = "GET" libraryVersion = "0.1" userAgent = "go-otx-api/" + libraryVersion defaultBaseURL = "https://otx.alienvault.com/" subscriptionsURLPath = "api/v1/pulses/subscribed" pulseDetailURLPath = "api/v1/pulses/" userURLPath = "api/v1/user/" apiVersion = "v1" ) type Client struct { client *http.Client BaseURL *url.URL UserAgent string UserDetail *OTXUserDetailService PulseDetail *OTXPulseDetailService ThreatIntel *OTXThreatIntelFeedService } type Response struct { *http.Response RawContent []uint8 Content map[string]interface{} `json:"results,omitempty"` } type ListOptions struct { Page int `url:"page,omitempty"` PerPage int `url:"limit,omitempty"` } func addOptions(s string, opt interface{}) (string, error) { v := reflect.ValueOf(opt) if v.Kind() == reflect.Ptr && v.IsNil() { return s, nil } u, err := url.Parse(s) if err != nil { return s, err } qs, err := query.Values(opt) if err != nil { return s, err } u.RawQuery = qs.Encode() return u.String(), nil } func (c *OTXPulseDetailService) Get(id_string string) (PulseDetail, Response, error) { client := &http.Client{} req, _ := http.NewRequest(get, fmt.Sprintf("%s/%s/%s/", defaultBaseURL, pulseDetailURLPath, id_string), nil) req.Header.Set("X-OTX-API-KEY", fmt.Sprintf("%s", os.Getenv("X_OTX_API_KEY"))) response, _ := client.Do(req) resp := Response{Response: response} contents, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Printf("%s", err) os.Exit(1) } pulse_detail := new(PulseDetail) json.Unmarshal(contents, &(pulse_detail)) json.Unmarshal(contents, &(resp.Content)) return *pulse_detail, resp, err } func (c *OTXThreatIntelFeedService) List(opt *ListOptions) (ThreatIntelFeed, Response, error) { client := &http.Client{} requestpath, err := addOptions(defaultBaseURL + subscriptionsURLPath, opt) if err != nil { return ThreatIntelFeed{}, Response{}, err } req, _ := http.NewRequest(get, requestpath, nil) req.Header.Set("X-OTX-API-KEY", fmt.Sprintf("%s", os.Getenv("X_OTX_API_KEY"))) response, _ := client.Do(req) resp := Response{Response: response} contents, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Printf("%s", err) os.Exit(1) } pulse_list := new(ThreatIntelFeed) err = json.Unmarshal(contents, &(pulse_list)) json.Unmarshal(contents, &(resp.Content)) if err != nil { fmt.Println("error not nil on json unmarshall") fmt.Println(err) } return *pulse_list, resp, err } func (c *OTXUserDetailService) Get() (UserDetail, *Response, error) { req, err := c.client.NewRequest(get, userURLPath, nil) if err != nil { return UserDetail{}, nil, err } req.Header.Set("X-OTX-API-KEY", fmt.Sprintf("%s", os.Getenv("X_OTX_API_KEY"))) userdetail := &UserDetail{} resp, err := c.client.Do(req, userdetail) if err != nil { return UserDetail{}, resp, err } err = json.Unmarshal(resp.RawContent, &(userdetail)) json.Unmarshal(resp.RawContent, &(resp.Content)) return *userdetail, resp, err } func NewClient(httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, _ := url.Parse(defaultBaseURL) c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent} c.UserDetail = &OTXUserDetailService{client: c} return c }
Apache License 2.0