query stringlengths 8 4.68k | pos stringlengths 30 210k | negs listlengths 7 7 |
|---|---|---|
/ The function fiat_p224_addcarryx_u32 is a thin wrapper around bits.Add32 that uses fiat_p224_uint1 rather than uint32 | func fiat_p224_addcarryx_u32(x uint32, y uint32, carry fiat_p224_uint1) (uint32, fiat_p224_uint1) {
var sum uint32
var carryOut uint32
sum, carryOut = bits.Add32(x, y, uint32(carry))
return sum, fiat_p224_uint1(carryOut)
} | [
"func softfloat_mul128By32(a64, a0 uint64, b uint32) Uint128 {\n\tvar z Uint128\n\tvar mid uint64\n\tvar carry uint32\n\n\tz.Low = a0 * uint64(b)\n\tmid = (a0 >> 32) * uint64(b)\n\tcarry = uint32(z.Low>>32) - uint32(mid)\n\tz.High = a64*uint64(b) + uint64((mid+uint64(carry))>>32)\n\treturn z\n}",
"func CarryAdd(o... |
vytvori prazdnu mapu velkosti 6x6 | func vytvorPrazdnuMapu() [6][6]uint8 {
mapa := [6][6]uint8{
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
}
return mapa
} | [
"func initTerrain(game *gamestate) {\n\trand.New(rand.NewSource(42)) //42 best magical Constant\n\trand.Seed(time.Now().UnixNano())\n\tx := 0\n\n\ty := heightOfMap - rand.Float64()*(heightOfMap/2) // the height to start at\n\tfmt.Println(y)\n\t//standardTerrain := y\n\tvar dy float64 = 0\n\tvar dyGoal float64 = 0\n... |
=== FUNCTION ============================================================== Name: GeneratePanicMsg Description: ============================================================================= | func GeneratePanicMsg(limit uint64) string {
overMaxElements := limit - maxUint64
msg :=
"\nThe numerator is too high: " + strconv.FormatUint(limit, 10) +
"\nThe numerator cannot exceed " + strconv.FormatUint(maxUint64, 10) +
"\nYou are over the limit by " + strconv.FormatUint(overMaxElements, 10)
return msg
} | [
"func SystemMessg(message byte, length uint16) *network.Writer {\n\tvar packet = network.NewWriter(SYSTEMMESSG)\n\tpacket.WriteByte(message)\n\tpacket.WriteUint16(length)\n\n\treturn packet\n}",
"func Panic(v ...interface{}) {\n s := sout(v...)\n Std.Output(LevelPanic, CallDepth, s)\n panic(s)\n}",
"fu... |
ValidateSlice validates that all items in target is one of valid | func ValidateSlice(target []string, valid []string) (bool, error) {
for _, item := range target {
found, _ := ValidateString(item, valid)
if !found {
return false, fmt.Errorf("'%s' is not in the allowed list: %s", item, strings.Join(valid, ", "))
}
}
return true, nil
} | [
"func TestMyValids(t *testing.T) {\n\n\ttables := []struct {\n\t\tmyQuery string\n\t\tindexList []int\n\t\tmyIndex int\n\t\tmyValIndex bool\n\t\theader []string\n\t\terr error\n\t}{\n\t\t{\"SELECT UPPER(NULLIF(draft_year,random_name))\", []int{3, 5, 6, 7, 8, 9}, 3, true, []string{\"draft_year\", \... |
ArrayContainsString checks to see if a value exists in the array | func ArrayContainsString(array []string, value string) bool {
hasValue := false
for i := 0; i < len(array); i++ {
if array[i] == value {
hasValue = true
}
}
return hasValue
} | [
"func Contains(aa []string, s string) bool {\n\tfor _, v := range aa {\n\t\tif s == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}",
"func (arr StringArray) Contains(v string) bool {\n\treturn arr.IndexOf(v) > -1\n}",
"func contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n... |
Render method writes File into HTTP response. | func (f *binaryRender) Render(w io.Writer) error {
if f.Reader != nil {
defer ess.CloseQuietly(f.Reader)
_, err := io.Copy(w, f.Reader)
return err
}
file, err := os.Open(f.Path)
if err != nil {
return err
}
defer ess.CloseQuietly(file)
fi, err := file.Stat()
if err != nil {
return err
}
if fi.IsDir() {
return fmt.Errorf("'%s' is a directory", f.Path)
}
_, err = io.Copy(w, file)
return err
} | [
"func (o EndpointsResponseOutput) File() pulumi.StringOutput {\n\treturn o.ApplyT(func(v EndpointsResponse) string { return v.File }).(pulumi.StringOutput)\n}",
"func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {\n\trender.Status(r, e.StatusCode)\n\treturn nil\n}",
"func (c *Context) F... |
Write operation is not supported. For interface compatibility only. | func (reader *embedFileReader) Write(b []byte) (int, error) {
return 0, ErrNotAvail
} | [
"func (m *Memory) Write(b []byte) (n int, err error) {\n\tpanic(\"not implemented\")\n}",
"func (r *MockReadWriteCloser) Write(p []byte) (n int, err error) {\n\n\tif err = r.WriteErr; err != nil {\n\t\tr.BytesWritten = p\n\t\tn = len(p)\n\t}\n\treturn\n}",
"func Write(ref name.Reference, img v1.Image, w io.Writ... |
NewBikePointGetAllParams creates a new BikePointGetAllParams object with the default values initialized. | func NewBikePointGetAllParams() *BikePointGetAllParams {
return &BikePointGetAllParams{
timeout: cr.DefaultTimeout,
}
} | [
"func NewGetZippedParams() *GetZippedParams {\n\tvar ()\n\treturn &GetZippedParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}",
"func NewGetContactsParams() *GetContactsParams {\n\tvar (\n\t\tlimitDefault = int32(5000)\n\t\toffsetDefault = int32(0)\n\t)\n\treturn &GetContactsParams{\n\t\tLimit: &limitDefault,\... |
NewMockTime creates a new mock instance | func NewMockTime(ctrl *gomock.Controller) *MockTime {
mock := &MockTime{ctrl: ctrl}
mock.recorder = &MockTimeMockRecorder{mock}
return mock
} | [
"func NewMock(serverHost string) (*MockClient, error) {\n\treturn &MockClient{}, nil\n}",
"func NewMockAuth(t mockConstructorTestingTNewMockAuth) *MockAuth {\n\tmock := &MockAuth{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}",
"func NewMock() *Mock {\n\treturn ... |
SharedAccessSignatureAuthorizationRuleListResultPreparer prepares a request to retrieve the next set of results. It returns nil if no more results exist. | func (client SharedAccessSignatureAuthorizationRuleListResult) SharedAccessSignatureAuthorizationRuleListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
} | [
"func (alr AppListResult) appListResultPreparer() (*http.Request, error) {\n\tif alr.NextLink == nil || len(to.String(alr.NextLink)) < 1 {\n\t\treturn nil, nil\n\t}\n\treturn autorest.Prepare(&http.Request{},\n\t\tautorest.AsJSON(),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(to.String(alr.NextLink)))\n}",
"... |
MetricKeyPrefix returns the metrics key prefix | func (p PostgresPlugin) MetricKeyPrefix() string {
if p.Prefix == "" {
p.Prefix = "postgres"
}
return p.Prefix
} | [
"func KeyPrefix(p string) []byte {\n\treturn []byte(p)\n}",
"func generateKeyPrefixID(prefix []byte, id uint64) []byte {\n\t// Handle the prefix.\n\tkey := append(prefix, prefixDelimiter)\n\n\t// Handle the item ID.\n\tkey = append(key, idToKey(id)...)\n\n\treturn key\n}",
"func TestConvertToGraphitePrefixKey(t... |
UnsetFirstName ensures that no value is present for FirstName, not even an explicit nil | func (o *RelationshipManager) UnsetFirstName() {
o.FirstName.Unset()
} | [
"func (o *GetSearchEmployeesParams) SetFirstName(firstName *string) {\n\to.FirstName = firstName\n}",
"func (o *Permissao) UnsetNome() {\n\to.Nome.Unset()\n}",
"func (uc *UserCreate) SetFirstName(s string) *UserCreate {\n\tuc.mutation.SetFirstName(s)\n\treturn uc\n}",
"func (uu *UserUpdate) ClearLastName() *U... |
CreateParcelVol mocks base method | func (m *MockNuvoVM) CreateParcelVol(arg0, arg1, arg2 string) (string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateParcelVol", arg0, arg1, arg2)
ret0, _ := ret[0].(string)
ret1, _ := ret[1].(error)
return ret0, ret1
} | [
"func (m *MockNuvoVM) DestroyVol(arg0, arg1, arg2 string, arg3 bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DestroyVol\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}",
"func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePha... |
NewBuildClient creates a new BuildClient instance that is set to the initial state (i.e., being idle). | func NewBuildClient(scheduler remoteworker.OperationQueueClient, buildExecutor BuildExecutor, filePool filesystem.FilePool, clock clock.Clock, workerID map[string]string, instanceNamePrefix digest.InstanceName, platform *remoteexecution.Platform, sizeClass uint32) *BuildClient {
return &BuildClient{
scheduler: scheduler,
buildExecutor: buildExecutor,
filePool: filePool,
clock: clock,
instanceNamePrefix: instanceNamePrefix,
instanceNamePatcher: digest.NewInstanceNamePatcher(digest.EmptyInstanceName, instanceNamePrefix),
request: remoteworker.SynchronizeRequest{
WorkerId: workerID,
InstanceNamePrefix: instanceNamePrefix.String(),
Platform: platform,
SizeClass: sizeClass,
CurrentState: &remoteworker.CurrentState{
WorkerState: &remoteworker.CurrentState_Idle{
Idle: &emptypb.Empty{},
},
},
},
nextSynchronizationAt: clock.Now(),
}
} | [
"func NewGitClient(t mockConstructorTestingTNewGitClient) *GitClient {\n\tmock := &GitClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}",
"func (c *Client) Build(params map[string]interface{}) (api.ClientAPI, error) {\n\t// tenantName, _ := params[\"name\"].(s... |
WithColumnKeys sets explicit column keys. It's also possible to set a key retriever on this property object. Upon file decryption, availability of explicit keys is checked before invocation of the retreiver callback. If an explicit key is available for a footer or a column, its key metadata will be ignored. | func WithColumnKeys(decrypt ColumnPathToDecryptionPropsMap) FileDecryptionOption {
return func(cfg *fileDecryptConfig) {
if len(decrypt) == 0 {
return
}
if len(cfg.colDecrypt) != 0 {
panic("column properties already set")
}
for _, v := range decrypt {
if v.IsUtilized() {
panic("parquet: column properties utilized in another file")
}
v.SetUtilized()
}
cfg.colDecrypt = decrypt
}
} | [
"func (b CreateIndexBuilder) Columns(columns ...string) CreateIndexBuilder {\n\treturn builder.Set(b, \"Columns\", columns).(CreateIndexBuilder)\n}",
"func NewColumnDecryptionProperties(column string, opts ...ColumnDecryptOption) *ColumnDecryptionProperties {\n\tvar cfg columnDecryptConfig\n\tfor _, o := range op... |
NewProjectV1UsingExternalConfig : constructs an instance of ProjectV1 with passed in options and external configuration. | func NewProjectV1UsingExternalConfig(options *ProjectV1Options) (project *ProjectV1, err error) {
if options.ServiceName == "" {
options.ServiceName = DefaultServiceName
}
if options.Authenticator == nil {
options.Authenticator, err = core.GetAuthenticatorFromEnvironment(options.ServiceName)
if err != nil {
return
}
}
project, err = NewProjectV1(options)
if err != nil {
return
}
err = project.Service.ConfigureService(options.ServiceName)
if err != nil {
return
}
if options.URL != "" {
err = project.Service.SetServiceURL(options.URL)
}
return
} | [
"func (s *Server) Create(ctx context.Context, q *project.ProjectCreateRequest) (*v1alpha1.AppProject, error) {\n\tif q.Project == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"missing payload 'project' in request\")\n\t}\n\tif err := s.enf.EnforceErr(ctx.Value(\"claims\"), rbacpolicy.ResourceProject... |
FirstPoolWithAvailableQuota returns the first pool ID in the list of pools with available addresses. This function always returns types.PoolNotExists | func (n *NoOpAllocator) FirstPoolWithAvailableQuota(preferredPoolIDs []types.PoolID) (types.PoolID, int) {
return types.PoolNotExists, 0
} | [
"func (sp *Storagepool) FindStoragePoolByName(ctx context.Context, poolName string) (*types.StoragePool, error) {\n\tif len(poolName) == 0 {\n\t\treturn nil, errors.New(\"poolName shouldn't be empty\")\n\t}\n\tspResponse := &types.StoragePool{}\n\terr := sp.client.executeWithRetryAuthenticate(ctx, http.MethodGet, f... |
decodeHTTPSumRequest is a transport/http.DecodeRequestFunc that decodes a JSONencoded request from the HTTP request body. Primarily useful in a server. | func decodeHTTPSumRequest(_ context.Context, r *http.Request) (interface{}, error) {
var req endpoints.SumRequest
err := json.NewDecoder(r.Body).Decode(&req)
return req, err
} | [
"func decodeHTTPNewJobRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\tvar req endpoint.NewJobRequest\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}",
"func BasicDecodeRequest(ctx context.Context, req *http.Request) (interface{}, error) {\n\treturn DecodeRequestWithHeade... |
SortStable sorts slice of HelpAppUpdate. | func (s HelpAppUpdateArray) SortStable(less func(a, b HelpAppUpdate) bool) HelpAppUpdateArray {
sort.SliceStable(s, func(i, j int) bool {
return less(s[i], s[j])
})
return s
} | [
"func (s EncryptedChatRequestedArray) SortByDate() EncryptedChatRequestedArray {\n\treturn s.Sort(func(a, b EncryptedChatRequested) bool {\n\t\treturn a.GetDate() < b.GetDate()\n\t})\n}",
"func (p SliceUI) Sort() { sort.Sort(p) }",
"func (s HelpAppUpdateClassArray) Sort(less func(a, b HelpAppUpdateClass) bool) ... |
New creates a Server with zerodown.Listener, and use defines parameters in server for running an HTTP server. It will listen on server.Addr | func New(server *http.Server) (*Server, error) {
listener, err := zerodown.Listen("tcp", server.Addr)
if err != nil {
return nil, err
}
return &Server{
server: server,
listener: listener,
}, nil
} | [
"func NewServer() *Server {\n\n\treturn &Server{\n\t\tConfig: Config{\n\t\t\tPort: \":8080\",\n\t\t},\n\t}\n}",
"func New(auth Authorizer, errorWriter ErrorWriter, clean CleanCredentials) *Server {\n\treturn &Server{\n\t\tpeers: map[string]peer{},\n\t\tauthorizer: auth,\n\t\tcleanCredentials: cle... |
AssignProperties_To_Servers_ConnectionPolicy_STATUS populates the provided destination Servers_ConnectionPolicy_STATUS from our Servers_ConnectionPolicy_STATUS | func (policy *Servers_ConnectionPolicy_STATUS) AssignProperties_To_Servers_ConnectionPolicy_STATUS(destination *v20211101s.Servers_ConnectionPolicy_STATUS) error {
// Create a new property bag
propertyBag := genruntime.NewPropertyBag()
// Conditions
destination.Conditions = genruntime.CloneSliceOfCondition(policy.Conditions)
// ConnectionType
if policy.ConnectionType != nil {
connectionType := string(*policy.ConnectionType)
destination.ConnectionType = &connectionType
} else {
destination.ConnectionType = nil
}
// Id
destination.Id = genruntime.ClonePointerToString(policy.Id)
// Kind
destination.Kind = genruntime.ClonePointerToString(policy.Kind)
// Location
destination.Location = genruntime.ClonePointerToString(policy.Location)
// Name
destination.Name = genruntime.ClonePointerToString(policy.Name)
// Type
destination.Type = genruntime.ClonePointerToString(policy.Type)
// Update the property bag
if len(propertyBag) > 0 {
destination.PropertyBag = propertyBag
} else {
destination.PropertyBag = nil
}
// No error
return nil
} | [
"func (trigger *RequestsBasedTrigger_STATUS) AssignProperties_To_RequestsBasedTrigger_STATUS(destination *v20220301s.RequestsBasedTrigger_STATUS) error {\n\t// Clone the existing property bag\n\tpropertyBag := genruntime.NewPropertyBag(trigger.PropertyBag)\n\n\t// Count\n\tdestination.Count = genruntime.ClonePointe... |
SetUUID adds the uuid to the application component snapshot collection get params | func (o *ApplicationComponentSnapshotCollectionGetParams) SetUUID(uuid *string) {
o.UUID = uuid
} | [
"func (o *QtreeCollectionGetParams) SetSvmUUID(svmUUID *string) {\n\to.SvmUUID = svmUUID\n}",
"func (ec *ExperienceCreate) SetUUID(u uuid.UUID) *ExperienceCreate {\n\tec.mutation.SetUUID(u)\n\treturn ec\n}",
"func (pc *PetCreate) SetUUID(u uuid.UUID) *PetCreate {\n\tpc.mutation.SetUUID(u)\n\treturn pc\n}",
"f... |
Decode transform the geohash string to a latitude && longitude location | func Decode(geohashStr string) (float64, float64, error) {
latitudeRange, longtitudeRange, err := decodeToRange(geohashStr)
if err != nil {
return 0, 0, err
}
return latitudeRange.GetMidVal(), longtitudeRange.GetMidVal(), nil
} | [
"func Neigbors(hashstring string) []string {\n\thashLen := len(hashstring)\n\n\tposition, errs := Decode(hashstring)\n\tlat := position[0]\n\tlon := position[1]\n\tlatErr := errs[0] * 2\n\tlonErr := errs[1] * 2\n\n\thashList := []string{}\n\tfor i := -1; i < 2; i++ {\n\t\tfor j := -1; j < 2; j++ {\n\t\t\tif i == 0 ... |
New read config file | func New(configFile string) *Config {
c, err := ioutil.ReadFile(configFile)
if err != nil {
log.Panicf("Read config file %s failed: %s", configFile, err.Error())
}
cfg := &Config{}
if err := yaml.Unmarshal(c, cfg); err != nil {
log.Panicf("yaml.Unmarshal config file %s failed: %s", configFile, err.Error())
}
return cfg
} | [
"func readConfig() (*koanf.Koanf, error) {\n\tvar k = koanf.New(\".\")\n\tf := flag.NewFlagSet(\"terrakube\", flag.ExitOnError)\n\tf.String(\"input\", \"STDIN\", \"Input directory/file(s) containing the Kubernetes YAML manifests.\")\n\tf.String(\"output\", \"STDOUT\", \"Output file for the generated terraform confi... |
NOTE put it to helper | func query_param(query_data map[string][]string) *pagination.QueryParam {
qp := new(pagination.QueryParam)
if len(query_data["page"]) > 0 {
page, err := strconv.Atoi(query_data["page"][0])
if err == nil {
qp.Page = page
}
}
if len(query_data["per_page"]) > 0 {
page, err := strconv.Atoi(query_data["per_page"][0])
if err == nil {
qp.Per_page = page
}
}
if len(query_data["value"]) > 0 {
qp.Value = query_data["value"][0]
}
if len(query_data["filter"]) > 0 {
qp.Filter, _ = strconv.ParseBool(query_data["filter"][0])
}
return qp
} | [
"func (ls *ListStack) containsHelper(item adts.ContainerElement) bool {\n\tfor tmp := ls.backer.Front(); tmp != nil; tmp = tmp.Next() {\n\t\tif v, ok := tmp.Value.(adts.ContainerElement); ok {\n\t\t\tif v.Equals(item) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}",
"func getHelper(nodeRPC strin... |
Query returns a query builder for Veterinarian. | func (c *VeterinarianClient) Query() *VeterinarianQuery {
return &VeterinarianQuery{config: c.config}
} | [
"func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} }",
"func (c *BeerClient) Query() *BeerQuery {\n\treturn &BeerQuery{\n\t\tconfig: c.config,\n\t}\n}",
"func (dao *VillageDAO) Query(rs app.RequestScope, offset, limit int, districtID int) ([]models.Village, error) {\n\tvillages := []... |
BuildAuthRequestCode builds the string representation of the auth code | func BuildAuthRequestCode(authReq AuthRequest, crypto Crypto) (string, error) {
return crypto.Encrypt(authReq.GetID())
} | [
"func BuildRPCToken(client, service, method string) ([]byte, error) {\n\ttok := RPCToken{\n\t\tClient: client,\n\t\tKind: TokenKindRPC,\n\t\tService: service,\n\t\tMethod: method,\n\t}\n\n\treturn json.Marshal(tok)\n}",
"func (a *AuthorizationsService) AuthorizationCode(redirectURL string) (string, error) {\... |
eat the next Rune from input | func (l *Lexer) next() rune {
r, width := utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += width
// log.Printf("[next] %s", l.debugString())
return r
} | [
"func (s *scanner) peek() rune {\n\tr := s.next()\n\ts.backup()\n\treturn r\n}",
"func (s *Scanner) nextRune() rune {\n\tr, _, err := s.r.ReadRune()\n\tif err != nil {\n\t\tif err != io.EOF {\n\t\t\tfmt.Fprintln(os.Stderr)\n\t\t}\n\t\tr = -1 // EOF rune\n\t}\n\treturn r\n}",
"func (l *Lexer) AcceptRun(valid str... |
Changed returns neighbors list update event chan. | func (a *PlaylistSongsHandler) Changed() <-chan struct{} {
return a.changed
} | [
"func (ctrler CtrlDefReactor) OnNodeUpdate(oldObj *Node, newObj *cluster.Node) error {\n\tlog.Info(\"OnNodeUpdate is not implemented\")\n\treturn nil\n}",
"func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsFilterer) WatchConfigChanged(opts *bind.WatchOpts, sink chan<- *UpkeepRegistrationRequestsConfigC... |
Swap atomically swaps the wrapped chainhash.ListTransactionsResult and returns the old value. | func (at *ListTransactionsResult) Swap(
n []btcjson.ListTransactionsResult,
) []btcjson.ListTransactionsResult {
o := at.v.Load().([]btcjson.ListTransactionsResult)
at.v.Store(n)
return o
} | [
"func (list VulnerabilityList) Swap(i, j int) {\n\ttemp := list[i]\n\tlist[i] = list[j]\n\tlist[j] = temp\n}",
"func (_IUniswapV2Router02 *IUniswapV2Router02Transactor) SwapExactTokensForETHSupportingFeeOnTransferTokens(opts *bind.TransactOpts, amountIn *big.Int, amountOutMin *big.Int, path []common.Address, to c... |
checkIfOldestFuturesCanReplace checks when there ara different oldest future blocks in different 2f+1 nodes, if there is a oldest future block can replace others | func (n *Node) checkIfOldestFuturesCanReplace(oldestFutureMsgs []*hbft.OldestFutureMsg, currentSeqID, currentViewID uint64) (bool, common.Hash, bool) {
differentFutureCntMap := make(map[common.Hash]int)
differentFutureMsgMap := make(map[common.Hash]*hbft.OldestFutureMsg)
differentFuturePrimMap := make(map[string]int)
// Check view and signature
cnt := 0
for _, oldestFutureMsg := range oldestFutureMsgs {
if oldestFutureMsg.SequenceID == currentSeqID &&
oldestFutureMsg.ViewID == currentViewID {
if err := n.checkMsgSignature(oldestFutureMsg); err != nil {
n.HBFTDebugInfo(fmt.Sprintf("checkIfOldestFuturesCanReplace failed, check signature failed, %s", err.Error()))
return false, common.Hash{}, false
}
if _, ok := differentFuturePrimMap[oldestFutureMsg.ViewPrimary]; ok {
n.HBFTDebugInfo("checkIfOldestFuturesCanReplace failed, duplicated prim")
return false, common.Hash{}, false
} else {
differentFuturePrimMap[oldestFutureMsg.ViewPrimary] = 1
}
if oldestFutureMsg.OldestFuture != nil {
differentFutureMsgMap[oldestFutureMsg.OldestFuture.Hash()] = oldestFutureMsg
} else {
differentFutureMsgMap[common.Hash{}] = oldestFutureMsg
}
cnt++
}
}
if cnt <= n.EleBackend.Get2fRealSealersCnt() {
n.HBFTDebugInfo("checkIfOldestFuturesCanReplace failed, check view failed")
return false, common.Hash{}, false
}
for _, oldestFutureMsg := range oldestFutureMsgs {
if !oldestFutureMsg.NoAnyFutures {
if _, ok := differentFutureCntMap[oldestFutureMsg.OldestFuture.Hash()]; !ok {
differentFutureCntMap[oldestFutureMsg.OldestFuture.Hash()] = 1
} else {
differentFutureCntMap[oldestFutureMsg.OldestFuture.Hash()] += 1
}
} else {
continue
}
}
if len(differentFutureCntMap) == 1 {
for hash, cnt := range differentFutureCntMap {
if cnt > n.EleBackend.Get2fRealSealersCnt()/2 {
return true, hash, true
} else {
return true, hash, false
}
}
}
oldestFutureBlockToReturn := common.Hash{}
maxValue := uint64(0)
for hash, cnt := range differentFutureCntMap {
if cnt > n.EleBackend.Get2fRealSealersCnt()/2 {
return true, hash, true
} else {
if differentFutureMsgMap[hash].Completed.ReqTimeStamp > maxValue && !common.EmptyHash(hash) {
maxValue = differentFutureMsgMap[hash].Completed.ReqTimeStamp
oldestFutureBlockToReturn = hash
}
//if differentFutureMsgMap[hash].Completed.BlockNum == 1 {
// if differentFutureMsgMap[hash].Completed.ReqTimeStamp > maxValue {
// maxValue = differentFutureMsgMap[hash].Completed.ReqTimeStamp
// oldestFutureBlockToReturn = hash
// }
//} else {
// if differentFutureMsgMap[hash].Completed.ReqTimeStamp > maxValue {
// maxValue = differentFutureMsgMap[hash].Completed.ReqTimeStamp
// oldestFutureBlockToReturn = hash
// }
//}
}
}
if !common.EmptyHash(oldestFutureBlockToReturn) {
return true, oldestFutureBlockToReturn, true
}
n.HBFTDebugInfo("checkIfOldestFuturesCanReplace failed")
return false, common.Hash{}, false
} | [
"func isOVNKubernetesChangeSafe(prev, next *operv1.NetworkSpec) []error {\n\tpn := prev.DefaultNetwork.OVNKubernetesConfig\n\tnn := next.DefaultNetwork.OVNKubernetesConfig\n\terrs := []error{}\n\n\tif next.Migration != nil && next.Migration.MTU != nil {\n\t\tmtuNet := next.Migration.MTU.Network\n\t\tmtuMach := next... |
ABI returns the ABI associated with a name | func (r *Resolver) ABI(name string) (string, error) {
contentTypes := big.NewInt(3)
nameHash, err := NameHash(name)
if err != nil {
return "", err
}
contentType, data, err := r.Contract.ABI(nil, nameHash, contentTypes)
var abi string
if err == nil {
if contentType.Cmp(big.NewInt(1)) == 0 {
// Uncompressed JSON
abi = string(data)
} else if contentType.Cmp(big.NewInt(2)) == 0 {
// Zlib-compressed JSON
b := bytes.NewReader(data)
var z io.ReadCloser
z, err = zlib.NewReader(b)
if err != nil {
return "", err
}
defer z.Close()
var uncompressed []byte
uncompressed, err = ioutil.ReadAll(z)
if err != nil {
return "", err
}
abi = string(uncompressed)
}
}
return abi, nil
} | [
"func (*bzlLibraryLang) Name() string { return languageName }",
"func BiosName() (string, error) {\n\t/*\n\t\tSample output of 'wmic bios get manufacturer'\n\n\t\tManufacturer\n\t\tLENOVO\n\t*/\n\tresult, err := readAndParseFromCommandLine(biosNameCmd)\n\tif err != nil {\n\t\treturn \"-1\", err\n\t}\n\n\tbiosName... |
dfs_traverse looks for the end point and returns a path or an error if we cannot get there | func (m *Maze) dfs_traverse(cp *Point, tr *traverser, path []*Point) ([]*Point, error) {
// we made it to the destination! return the path and get out!
if cp.IsDestination {
return path, nil
}
// nothing more to visit and there was no destination
if tr.isVisitComplete() {
return []*Point{}, errors.New("destination unreachable")
}
// change the current point - DFS pops the last node, as a stack
cp = tr.popLastNode()
// next point has already been visited
if tr.isNodeVisited(cp) {
return m.dfs_traverse(cp, tr, path)
}
tr.enqueueNodes(m.getLegalNextMoves(cp))
tr.visitNode(cp)
newPath := append(path, cp)
return m.dfs_traverse(cp, tr, newPath)
} | [
"func (d *Dijkstra) PathToTarget() ([]graphEdge, error) {\n\tif d.err != nil {\n\t\treturn []graphEdge{}, d.err\n\t}\n\n\tvar path []graphEdge\n\tidx := d.target\n\tfor {\n\t\tif idx == d.source {\n\t\t\tbreak\n\t\t}\n\t\te, ok := d.spt[idx]\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tpath = append(path, e)\n\t\tidx = e... |
SetStat set all stat cache(redis) | func (r *RPC) SetStat(c context.Context, arg *model.ArgStats, res *struct{}) (err error) {
err = r.s.SetStat(c, arg.Aid, arg.Stats)
return
} | [
"func (fc *fileCache) Set(key, value string, ttl int) {\n\tfc.cache.Set(key, &cacheObject{\n\t\tValue: value,\n\t\tTimestamp: time.Now().Unix(),\n\t\tTTL: ttl,\n\t})\n\tfc.dirty = true\n}",
"func (c *FakeZkConn) Set(path string, data []byte, version int32) (*zk.Stat, error) {\n\tc.history.addToHistory(\... |
Value implementation of driver.Valuer | func (number Number) Value() (value driver.Value, err error) {
if number == "" {
return "", nil
}
if err = number.Validate(); err != nil {
return nil, err
}
return number.String(), nil
} | [
"func (i Item) Value() interface{} {\n\treturn i.v\n}",
"func (v Value2) Get() any { return int(v) }",
"func (u UUID) Value() (driver.Value, error) {\n\treturn []byte(u), nil\n}",
"func (v Vars) Value() (driver.Value, error) {\n\tm := make(map[string]sql.NullString)\n\n\tfor k, v := range v {\n\t\tm[string(k)... |
RefreshOAuth2Token will fetch a new API Key / Access Token from a refresh token | func RefreshOAuth2Token(client *http.Client, channel string, provider string, refreshToken string) (string, error) {
theurl := sdk.JoinURL(
api.BackendURL(api.AuthService, channel),
fmt.Sprintf("oauth2/%s/refresh/%s", provider, url.PathEscape(refreshToken)),
)
req, err := http.NewRequest(http.MethodGet, theurl, nil)
if err != nil {
return "", err
}
api.SetUserAgent(req)
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", err
}
var res struct {
AccessToken string `json:"access_token"`
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return "", err
}
if res.AccessToken == "" {
return "", errors.New("new token not returned, refresh_token might be bad")
}
return res.AccessToken, nil
} | [
"func (c *Client) Refresh(refreshToken string) (*gocloak.JWT, error) {\n\t// c.l.Started(\"Refresh\")\n\tt, err := c.kc.RefreshToken(c.ctx, refreshToken, c.client.clientID, c.cfg.ClientSecret, c.realm)\n\tif err != nil {\n\t\t// c.l.Errorf(\"Refresh\", err, \"failed refresh\")\n\t\treturn nil, err\n\t}\n\t// c.l.Co... |
BazelMetricsFilename returns the bazel profile filename based on the action name. This is to help to store a set of bazel profiles since bazel may execute multiple times during a single build. | func BazelMetricsFilename(s SharedPaths, actionName bazel.RunName) string {
return filepath.Join(s.BazelMetricsDir(), actionName.String()+"_bazel_profile.gz")
} | [
"func (o MrScalarCoreScalingDownPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingDownPolicy) string { return v.MetricName }).(pulumi.StringOutput)\n}",
"func (o ElastigroupScalingUpPolicyOutput) MetricName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupSc... |
IDsX is like IDs, but panics if an error occurs. | func (fdq *FurnitureDetailQuery) IDsX(ctx context.Context) []int {
ids, err := fdq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
} | [
"func (liq *LineItemQuery) IDsX(ctx context.Context) []uuid.UUID {\n\tids, err := liq.IDs(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ids\n}",
"func (ecpq *EntityContactPointQuery) IDsX(ctx context.Context) []int {\n\tids, err := ecpq.IDs(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ids\n}",
... |
String returns the string representation | func (s Expression) String() string {
return awsutil.Prettify(s)
} | [
"func (i NotMachine) String() string { return toString(i) }",
"func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}",
"func (o QtreeCreateResponseResult) String() string {\n\treturn ToString(reflect.Va... |
Concat returns a new operator node as a result of the fn.Concat function. | func (g *Graph) Concat(xs ...Node) Node {
return g.NewOperator(fn.NewConcat(Operands(xs)), xs...)
} | [
"func MOVSHDUP(mx, x operand.Op) { ctx.MOVSHDUP(mx, x) }",
"func Add(a, b NumberArray) (resultingMatrix NumberArray, err error) {\n\treturn binaryOperation(\"Add\", a, b)\n}",
"func AddToOperator(m manager.Manager) error {\n\tfor _, f := range AddToOperatorFuncs {\n\t\tif err := f(m); err != nil {\n\t\t\treturn... |
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil. | func (in *ScheduledSparkApplicationSpec) DeepCopyInto(out *ScheduledSparkApplicationSpec) {
*out = *in
in.Template.DeepCopyInto(&out.Template)
if in.Suspend != nil {
in, out := &in.Suspend, &out.Suspend
*out = new(bool)
**out = **in
}
if in.SuccessfulRunHistoryLimit != nil {
in, out := &in.SuccessfulRunHistoryLimit, &out.SuccessfulRunHistoryLimit
*out = new(int32)
**out = **in
}
if in.FailedRunHistoryLimit != nil {
in, out := &in.FailedRunHistoryLimit, &out.FailedRunHistoryLimit
*out = new(int32)
**out = **in
}
return
} | [
"func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}",
"func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots... |
CheckDescriptionLength checks if the given PR's description contains enough number of arguments | func CheckDescriptionLength(pr *gogh.PullRequest, config PluginConfiguration, logger log.Logger) string {
actualLength := len(strings.TrimSpace(issueLinkRegexp.ReplaceAllString(pr.GetBody(), "")))
if actualLength < config.DescriptionContentLength {
return fmt.Sprintf(DescriptionLengthShortMessage, config.DescriptionContentLength, actualLength)
}
return ""
} | [
"func invalidLength(offset, length, sliceLength int) bool {\n\treturn offset+length < offset || offset+length > sliceLength\n}",
"func TestLengths(t *testing.T) {\n // strings\n for k, v := range testStr {\n val := LenString(k)\n if val != v {\n t.Fatalf(\"%v returned %v (expected %... |
Float64 returns a single float64 from selector. It is only allowed when selecting one field. | func (fds *FurnitureDetailSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = fds.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{furnituredetail.Label}
default:
err = fmt.Errorf("ent: FurnitureDetailSelect.Float64s returned %d results when one was expected", len(v))
}
return
} | [
"func (e *Element) GetFloat64(key string) float64 {\n\tval, _ := e.Get(key)\n\tassertedVal, ok := val.(float64)\n\tif !ok {\n\t\tassertedVal = 0\n\t}\n\treturn assertedVal\n}",
"func (ups *UnsavedPostSelect) Float64(ctx context.Context) (_ float64, err error) {\n\tvar v []float64\n\tif v, err = ups.Float64s(ctx);... |
respecify a portion of a color table | func CopyColorSubTable(target uint32, start int32, x int32, y int32, width int32) {
C.glowCopyColorSubTable(gpCopyColorSubTable, (C.GLenum)(target), (C.GLsizei)(start), (C.GLint)(x), (C.GLint)(y), (C.GLsizei)(width))
} | [
"func (c *Colorscheme) tcellColor(name string) tcell.Color {\n\tv, ok := c.colors[name].(string)\n\tif !ok {\n\t\treturn tcell.ColorDefault\n\t}\n\n\tif color, found := TcellColorschemeColorsMap[v]; found {\n\t\treturn color\n\t}\n\n\tcolor := tcell.GetColor(v)\n\tif color != tcell.ColorDefault {\n\t\treturn color\... |
resolveSystemRegistry find all image field in yaml content and replace with new image value which system registry prefixed | func resolveSystemRegistry(content string) string {
if settings.SystemDefaultRegistry.Get() == "" {
return content
}
exp := `image:.*`
return regexp.MustCompile(exp).ReplaceAllStringFunc(content, replaceImage)
} | [
"func (rt *ReplicateTasks) processKustomizeDir(absPath string, registry string, include string, exclude string) error {\n\tlog.Infof(\"Processing %v\", absPath)\n\tkustomizationFilePath := filepath.Join(absPath, \"kustomization.yaml\")\n\tif _, err := os.Stat(kustomizationFilePath); err != nil {\n\t\tlog.Infof(\"Sk... |
Deprecated: Use VmxcTxHistory.ProtoReflect.Descriptor instead. | func (*VmxcTxHistory) Descriptor() ([]byte, []int) {
return file_wallet_proto_rawDescGZIP(), []int{20}
} | [
"func (*StateMachineLogEntryProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{6}\n}",
"func (*EpochChange) Descriptor() ([]byte, []int) {\n\treturn file_msgs_msgs_proto_rawDescGZIP(), []int{21}\n}",
"func (*IntegrationChangeHistoryListResp) Descriptor() ([]byte, []int) {\n\tre... |
/ Creates a file if it does not already exist. | func CreateFileIfNotExists(path string) error {
exists, er := FilePathExists(path)
if er != nil {
return er
} else {
if !exists {
var file, err = os.Create(path)
if err != nil {
return err
}
defer file.Close()
}
}
return nil
} | [
"func CreateFile(fileName string, canAppend bool) *os.File {\n\tfileMode := os.O_TRUNC\n\n\tif canAppend {\n\t\tfileMode = os.O_APPEND\n\t}\n\n\tfile, err := os.OpenFile(fileName, fileMode|os.O_CREATE|os.O_WRONLY, 0644)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn file\n\n}",
"func createDefaultFileIfN... |
DeleteRecord indicates an expected call of DeleteRecord | func (mr *MockDBStorageMockRecorder) DeleteRecord(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRecord", reflect.TypeOf((*MockDBStorage)(nil).DeleteRecord), arg0, arg1, arg2)
} | [
"func (mr *MockFlagMockRecorder) Delete(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockFlag)(nil).Delete), arg0, arg1)\n}",
"func (mr *ClientMockRecorder) Delete(arg0, arg1 interface{}) *gomock.Call {\n\tm... |
Remove jwt token from db. Remove user access. | func (gs *GateService) Logout(ctx context.Context, opaque string) error {
return gs.repo.RemoveToken(ctx, opaque)
} | [
"func revokeMT(tx *sqlx.Tx, id mtid.MTID) error {\n\treturn db.RunWithinTransaction(tx, func(tx *sqlx.Tx) error {\n\t\tif err := encryptionkeyrepo.DeleteEncryptionKey(tx, id); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err := tx.Exec(`DELETE FROM MTokens WHERE id=?`, id)\n\t\treturn errors.WithStack(err)\n\t})\n... |
NewDockerMemoryStatsUpdate returns the fields that have been updated since the last measurement. It returns nil if nothing has changed. | func NewDockerMemoryStatsUpdate(prev, next docker.ContainerMemoryStats) *DockerMemoryStatsUpdate {
if prev == next {
return nil
}
var delta DockerMemoryStatsUpdate
if prev.Usage != next.Usage {
delta.Usage = &next.Usage
}
if prev.MaxUsage != next.MaxUsage {
delta.MaxUsage = &next.MaxUsage
}
if prev.Limit != next.Limit {
delta.Limit = &next.Limit
}
if prev.Stats == next.Stats {
return &delta
}
if prev.Stats.ActiveAnon != next.Stats.ActiveAnon {
delta.ActiveAnon = &next.Stats.ActiveAnon
}
if prev.Stats.ActiveFile != next.Stats.ActiveFile {
delta.ActiveFile = &next.Stats.ActiveFile
}
if prev.Stats.InactiveAnon != next.Stats.InactiveAnon {
delta.InactiveAnon = &next.Stats.InactiveAnon
}
if prev.Stats.InactiveFile != next.Stats.InactiveFile {
delta.InactiveFile = &next.Stats.InactiveFile
}
if prev.Stats.TotalCache != next.Stats.TotalCache {
delta.TotalCache = &next.Stats.TotalCache
}
if prev.Stats.TotalRss != next.Stats.TotalRss {
delta.TotalRss = &next.Stats.TotalRss
}
return &delta
} | [
"func getMmStat(ctx context.Context) ([]float64, error) {\n\tout, err := testexec.CommandContext(ctx,\n\t\t\"cat\", zramMmStatPath).Output(testexec.DumpLogOnError)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to dump zram mm_stat\")\n\t}\n\n\tstatsRaw := strings.Fields(string(out))\n\tnumFields := ... |
resetPassword actually resets the users password. Based on data provided and generated | func resetPassword(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// take email, token and new password
body := struct {
Email string `json:"email"`
OTP string `json:"otp"`
Password string `json:"password"`
}{}
err := json.NewDecoder(r.Body).Decode(&body)
log.ErrorHandler(err)
// check email for existence
var user User
err = db.Find(&user, "email = ?", body.Email).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
w.WriteHeader(http.StatusUnauthorized)
log.ErrorHandler(err)
err = json.NewEncoder(w).Encode(core.FourOOne)
log.ErrorHandler(err)
log.AccessHandler(r, 401)
return
}
// check if token exists
storedOtp, err := redisClient.Get(ctx, "password_reset_"+body.Email).Result()
log.ErrorHandler(err)
if storedOtp != body.OTP {
w.WriteHeader(http.StatusUnauthorized)
err = json.NewEncoder(w).Encode(core.FourOOne)
log.ErrorHandler(err)
log.AccessHandler(r, 401)
return
}
// validate password
safePassword := passwordValidator(body.Password)
if !safePassword {
w.WriteHeader(http.StatusUnprocessableEntity)
err = json.NewEncoder(w).Encode(core.FourTwoTwo)
log.ErrorHandler(err)
log.AccessHandler(r, 422)
return
}
// Generate password hash and save
hashedPassword, err := generatePasswordHash(body.Password)
log.ErrorHandler(err)
user.Password = hashedPassword
db.Save(&user)
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(core.TwoHundred)
log.ErrorHandler(err)
log.AccessHandler(r, 200)
// Delete from redis
redisClient.Del(ctx, "password_reset_"+body.Email)
return
} | [
"func ForgetPassword(input *User) (*User, error) {\n\tuser := getUserByEmail(input.Email)\n\n\tif user == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid email address.\")\n\t} else if user.ActivationCode != nil {\n\t\treturn nil, fmt.Errorf(\"Please activate your account first.\")\n\t}\n\n\t// Store the reset password... |
if error of reading the body it prinnts a fragment (perhaps empty) of the body instead of head tag if is not a head tag it prints only error | func printHeadTag(r *http.Response) {
var head string
var err error
var b = bytes.NewBuffer(nil)
var n int64
var openInd, closeInd int
//if len(r.Body) == 0 {
// fmt.Printf("getrequester.getHeadTag: no body\n")
// return
//}
if n, err = b.ReadFrom(r.Body); err != nil {
fmt.Printf("getrequester.getHeadTag err=%v\n", err.Error())
head = b.String()
if head == "" {
fmt.Printf("getrequester.getHeadTag: nothing was read from the body\n")
} else {
fmt.Printf("%v\n", head)
}
return
}
if n == 0 {
fmt.Printf("getrequester.getHeadTag: no body\n")
return
}
r.Body.Close()
openInd = strings.Index(b.String(), "<head>")
closeInd = strings.Index(b.String(), "</head>")
if openInd == -1 || closeInd == -1 {
fmt.Printf("getrequester.getHeadTag no head tag (%v;%v)", openInd, closeInd)
return
}
head = b.String()
head = head[openInd : closeInd+6]
fmt.Printf("%v\n", head)
} | [
"func pagemain(w http.ResponseWriter, r *http.Request){\n w.Write([]byte( `\n <!doctype html>\n <title>Ciao</title>\n <h1>Come stai</h1>\n <img src=\"https://www.4gamehz.com/wp-content/uploads/2019/10/league-of-legends-4.jpg\">\n `))\n }",
"func (self *Client) body(res *ht... |
Children implements the Node interface. | func (n UnaryNode) Children() []sql.Node {
return []sql.Node{n.Child}
} | [
"func (r *postExternalLinkResolver) Children(ctx context.Context, post *posts.ExternalLink, first *int, after *string) (*graphql.PostResultCursor, error) {\n\tif first == nil {\n\t\tthree := 3\n\t\tfirst = &three\n\t}\n\treturn children(ctx, r.postService, post.ID, first, after)\n}",
"func (b *BaseElement) GetChi... |
Execute is ExecuteFetch without the maxrows. | func (vc *vdbClient) Execute(query string) (*sqltypes.Result, error) {
// Number of rows should never exceed relayLogMaxItems.
return vc.ExecuteFetch(query, relayLogMaxItems)
} | [
"func (e *storageExecutor) Execute() {\n\t// do query validation\n\tif err := e.validation(); err != nil {\n\t\te.queryFlow.Complete(err)\n\t\treturn\n\t}\n\n\t// get shard by given query shard id list\n\tfor _, shardID := range e.ctx.shardIDs {\n\t\tshard, ok := e.database.GetShard(shardID)\n\t\t// if shard exist,... |
The zone of the EIP.This parameter is returned only for whitelist users that are visible to the zone. The following arguments will be discarded. Please use new fields as soon as possible: | func (o EipAddressOutput) Zone() pulumi.StringOutput {
return o.ApplyT(func(v *EipAddress) pulumi.StringOutput { return v.Zone }).(pulumi.StringOutput)
} | [
"func (europ europeTimeZones) Jersey() string {return \"Europe/Jersey\" }",
"func (europ europeTimeZones) Zurich() string {return \"Europe/Zurich\" }",
"func (ip IP) Zone() string {\n\tif ip.z == nil {\n\t\treturn \"\"\n\t}\n\tzone, _ := ip.z.Get().(string)\n\treturn zone\n}",
"func (o LiteSubscriptionOutput)... |
StderrPipe returns a pipe that will be connected to the command's standard error when the command starts. Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves; however, an implication is that it is incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use Run when using StderrPipe. See the StdoutPipe example for idiomatic usage. | func (c *Cmd) StderrPipe() (io.ReadCloser, error) | [
"func (c *Cmd) StderrPipe() (io.ReadCloser, error) {\n\treturn c.Cmd.StderrPipe()\n}",
"func (m *MinikubeRunner) teeRun(cmd *exec.Cmd, waitForRun ...bool) (string, string, error) {\n\tw := true\n\tif waitForRun != nil {\n\t\tw = waitForRun[0]\n\t}\n\n\terrPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tretu... |
NextPage returns true if the pager advanced to the next page. Returns false if there are no more pages or an error occurred. | func (p *DeploymentScriptsListByResourceGroupPager) NextPage(ctx context.Context) bool {
var req *policy.Request
var err error
if !reflect.ValueOf(p.current).IsZero() {
if p.current.DeploymentScriptListResult.NextLink == nil || len(*p.current.DeploymentScriptListResult.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.pl.Do(req)
if err != nil {
p.err = err
return false
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
p.err = p.client.listByResourceGroupHandleError(resp)
return false
}
result, err := p.client.listByResourceGroupHandleResponse(resp)
if err != nil {
p.err = err
return false
}
p.current = result
return true
} | [
"func (p *ExpressRoutePortsClientListPager) NextPage(ctx context.Context) bool {\n\tvar req *policy.Request\n\tvar err error\n\tif !reflect.ValueOf(p.current).IsZero() {\n\t\tif p.current.ExpressRoutePortListResult.NextLink == nil || len(*p.current.ExpressRoutePortListResult.NextLink) == 0 {\n\t\t\treturn false\n\t... |
Value returns value of field | func (f *Fieldx) Value() interface{} {
return f.value.Interface()
} | [
"func (e PciValidationError) Field() string { return e.field }",
"func (e GetResponseValidationError) Field() string { return e.field }",
"func (e RetrieveBookingResponseValidationError) Field() string { return e.field }",
"func (n Number) Value() (driver.Value, error) {\n\treturn string(n), nil\n}",
"func ... |
NewSimpleController create an instance of Controller | func NewSimpleController(cfg *Config, crd CRD, handler Handler) Controller {
if cfg == nil {
cfg = &Config{}
}
cfg.setDefaults()
// queue
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
resourceEventHandlerFuncs := cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
UpdateFunc: func(old interface{}, new interface{}) {
key, err := cache.MetaNamespaceKeyFunc(new)
if err == nil {
queue.Add(key)
}
},
DeleteFunc: func(obj interface{}) {
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
}
// indexer and informer
indexer, informer := cache.NewIndexerInformer(
crd.GetListerWatcher(),
crd.GetObject(),
0,
resourceEventHandlerFuncs,
cache.Indexers{})
// Create the SimpleController Instance
return &SimpleController{
cfg: cfg,
informer: informer,
indexer: indexer,
queue: queue,
handler: handler,
}
} | [
"func NewController(cfg *config.Config) (*Controller, error) {\n\tsrv, err := service.NewService(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Controller{\n\t\tService: srv,\n\t}, nil\n}",
"func newController(clusterCfg clusterConfig) (Controller, error) {\n\tcfg := &rest.Config{\n\t\tHost: clust... |
DescribeAccountAttributesWithContext indicates an expected call of DescribeAccountAttributesWithContext | func (mr *MockRDSAPIMockRecorder) DescribeAccountAttributesWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeAccountAttributesWithContext", reflect.TypeOf((*MockRDSAPI)(nil).DescribeAccountAttributesWithContext), varargs...)
} | [
"func (o *UpdateAccountStateParams) WithContext(ctx context.Context) *UpdateAccountStateParams {\n\to.SetContext(ctx)\n\treturn o\n}",
"func (pager *AccountsPager) GetAllWithContext(ctx context.Context) (allItems []Account, err error) {\n\tfor pager.HasNext() {\n\t\tvar nextPage []Account\n\t\tnextPage, err = pag... |
MovieResult.Get() will accept url, movie provider, id and access token which will be used to retrieve a specific movie from external api. It will unmarshal the response into itself. It returns error if issue occurred. | func (m *MovieResult) Get(url, from, id, accessToken string) (error) {
//format url
url = url + "/api/" + from + "/movie/" + id
//call get request
result, err := tools.GetRequest(url, accessToken)
if err != nil {
return err
}
//check if status code is 200
if result.StatusCode != 200 {
return errors.New(string(result.ResponseBody))
}
//unmarshal response to itself
err = json.Unmarshal(result.ResponseBody, m)
if err != nil {
return err
}
return nil
} | [
"func GetMovies(w http.ResponseWriter, r *http.Request) {\n\tctx := NewContext()\n\tdefer ctx.Close()\n\n\tmgc := ctx.DBCollection(\"movies\")\n\trepo := data.NewMovieRepository(mgc)\n\tmovies := repo.GetAll()\n\tj, err := json.Marshal(MoviesData{movies})\n\tif err != nil {\n\t\tcommon.ResponseError(\n\t\t\tw, err,... |
FlatMapModelChanges is used to read and apply input events and produce a channel of Model values that will never repeat. | func (dev *Source) FlatMapModelChanges(ctx context.Context) <-chan Model {
model := Model{}
output := make(chan Model)
go func(output chan<- Model) {
defer close(output)
for {
nextModel, err := dev.Update(model)
if err != nil {
dev.Err = err
return
}
if nextModel == model {
continue
}
model = nextModel
select {
case output <- model:
case <-ctx.Done():
return
}
}
}(output)
return output
} | [
"func (r *volumeReactor) syncAll() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tfor _, c := range r.claims {\n\t\tr.changedObjects = append(r.changedObjects, c)\n\t}\n\tfor _, v := range r.volumes {\n\t\tr.changedObjects = append(r.changedObjects, v)\n\t}\n\tr.changedSinceLastSync = 0\n}",
"func (in *V1Source... |
CtrPrepareSnapshot creates snapshot for the given image | func CtrPrepareSnapshot(snapshotID string, image containerd.Image) ([]mount.Mount, error) {
if err := verifyCtr(); err != nil {
return nil, fmt.Errorf("CtrPrepareSnapshot: exception while verifying ctrd client: %s", err.Error())
}
// use rootfs unpacked image to create a writable snapshot with default snapshotter
diffIDs, err := image.RootFS(ctrdCtx)
if err != nil {
err = fmt.Errorf("CtrPrepareSnapshot: Could not load rootfs of image: %v. %v", image.Name(), err)
return nil, err
}
snapshotter := CtrdClient.SnapshotService(defaultSnapshotter)
parent := identity.ChainID(diffIDs).String()
labels := map[string]string{"containerd.io/gc.root": time.Now().UTC().Format(time.RFC3339)}
return snapshotter.Prepare(ctrdCtx, snapshotID, parent, snapshots.WithLabels(labels))
} | [
"func createImageResource(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {\n\t// Warning or errors can be collected in a slice type\n\tvar diags diag.Diagnostics\n\n\tclient := (meta.(Client)).Client\n\tname := rdEntryStr(d, \"name\")\n\tid := rdEntryStr(d, \"id\")\n\terrMsgPrefix :... |
ReadBytes read a Bytes value | func (p *Stream) ReadBytes() (Bytes, *base.Error) {
// empty bytes
v := p.readFrame[p.readIndex]
if v == 192 {
if p.CanRead() {
p.gotoNextReadByteUnsafe()
return Bytes{}, nil
}
} else if v > 192 && v < 255 {
bytesLen := int(v - 192)
ret := make(Bytes, bytesLen)
if p.isSafetyReadNBytesInCurrentFrame(bytesLen + 1) {
copy(ret, p.readFrame[p.readIndex+1:])
p.readIndex += bytesLen + 1
return ret, nil
} else if p.hasNBytesToRead(bytesLen + 1) {
copyBytes := copy(ret, p.readFrame[p.readIndex+1:])
p.readIndex += copyBytes + 1
if p.readIndex == streamBlockSize {
p.readSeg++
p.readFrame = *(p.frames[p.readSeg])
p.readIndex = copy(ret[copyBytes:], p.readFrame)
}
return ret, nil
}
} else if v == 255 {
readStart := p.GetReadPos()
bytesLen := -1
if p.isSafetyReadNBytesInCurrentFrame(5) {
b := p.readFrame[p.readIndex:]
bytesLen = int(uint32(b[1])|
(uint32(b[2])<<8)|
(uint32(b[3])<<16)|
(uint32(b[4])<<24)) - 5
p.readIndex += 5
} else if p.hasNBytesToRead(5) {
b := p.readNBytesCrossFrameUnsafe(5)
bytesLen = int(uint32(b[1])|
(uint32(b[2])<<8)|
(uint32(b[3])<<16)|
(uint32(b[4])<<24)) - 5
}
if bytesLen > 62 {
if p.isSafetyReadNBytesInCurrentFrame(bytesLen) {
ret := make(Bytes, bytesLen)
copy(ret, p.readFrame[p.readIndex:])
p.readIndex += bytesLen
return ret, nil
} else if p.hasNBytesToRead(bytesLen) {
ret := make(Bytes, bytesLen)
reads := 0
for reads < bytesLen {
readLen := copy(ret[reads:], p.readFrame[p.readIndex:])
reads += readLen
p.readIndex += readLen
if p.readIndex == streamBlockSize {
p.gotoNextReadFrameUnsafe()
}
}
return ret, nil
}
}
p.SetReadPos(readStart)
}
return Bytes{}, base.ErrStream
} | [
"func (r *Reader) ReadBytes(length int) []byte {\n\tif len(r.buffer) <= r.index+length-1 {\n\t\tlog.Panic(\"Error reading []byte: buffer is too small!\")\n\t}\n\n\tvar data = r.buffer[r.index : r.index+length]\n\tr.index += length\n\n\treturn data\n}",
"func ReadBytes(r io.Reader) ([]byte, error) {\n\tn, err := R... |
Make sure that existing stream widgets are discarded if the user loads a new pcap. | func (t ManageCapinfoCache) OnNewSource(pcap.HandlerCode, gowid.IApp) {
clearCapinfoState()
} | [
"func (route_p *Router) unpublish(pkt_p *defs.UDPMsg, addr_p *net.UDPAddr) {\n\tpkt_p.Hops--\n\tif pkt_p.Hops < 0 {\n\t\treturn\n\t}\n}",
"func (trace *Trace) Packets() chan gopacket.Packet {\n\treturn trace.pktSource.Packets()\n}",
"func (f genHelperDecoder) DecSwallow() { f.d.swallow() }",
"func NewDiscardI... |
TransferFrom is a paid mutator transaction binding the contract method 0x23b872dd. Solidity: function transferFrom(address sender, address recipient, uint256 amount) returns(bool) | func (_StakingToken *StakingTokenSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {
return _StakingToken.Contract.TransferFrom(&_StakingToken.TransactOpts, sender, recipient, amount)
} | [
"func (_Erc20Mock *Erc20MockTransactorSession) TransferFrom(from common.Address, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Erc20Mock.Contract.TransferFrom(&_Erc20Mock.TransactOpts, from, to, value)\n}",
"func (_Bindings *BindingsTransactor) TransferFrom(opts *bind.TransactOpts, s... |
New creates a new Module with the given update count provider. By default, the module will refresh the update counts every hour. The refresh interval can be configured using `Every`. | func New(provider Provider) *Module {
m := &Module{
provider: provider,
scheduler: timing.NewScheduler(),
}
m.notifyFn, m.notifyCh = notifier.New()
m.outputFunc.Set(func(info Info) bar.Output {
if info.Updates == 1 {
return outputs.Text("1 update")
}
return outputs.Textf("%d updates", info.Updates)
})
m.Every(time.Hour)
return m
} | [
"func New(policy *Policy) *RateLimiter {\n\trl := &RateLimiter{\n\t\tpolicy: policy,\n\t\tstartTime: nowFunc(),\n\t}\n\treturn rl\n}",
"func NewProvider(t *testing.T) *Provider {\n\treturn &Provider{\n\t\tt: t,\n\t\tcounters: make(map[string]*Counter),\n\t\thistograms: make(map[string]*Histogr... |
Xor returns the xor value of two bitmap. | func (bitmap *bitmap) Xor(other *bitmap) *bitmap {
if bitmap.Size != other.Size {
panic("size not the same")
}
distance := newBitmap(bitmap.Size)
div, mod := distance.Size/8, distance.Size%8
for i := 0; i < div; i++ {
distance.data[i] = bitmap.data[i] ^ other.data[i]
}
for i := div * 8; i < div*8+mod; i++ {
distance.set(i, bitmap.Bit(i)^other.Bit(i))
}
return distance
} | [
"func bool_xor(A, B bool) bool {\n return (A && !B) || (!A && B)\n}",
"func xor(x, y bool) bool {\n\treturn (x && !y) || (!x && y)\n}",
"func encryptDecryptXor(input string, key byte) (output string) {\n for i := 0; i < len(input); i++ {\n output += string(input[i] ^ key)\n }\n return output\n}",
"fu... |
HasDescription returns a boolean if a field has been set. | func (o *Tier) HasDescription() bool {
if o != nil && o.Description != nil {
return true
}
return false
} | [
"func (o *ConnectorTypeAllOf) HasDescription() bool {\n\tif o != nil && o.Description != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o *MicrosoftGraphEducationSchool) HasDescription() bool {\n\tif o != nil && o.Description != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (o *UpdateRole)... |
AuthorizeDBSecurityGroupIngressWithContext indicates an expected call of AuthorizeDBSecurityGroupIngressWithContext | func (mr *MockRDSAPIMockRecorder) AuthorizeDBSecurityGroupIngressWithContext(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AuthorizeDBSecurityGroupIngressWithContext", reflect.TypeOf((*MockRDSAPI)(nil).AuthorizeDBSecurityGroupIngressWithContext), varargs...)
} | [
"func (mr *MockSecurityGroupServiceIfaceMockRecorder) AuthorizeSecurityGroupEgress(p interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AuthorizeSecurityGroupEgress\", reflect.TypeOf((*MockSecurityGroupServiceIface)(nil).AuthorizeSecurityGroupEgress), p... |
/ Given a project and zone name, return a fake zone link. eg. | func fakeZoneLink(project string, zone string) string {
return fmt.Sprintf("%s/projects/%s/zones/%s", gcpComputeURL, project, zone)
} | [
"func noZone(addr string) string {\n\tipMatch := ipRegex.FindStringSubmatch(addr)\n\tif len(ipMatch) == 2 {\n\t\treturn ipMatch[1]\n\t}\n\treturn addr\n}",
"func (ameri americaTimeZones) Glace_Bay() string {return \"America/Glace_Bay\" }",
"func (ameri americaTimeZones) Port_of_Spain() string {return \"America/... |
DeleteOne returns a delete builder for the given entity. | func (c *BeerClient) DeleteOne(b *Beer) *BeerDeleteOne {
return c.DeleteOneID(b.ID)
} | [
"func (c *CleanernameClient) DeleteOne(cl *Cleanername) *CleanernameDeleteOne {\n\treturn c.DeleteOneID(cl.ID)\n}",
"func (c *TitleClient) DeleteOne(t *Title) *TitleDeleteOne {\n\treturn c.DeleteOneID(t.ID)\n}",
"func (c *UnsavedPostAttachmentClient) DeleteOneID(id int) *UnsavedPostAttachmentDeleteOne {\n\tbuil... |
Query the BamAt with 0base halfopen interval. | func (b *BamAt) Query(chrom string, start int, end int) (*bam.Iterator, error) {
if chrom == "" { // stdin
return bam.NewIterator(b.Reader, nil)
}
ref := b.Refs[chrom]
if end <= 0 {
end = ref.Len() - 1
}
chunks, err := b.idx.Chunks(ref, start, end)
if err != nil {
return nil, err
}
return bam.NewIterator(b.Reader, chunks)
} | [
"func (bsn *SubBasin) baseflow(g float64) float64 {\n\t// note: no bypass flow; no partioning to deep aquifer (pg.173)\n\td1 := math.Exp(-1. / bsn.dgw)\n\tbsn.psto += g\n\tbsn.wrch = (1.-d1)*g + d1*bsn.wrch // recharge entering aquifer (pg.172)\n\tbsn.psto -= bsn.wrch // water in \"percolation\" stora... |
Get takes name of the l4Rule, and returns the corresponding l4Rule object, and an error if there is any. | func (c *FakeL4Rules) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha2.L4Rule, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(l4rulesResource, c.ns, name), &v1alpha2.L4Rule{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha2.L4Rule), err
} | [
"func (f *Finding) RuleName() string {\n\treturn f.etd.JSONPayload.DetectionCategory.RuleName\n}",
"func (rule *GameRule) GetName() GameRuleName {\n\treturn rule.name\n}",
"func (c *TestClient) GetForwardingRule(project, region, name string) (*compute.ForwardingRule, error) {\n\tif c.GetForwardingRuleFn != nil ... |
RunJSONSerializationTestForNumberNotInAdvancedFilter_STATUS_ARM runs a test to see if a specific instance of NumberNotInAdvancedFilter_STATUS_ARM round trips to JSON and back losslessly | func RunJSONSerializationTestForNumberNotInAdvancedFilter_STATUS_ARM(subject NumberNotInAdvancedFilter_STATUS_ARM) string {
// Serialize to JSON
bin, err := json.Marshal(subject)
if err != nil {
return err.Error()
}
// Deserialize back into memory
var actual NumberNotInAdvancedFilter_STATUS_ARM
err = json.Unmarshal(bin, &actual)
if err != nil {
return err.Error()
}
// Check for outcome
match := cmp.Equal(subject, actual, cmpopts.EquateEmpty())
if !match {
actualFmt := pretty.Sprint(actual)
subjectFmt := pretty.Sprint(subject)
result := diff.Diff(subjectFmt, actualFmt)
return result
}
return ""
} | [
"func RunJSONSerializationTestForNatGatewaySku_ARM(subject NatGatewaySku_ARM) string {\n\t// Serialize to JSON\n\tbin, err := json.Marshal(subject)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\t// Deserialize back into memory\n\tvar actual NatGatewaySku_ARM\n\terr = json.Unmarshal(bin, &actual)\n\tif err != ... |
ChangeAccountLevelsAddr is a paid mutator transaction binding the contract method 0xe8f6bc2e. Solidity: function changeAccountLevelsAddr(accountLevelsAddr_ address) returns() | func (_EtherDelta *EtherDeltaTransactor) ChangeAccountLevelsAddr(opts *bind.TransactOpts, accountLevelsAddr_ common.Address) (*types.Transaction, error) {
return _EtherDelta.contract.Transact(opts, "changeAccountLevelsAddr", accountLevelsAddr_)
} | [
"func UpdateLogLevels(logLevel []LogLevel) {\n\t//it should retrieve active confguration from logger\n\t//it should compare with new entries one by one and apply if any changes\n\n\tactiveLogLevels, _ := getActiveLogLevel()\n\tcurrentLogLevel := createCurrentLogLevel(activeLogLevels, logLevel)\n\tfor _, level := ra... |
DeleteByQuery deletes documents matching the specified query. It will return an error for ES 2.x, because delete by query support was removed in those versions. | func (c *Client) DeleteByQuery(query interface{}, indexList []string, typeList []string, extraArgs url.Values) (*Response, error) {
version, err := c.Version()
if err != nil {
return nil, err
}
if version > "2" && version < "5" {
return nil, errors.New("ElasticSearch 2.x does not support delete by query")
}
r := Request{
Query: query,
IndexList: indexList,
TypeList: typeList,
Method: "DELETE",
API: "_query",
ExtraArgs: extraArgs,
}
if version > "5" {
r.API = "_delete_by_query"
r.Method = "POST"
}
return c.Do(&r)
} | [
"func (c *commentsQueryBuilder) Delete() (int64, error) {\n\tif c.err != nil {\n\t\treturn 0, c.err\n\t}\n\treturn c.builder.Delete()\n}",
"func (q dMessageEmbedQuery) DeleteAll() error {\n\tif q.Query == nil {\n\t\treturn errors.New(\"models: no dMessageEmbedQuery provided for delete all\")\n\t}\n\n\tqueries.Set... |
InternalAPI gets a URL base to send HTTP requests to. | func (c *Context) InternalAPI() *url.URL { return c.internalAPI } | [
"func Base(path string) string {\n\treturn std.Base(path)\n}",
"func newBaseClient() *baseClient {\n\treturn &baseClient{\n\t\thttpClient: http.DefaultClient,\n\t\tmethod: \"GET\",\n\t\theader: make(http.Header),\n\t}\n}",
"func (s *ClusterScope) BaseURI() string {\n\treturn s.ResourceManagerEndpoint\n}... |
XXX_OneofWrappers is for the internal use of the proto package. | func (*MetricsData) XXX_OneofWrappers() []interface{} {
return []interface{}{
(*MetricsData_BoolValue)(nil),
(*MetricsData_StringValue)(nil),
(*MetricsData_Int64Value)(nil),
(*MetricsData_DoubleValue)(nil),
(*MetricsData_DistributionValue)(nil),
}
} | [
"func (*CodebookSubType_MultiPanel) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookSubType_MultiPanel_TwoTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoOne_TypeI_MultiPa... |
Match matches input kv with kv, value will be wildcard matched depending on the user input | func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if strings.EqualFold(kv.Key, ikv.Key) {
return wildcard.Match(kv.Value, ikv.Value)
}
return false
} | [
"func (cont *Container) Match(query fl.Query) bool {\n\tfor k, q := range query {\n\t\tif !cont.MatchField(k, q...) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func match(got string, pattern *regexp.Regexp, msg string, note func(key string, value interface{})) error {\n\tif pattern.MatchString(got) {\n... |
Start starts embeded web server | func (srv *MonitorServer) Start() {
err := srv.ListenAndServe()
if err != nil {
log.Logger.Error("MonitorServer.Start():err in http.ListenAndServe():%s", err.Error())
abnormalExit()
}
} | [
"func (s *HttpServer) Start() error {\n\n\tif err := http.ListenAndServe(s.Config.Host+\":\"+s.Config.HTTPPort, s.ServeMux); err != nil {\n\t\tlog.Error().Err(err).Msg(\"Unable to start http server\")\n\t\treturn err\n\t}\n\treturn nil\n}",
"func startHTTPServer(app *AppContext) *http.Server {\n\n\tsrv := &http.S... |
NewClient takes in a format (ex. json), a connection type (ex. tcp) and an address where a hyrax server can be found (including the port). It also takes in a push channel, which can be nil if you want to ignore push messages. It returns a Client created from your specifications, or an error. | func NewClient(
le *types.ListenEndpoint, pushCh chan *types.Action) (Client, error) {
trans, err := translate.StringToTranslator(le.Format)
if err != nil {
return nil, err
}
switch le.Type {
case "tcp":
return net.NewTcpClient(trans, le.Addr, pushCh)
default:
return nil, errors.New("unknown connection type")
}
} | [
"func NewClient(connectionString string, baselineEncoding encoding.Encoding) (Client, error) {\n\tparts := strings.Split(connectionString, \"://\")\n\tif len(parts) < 2 {\n\t\treturn nil, errors.New(\"Connection string not in the correct format, must be transport://server:port\")\n\t}\n\n\ttransport := parts[0]\n\t... |
This function intSeq returns another function, which we define anonymously in the body of nextInt. The returned function closes over the variable i to form a closure. | func nextInt() func() int {
i := 0
return func() int {
i++
return i
}
} | [
"func (v Varint) Iterator() func() (n int64, ok bool) {\n\tnext := v.Uvarint.Iterator()\n\treturn func() (int64, bool) {\n\t\tu, ok := next()\n\t\treturn int64(u), ok\n\t}\n}",
"func NewIntCode(prog []int, in io.Reader, out io.Writer) *IntCode {\n\t// please don't mutate my input\n\tb := make([]int, len(prog))\n\... |
SetId gets a reference to the given string and assigns it to the Id field. | func (o *MicrosoftGraphWorkbookComment) SetId(v string) {
o.Id = &v
} | [
"func (obj *SObject) setID(id string) {\n\t(*obj)[sobjectIDKey] = id\n}",
"func (s *DescribeTestSetInput) SetTestSetId(v string) *DescribeTestSetInput {\n\ts.TestSetId = &v\n\treturn s\n}",
"func SetID(ctx context.Context, requestID string) context.Context {\n\treturn context.WithValue(ctx, requestIDKey, reques... |
GetConfigMap returns a map[string]map[string]string which contains the option/value pairs for each config section. | func (c *ConfigParser) GetConfigMap() (confmap map[string]map[string]string, err error) {
confmap = make(map[string]map[string]string)
err = c.Parse()
if err != nil {
return
}
for section, secdata := range c.sections {
confmap[section] = make(map[string]string)
for option, value := range secdata.options {
confmap[section][option] = value
}
}
return
} | [
"func ConfigMap(\n\tinCluster *v1beta1.PostgresCluster,\n\toutConfigMap *corev1.ConfigMap,\n) error {\n\tif inCluster.Spec.UserInterface == nil || inCluster.Spec.UserInterface.PGAdmin == nil {\n\t\t// pgAdmin is disabled; there is nothing to do.\n\t\treturn nil\n\t}\n\n\tinitialize.StringMap(&outConfigMap.Data)\n\n... |
NewRoleFindByIDBadRequest creates a RoleFindByIDBadRequest with default headers values | func NewRoleFindByIDBadRequest() *RoleFindByIDBadRequest {
return &RoleFindByIDBadRequest{}
} | [
"func NewSearchInventoryBadRequest() *SearchInventoryBadRequest {\n\treturn &SearchInventoryBadRequest{}\n}",
"func NewFindMaterialByIDForbidden() *FindMaterialByIDForbidden {\n\treturn &FindMaterialByIDForbidden{}\n}",
"func (p *API) FindByID(c *gin.Context) {\n\tif p.Engine.CheckAccess(c, \"roles:read\") {\n\... |
SetScriptIdentifier sets the ScriptIdentifier field's value. | func (s *Result) SetScriptIdentifier(v string) *Result {
s.ScriptIdentifier = &v
return s
} | [
"func (o *SparseClaims) SetIdentifier(id string) {\n\n\tif id != \"\" {\n\t\to.ID = &id\n\t} else {\n\t\to.ID = nil\n\t}\n}",
"func (o *CloudSnapshotAccount) SetIdentifier(id string) {\n\n}",
"func (s *NASInstance) SetNASInstanceIdentifier(v string) *NASInstance {\n\ts.NASInstanceIdentifier = &v\n\treturn s\n}"... |
GetDNSOverTLS obtains if the DNS over TLS should be enabled from the environment variable DOT | func (r *reader) GetDNSOverTLS() (DNSOverTLS bool, err error) { //nolint:gocritic
return r.envParams.GetOnOff("DOT", libparams.Default("on"))
} | [
"func (c *Cert) TLS() *tls.Certificate {\n\tif c.leaf == nil {\n\t\tlog.Panicf(\"cert TLS called with nil leaf!\")\n\t}\n\treturn c.leaf\n}",
"func TLSConn(protocol string, addr string, conf *tls.Config) (*tls.Conn, error) {\n\tnewTLS, err := tls.Dial(protocol, addr, conf)\n\tif err != nil {\n\t\treturn nil, err\... |
UploadDifferences will upload the files that are missing from the remote index | func UploadDifferences(localIndex, remoteIndex *Index, interval int, store IndexStore, getFile FileGetter) error {
diff := localIndex.Diff(remoteIndex)
toUpload := CopyIndex(remoteIndex)
count := 0
uploadIndex := func() error {
r, _ := toUpload.Encode()
doLog("Uploading index as %s\n", indexFile)
err := store.Save(indexFile, bytes.NewBufferString(r))
if err != nil {
return err
}
return nil
}
for p, srcFile := range diff.Files {
r := getFile(p)
defer func() {
_ = r.Close()
}()
doLog("Uploading %s as %s\n", p, srcFile.Key)
err := store.Save(srcFile.Key, r)
if err != nil {
return err
}
count++
toUpload.Add(p, srcFile)
if count == interval {
err := uploadIndex()
if err != nil {
return err
}
count = 0
}
}
err := uploadIndex()
if err != nil {
return err
}
return nil
} | [
"func handleUpload(ctx *web.Context, updateURL chan<- *urlUpdateMsg) string {\n\t//TODO: Implemente limits with settings.ini or something\n\terr := ctx.Request.ParseMultipartForm(100 * 1024 * 1024)\n\tif err != nil {\n\t\treturn \"Error handling form!\\n\"\n\t}\n\tform := ctx.Request.MultipartForm\n\n\t//Loop throu... |
doBeforeUpdateHooks executes all "before Update" hooks. | func (o *RowerGroup) doBeforeUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range rowerGroupBeforeUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
} | [
"func (o *AssetRevision) doBeforeUpdateHooks(exec boil.Executor) (err error) {\n\tfor _, hook := range assetRevisionBeforeUpdateHooks {\n\t\tif err := hook(exec, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (o *AuthToken) doBeforeUpdateHooks(exec boil.Executor) (err error) {\n\tfor _,... |
ParseRecordFlags parses simple K=V pairs from a comment on a record. Any bare words are included and are assumed to have a "" value. | func ParseRecordFlags(str string) (RecordFlags, error) {
var res RecordFlags
scan := bufio.NewScanner(strings.NewReader((str)))
scan.Split(bufio.ScanWords)
for scan.Scan() {
vs := strings.SplitN(scan.Text(), "=", 2)
k := vs[0]
v := ""
if len(vs) == 2 {
v = vs[1]
}
if res == nil {
res = make(RecordFlags)
}
res[k] = v
}
if err := scan.Err(); err != nil {
return nil, err
}
return res, nil
} | [
"func parseScopeFlag(flag string) (scopeFlag, error) {\n\tif flag == \"\" {\n\t\treturn scopeFlag{}, errfmt.WrapError(InvalidFlagEmpty())\n\t}\n\n\t// get first idx of any operator\n\toperatorIdx := strings.IndexAny(flag, \"=!<>\")\n\tif operatorIdx == -1 || // no operator, as a set flag\n\t\t(operatorIdx == 0 && f... |
NOTE: Not implement yet Sets a DSP unit's binary data parameter by index. To find out the parameter names and range, see the see also field. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo". | func (d *DSP) SetParameterData(index C.int, data *interface{}, length C.uint) error {
//FMOD_RESULT F_API FMOD_DSP_SetParameterData(FMOD_DSP *dsp, int index, void *data, unsigned int length);
return ErrNoImpl
} | [
"func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}",
"func (cmd *VehicleSpeed) SetValue(result *Result) error {\n\tpayload, err := result... |
destroyDeployment shuts down a deployments instances, and removes all its data. It expects the (absolute) parent path, e.g. the one above the repo dir. | func destroyDeployment(toRemove string) {
log.Debug("Destroying deployment %s", toRemove)
oldPwd := sh.Pwd()
toRemoveRepo := path.Join(toRemove, sh.Basename(repoURL))
sh.Cd(toRemoveRepo)
log.Debugf("Actually destroying resources now")
cloudRe := regexp.MustCompile(`(gce|aws|digitalocean|openstack|softlayer)`)
if cloudRe.MatchString(toRemove) {
log.Debug("Destroying terraformed resources in %s", toRemoveRepo)
terraformDestroy(toRemoveRepo)
} else {
log.Debug("Destroying vagrant box in %s", toRemoveRepo)
sh.SetE(exec.Command("vagrant", "destroy", "-f"))
}
sh.Cd(oldPwd)
log.Debugf("Removing leftovers in %s", toRemove)
sh.RmR(toRemove)
log.Debug("Finished destruction process")
} | [
"func (s *deploymentServer) updateDeployment(ctx context.Context, deployment *appsv1.Deployment, repo *Repository) (bool, error) {\n\tcontainers := deployment.Spec.Template.Spec.InitContainers\n\n\tif len(containers) > 0 {\n\t\tfmt.Println(\"deployment \" + deployment.Namespace + \".\" + deployment.Name + \" has in... |
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IdlerList. | func (in *IdlerList) DeepCopy() *IdlerList {
if in == nil {
return nil
}
out := new(IdlerList)
in.DeepCopyInto(out)
return out
} | [
"func (o ImageVulnerabilitiesList) Copy() elemental.Identifiables {\n\n\tcopy := append(ImageVulnerabilitiesList{}, o...)\n\treturn ©\n}",
"func (o APIChecksList) Copy() elemental.Identifiables {\n\n\tcopy := append(APIChecksList{}, o...)\n\treturn ©\n}",
"func (in *TraincrdList) DeepCopy() *TraincrdLis... |
NewStock creates a new Stock datamapper and returns a pointer to it | func NewStock(dbSession *sql.DB) *Stock {
return &Stock{
db: dbSession,
}
} | [
"func NewStore()(*Store) {\n m := &Store{\n Entity: *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.NewEntity(),\n }\n return m\n}",
"func (s *Stock) Insert(stockModel model.Model) *errors.Error {\n\tstockModelObj, ok := stockModel.(*model.Stock)\n\tif false == ok {\n\t\treturn ... |
IsTCPPortAvailable returns a flag indicating whether or not a TCP port is available. | func IsTCPPortAvailable(port int) bool {
if port < minTCPPort || port > maxTCPPort {
return false
}
conn, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return false
}
conn.Close()
return true
} | [
"func WaitForTCP(ctx context.Context, rAddr string) error {\n\tdialer := net.Dialer{}\n\tconn, err := dialer.DialContext(ctx, \"tcp\", rAddr)\n\t//For loop to get around OS Dial Timeout\n\tfor err != nil {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\t\tconn, err = dialer.Dia... |
Funcion que imprime la representacion en cadena de un vertice | func (v Vertex) Print() {
fmt.Printf("Vertice: %d\n Feromona Ini: %f\n Feromona Act: %f\n", v.index, v.pheromone_init, v.pheromone)
} | [
"func FromUnidirectionalEdge(\n\tedge H3Index,\n) (origin, destination H3Index) {\n\tcout := make([]C.H3Index, 2)\n\tC.getH3IndexesFromUnidirectionalEdge(edge, &cout[0])\n\torigin = H3Index(cout[0])\n\tdestination = H3Index(cout[1])\n\treturn\n}",
"func Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.x*v.x + v.y*v.... |
ContextValidate validates this transit gateway location based on context it is used | func (m *TransitGatewayLocation) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
} | [
"func (o *GetPastUsageBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}",
"func (m *ClusterMetroAvailabilityChecklistSecondaryZone) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateItems(ctx, formats... |
NewInstall creates a new Install object with given configuration. | func NewInstall(cfg *Configuration) *Install {
return &Install{
cfg: cfg,
}
} | [
"func New(log log.Logger, c *Config) (integrations.Integration, error) {\n\tdsn, err := c.getDataSourceNames()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\te := exporter.NewExporter(\n\t\tdsn,\n\t\tlog,\n\t\texporter.DisableDefaultMetrics(c.DisableDefaultMetrics),\n\t\texporter.WithUserQueriesPath(c.QueryPath)... |
LenStrs returns the space requirecd by PutStrs | func LenStrs(ss []string) int {
n := 2
for _, s := range ss {
n += LenStr(s)
}
return n
} | [
"func StringLength(str string, min int, max int) bool {\n\tslen := utf8.RuneCountInString(str)\n\treturn slen >= min && slen <= max\n}",
"func getMaxLen(strs []string) int {\n\tmaxLen := 0\n\tfor _, str := range strs {\n\t\tif len(str) > maxLen {\n\t\t\tmaxLen = len(str)\n\t\t}\n\t}\n\treturn maxLen\n}",
"func ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.